Skip to main content

lean_ctx_ext/core/
benchmark.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::HashMap;
3use std::path::{Path, PathBuf};
4use std::time::Instant;
5
6use walkdir::WalkDir;
7
8use crate::core::compressor;
9use crate::core::deps;
10use crate::core::entropy;
11use crate::core::preservation;
12use crate::core::signatures;
13use crate::core::tokens::count_tokens;
14
15const COST_PER_TOKEN: f64 = crate::core::stats::DEFAULT_INPUT_PRICE_PER_M / 1_000_000.0;
16const MAX_FILE_SIZE: u64 = 100 * 1024;
17const MAX_FILES: usize = 50;
18fn cache_hit_tokens() -> usize {
19    let stub = "F1=src/example.rs [unchanged, 500L, use cached context]";
20    count_tokens(stub)
21}
22
23// ── Types ───────────────────────────────────────────────────
24
25#[derive(Debug, Clone)]
26pub(crate) struct ModeMeasurement {
27    pub(crate) mode: String,
28    pub(crate) tokens: usize,
29    pub(crate) savings_pct: f64,
30    pub(crate) latency_us: u64,
31    pub(crate) preservation_score: f64,
32}
33
34#[derive(Debug, Clone)]
35pub(crate) struct FileMeasurement {
36    pub(crate) path: String,
37    pub(crate) ext: String,
38    pub(crate) raw_tokens: usize,
39    pub(crate) modes: Vec<ModeMeasurement>,
40}
41
42#[derive(Debug, Clone)]
43pub(crate) struct LanguageStats {
44    pub(crate) ext: String,
45    pub(crate) count: usize,
46    pub(crate) total_tokens: usize,
47    pub(crate) best_mode: String,
48    pub(crate) best_mode_tokens: usize,
49    pub(crate) best_savings_pct: f64,
50}
51
52#[derive(Debug, Clone)]
53pub(crate) struct ModeSummary {
54    pub(crate) mode: String,
55    pub(crate) total_compressed_tokens: usize,
56    pub(crate) avg_savings_pct: f64,
57    pub(crate) avg_latency_us: u64,
58    pub(crate) avg_preservation: f64,
59}
60
61#[derive(Debug, Clone)]
62pub(crate) struct SessionSimResult {
63    pub(crate) raw_tokens: usize,
64    pub(crate) lean_tokens: usize,
65    pub(crate) lean_ccp_tokens: usize,
66    pub(crate) raw_cost: f64,
67    pub(crate) lean_cost: f64,
68    pub(crate) ccp_cost: f64,
69}
70
71#[derive(Debug, Clone)]
72pub struct ProjectBenchmark {
73    pub(crate) root: String,
74    pub(crate) files_scanned: usize,
75    pub(crate) files_measured: usize,
76    pub(crate) total_raw_tokens: usize,
77    pub(crate) languages: Vec<LanguageStats>,
78    pub(crate) mode_summaries: Vec<ModeSummary>,
79    pub(crate) session_sim: SessionSimResult,
80    pub(crate) file_results: Vec<FileMeasurement>,
81}
82
83// ── Scanner ─────────────────────────────────────────────────
84
85fn is_skipped_dir(name: &str) -> bool {
86    matches!(
87        name,
88        "node_modules"
89            | ".git"
90            | "target"
91            | "dist"
92            | "build"
93            | ".next"
94            | ".nuxt"
95            | "__pycache__"
96            | ".cache"
97            | "coverage"
98            | "vendor"
99            | ".svn"
100            | ".hg"
101    )
102}
103
104fn is_text_ext(ext: &str) -> bool {
105    matches!(
106        ext,
107        "rs" | "ts"
108            | "tsx"
109            | "js"
110            | "jsx"
111            | "py"
112            | "go"
113            | "java"
114            | "c"
115            | "cpp"
116            | "h"
117            | "hpp"
118            | "cs"
119            | "kt"
120            | "swift"
121            | "rb"
122            | "php"
123            | "vue"
124            | "svelte"
125            | "html"
126            | "css"
127            | "scss"
128            | "less"
129            | "json"
130            | "yaml"
131            | "yml"
132            | "toml"
133            | "xml"
134            | "md"
135            | "txt"
136            | "sh"
137            | "bash"
138            | "zsh"
139            | "fish"
140            | "sql"
141            | "graphql"
142            | "proto"
143            | "ex"
144            | "exs"
145            | "zig"
146            | "lua"
147            | "r"
148            | "R"
149            | "dart"
150            | "scala"
151    )
152}
153
154fn scan_project(root: &str) -> Vec<PathBuf> {
155    let mut files: Vec<(PathBuf, u64)> = Vec::new();
156
157    for entry in WalkDir::new(root)
158        .max_depth(8)
159        .into_iter()
160        .filter_entry(|e| {
161            let name = e.file_name().to_string_lossy();
162            if e.file_type().is_dir() {
163                if e.depth() > 0 && name.starts_with('.') {
164                    return false;
165                }
166                return !is_skipped_dir(&name);
167            }
168            true
169        })
170    {
171        let Ok(entry) = entry else { continue };
172
173        if entry.file_type().is_dir() {
174            continue;
175        }
176
177        let path = entry.path().to_path_buf();
178        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
179
180        if !is_text_ext(ext) {
181            continue;
182        }
183
184        let size = entry.metadata().map_or(0, |m| m.len());
185        if size == 0 || size > MAX_FILE_SIZE {
186            continue;
187        }
188
189        files.push((path, size));
190    }
191
192    files.sort_by_key(|x| std::cmp::Reverse(x.1));
193
194    let mut selected = Vec::new();
195    let mut ext_counts: HashMap<String, usize> = HashMap::new();
196
197    for (path, _size) in &files {
198        if selected.len() >= MAX_FILES {
199            break;
200        }
201        let ext = path
202            .extension()
203            .and_then(|e| e.to_str())
204            .unwrap_or("")
205            .to_string();
206        let count = ext_counts.entry(ext.clone()).or_insert(0);
207        if *count < 10 {
208            *count += 1;
209            selected.push(path.clone());
210        }
211    }
212
213    selected
214}
215
216// ── Measurement ─────────────────────────────────────────────
217
218fn measure_mode(content: &str, ext: &str, mode: &str, raw_tokens: usize) -> ModeMeasurement {
219    let start = Instant::now();
220
221    let compressed = match mode {
222        "map" => {
223            let sigs = signatures::extract_signatures(content, ext);
224            let dep_info = deps::extract_deps(content, ext);
225            let mut parts = Vec::new();
226            if !dep_info.imports.is_empty() {
227                parts.push(format!("deps: {}", dep_info.imports.join(", ")));
228            }
229            let key_refs: Vec<&signatures::Signature> = sigs
230                .iter()
231                .filter(|s| s.is_exported || s.indent == 0)
232                .collect();
233            // Drop exports the API already lists so the benchmark measures the
234            // same deduped map the renderers emit (mirrors ctx_read map, #361).
235            let extra_exports = signatures::exports_not_in_signatures(&dep_info.exports, &key_refs);
236            if !extra_exports.is_empty() {
237                parts.push(format!("exports: {}", extra_exports.join(", ")));
238            }
239            if !key_refs.is_empty() {
240                let key_sigs: Vec<String> = key_refs.iter().map(|s| s.to_compact()).collect();
241                parts.push(key_sigs.join("\n"));
242            }
243            parts.join("\n")
244        }
245        "signatures" => {
246            let sigs = signatures::extract_signatures(content, ext);
247            sigs.iter()
248                .map(super::signatures::Signature::to_compact)
249                .collect::<Vec<_>>()
250                .join("\n")
251        }
252        "aggressive" => compressor::aggressive_compress(content, Some(ext)),
253        // Deterministic variant: benchmark numbers feed the scorecard's
254        // reproducibility digest (#211) and must not depend on whether the
255        // shared embedding engine happens to be loaded in this process.
256        "entropy" => entropy::entropy_compress_deterministic(content).output,
257        "cache_hit" => format!(
258            "F1=src/file.{ext} [unchanged, {}L, use cached context]",
259            content.lines().count()
260        ),
261        _ => content.to_string(),
262    };
263
264    let latency = start.elapsed();
265    let tokens = count_tokens(&compressed);
266
267    let savings_pct = if raw_tokens > 0 {
268        (1.0 - tokens as f64 / raw_tokens as f64) * 100.0
269    } else {
270        0.0
271    };
272
273    let preservation_score = if mode == "cache_hit" {
274        -1.0
275    } else {
276        preservation::measure(content, &compressed, ext).overall()
277    };
278
279    ModeMeasurement {
280        mode: mode.to_string(),
281        tokens,
282        savings_pct,
283        latency_us: latency.as_micros() as u64,
284        preservation_score,
285    }
286}
287
288fn measure_file(path: &Path, root: &str) -> Option<FileMeasurement> {
289    let content = std::fs::read_to_string(path).ok()?;
290    if content.is_empty() {
291        return None;
292    }
293
294    let ext = path
295        .extension()
296        .and_then(|e| e.to_str())
297        .unwrap_or("")
298        .to_string();
299
300    let raw_tokens = count_tokens(&content);
301    if raw_tokens == 0 {
302        return None;
303    }
304
305    let modes = ["map", "signatures", "aggressive", "entropy", "cache_hit"];
306    let measurements: Vec<ModeMeasurement> = modes
307        .iter()
308        .map(|m| measure_mode(&content, &ext, m, raw_tokens))
309        .collect();
310
311    let display_path = path
312        .strip_prefix(root)
313        .unwrap_or(path)
314        .to_string_lossy()
315        .to_string();
316
317    Some(FileMeasurement {
318        path: display_path,
319        ext,
320        raw_tokens,
321        modes: measurements,
322    })
323}
324
325// ── Aggregation ─────────────────────────────────────────────
326
327/// Structural modes (map, signatures) only produce meaningful output for
328/// programming languages with parseable code structures. For data/markup
329/// files, these modes return near-empty output that would be misleading
330/// as "compression". Only `aggressive` and `entropy` are honest for these.
331fn is_mode_applicable_for_ext(mode: &str, ext: &str, tokens: usize) -> bool {
332    if tokens == 0 {
333        return false;
334    }
335    let is_structural_mode = matches!(mode, "map" | "signatures");
336    if !is_structural_mode {
337        return true;
338    }
339    // Extensions with actual code structures (functions, classes, types)
340    let code_exts = [
341        "rs", "ts", "tsx", "js", "jsx", "py", "go", "java", "kt", "c", "cpp", "h", "hpp", "cs",
342        "rb", "swift", "scala", "zig", "lua", "php", "dart", "ex", "exs", "elm", "hs", "ml",
343        "svelte", "vue", "sh", "bash", "zsh",
344    ];
345    code_exts.contains(&ext)
346}
347
348fn aggregate_languages(files: &[FileMeasurement]) -> Vec<LanguageStats> {
349    struct LangAccum {
350        count: usize,
351        total_tokens: usize,
352        mode_tokens: HashMap<String, usize>,
353    }
354
355    let mut map: HashMap<String, LangAccum> = HashMap::new();
356    for f in files {
357        let entry = map.entry(f.ext.clone()).or_insert_with(|| LangAccum {
358            count: 0,
359            total_tokens: 0,
360            mode_tokens: HashMap::new(),
361        });
362        entry.count += 1;
363        entry.total_tokens += f.raw_tokens;
364        for m in &f.modes {
365            *entry.mode_tokens.entry(m.mode.clone()).or_insert(0) += m.tokens;
366        }
367    }
368
369    let mut stats: Vec<LanguageStats> = map
370        .into_iter()
371        .map(|(ext, acc)| {
372            let (best_mode, best_tokens) = acc
373                .mode_tokens
374                .iter()
375                .filter(|(m, _)| m.as_str() != "cache_hit")
376                .filter(|(m, t)| is_mode_applicable_for_ext(m, &ext, **t))
377                .min_by_key(|(_, t)| **t)
378                .map_or_else(
379                    || ("full".to_string(), acc.total_tokens),
380                    |(m, t)| (m.clone(), *t),
381                );
382
383            let savings = if acc.total_tokens > 0 {
384                (1.0 - best_tokens as f64 / acc.total_tokens as f64) * 100.0
385            } else {
386                0.0
387            };
388
389            LanguageStats {
390                ext,
391                count: acc.count,
392                total_tokens: acc.total_tokens,
393                best_mode,
394                best_mode_tokens: best_tokens,
395                best_savings_pct: savings,
396            }
397        })
398        .collect();
399    stats.sort_by_key(|x| std::cmp::Reverse(x.total_tokens));
400    stats
401}
402
403fn aggregate_modes(files: &[FileMeasurement]) -> Vec<ModeSummary> {
404    let mode_names = ["map", "signatures", "aggressive", "entropy", "cache_hit"];
405    let mut summaries = Vec::new();
406
407    for mode_name in &mode_names {
408        let mut total_tokens = 0usize;
409        let mut total_savings = 0.0f64;
410        let mut total_latency = 0u64;
411        let mut total_preservation = 0.0f64;
412        let mut preservation_count = 0usize;
413        let mut count = 0usize;
414
415        for f in files {
416            if let Some(m) = f.modes.iter().find(|m| m.mode == *mode_name) {
417                total_tokens += m.tokens;
418                total_savings += m.savings_pct;
419                total_latency += m.latency_us;
420                if m.preservation_score >= 0.0 {
421                    total_preservation += m.preservation_score;
422                    preservation_count += 1;
423                }
424                count += 1;
425            }
426        }
427
428        if count == 0 {
429            continue;
430        }
431
432        summaries.push(ModeSummary {
433            mode: mode_name.to_string(),
434            total_compressed_tokens: total_tokens,
435            avg_savings_pct: total_savings / count as f64,
436            avg_latency_us: total_latency / count as u64,
437            avg_preservation: if preservation_count > 0 {
438                total_preservation / preservation_count as f64
439            } else {
440                -1.0
441            },
442        });
443    }
444
445    summaries
446}
447
448// ── Session Simulation ──────────────────────────────────────
449
450/// Honest CCP resume size (GL #573): measure what `ctx_session load` actually
451/// emits for the latest real session instead of asserting a constant. The
452/// model value is the documented fallback for machines without session history.
453fn measured_ccp_resume_tokens() -> usize {
454    const RESUME_CCP_MODEL_TOKENS: usize = 400;
455    crate::core::session::SessionState::load_latest().map_or(RESUME_CCP_MODEL_TOKENS, |s| {
456        crate::core::tokens::count_tokens(&format!("Session loaded.\n{}", s.format_compact()))
457    })
458}
459
460fn simulate_session(files: &[FileMeasurement]) -> SessionSimResult {
461    if files.is_empty() {
462        return SessionSimResult {
463            raw_tokens: 0,
464            lean_tokens: 0,
465            lean_ccp_tokens: 0,
466            raw_cost: 0.0,
467            lean_cost: 0.0,
468            ccp_cost: 0.0,
469        };
470    }
471
472    let file_count = files.len().min(15);
473    let selected = &files[..file_count];
474
475    let first_read_raw: usize = selected.iter().map(|f| f.raw_tokens).sum();
476
477    let first_read_lean: usize = selected
478        .iter()
479        .enumerate()
480        .map(|(i, f)| {
481            let mode = if i % 3 == 0 { "aggressive" } else { "map" };
482            f.modes
483                .iter()
484                .find(|m| m.mode == mode)
485                .map_or(f.raw_tokens, |m| m.tokens)
486        })
487        .sum();
488
489    let cache_reread_count = 10usize.min(file_count);
490    let cache_raw: usize = selected[..cache_reread_count]
491        .iter()
492        .map(|f| f.raw_tokens)
493        .sum();
494    let cache_lean: usize = cache_reread_count * cache_hit_tokens();
495
496    let shell_count = 8usize;
497    let shell_raw = shell_count * 500;
498    let shell_lean = shell_count * 200;
499
500    let resume_raw: usize = selected.iter().map(|f| f.raw_tokens).sum();
501    let resume_lean: usize = selected
502        .iter()
503        .map(|f| {
504            f.modes
505                .iter()
506                .find(|m| m.mode == "map")
507                .map_or(f.raw_tokens, |m| m.tokens)
508        })
509        .sum();
510    let resume_ccp = measured_ccp_resume_tokens();
511
512    let raw_total = first_read_raw + cache_raw + shell_raw + resume_raw;
513    let lean_total = first_read_lean + cache_lean + shell_lean + resume_lean;
514    let ccp_total = first_read_lean + cache_lean + shell_lean + resume_ccp;
515
516    SessionSimResult {
517        raw_tokens: raw_total,
518        lean_tokens: lean_total,
519        lean_ccp_tokens: ccp_total,
520        raw_cost: raw_total as f64 * COST_PER_TOKEN,
521        lean_cost: lean_total as f64 * COST_PER_TOKEN,
522        ccp_cost: ccp_total as f64 * COST_PER_TOKEN,
523    }
524}
525
526// ── Public API ──────────────────────────────────────────────
527
528pub fn run_project_benchmark(path: &str) -> ProjectBenchmark {
529    let root = if path.is_empty() { "." } else { path };
530    let scanned = scan_project(root);
531    let files_scanned = scanned.len();
532
533    let file_results: Vec<FileMeasurement> = scanned
534        .iter()
535        .filter_map(|p| measure_file(p, root))
536        .collect();
537
538    let total_raw_tokens: usize = file_results.iter().map(|f| f.raw_tokens).sum();
539    let languages = aggregate_languages(&file_results);
540    let mode_summaries = aggregate_modes(&file_results);
541    let session_sim = simulate_session(&file_results);
542
543    ProjectBenchmark {
544        root: root.to_string(),
545        files_scanned,
546        files_measured: file_results.len(),
547        total_raw_tokens,
548        languages,
549        mode_summaries,
550        session_sim,
551        file_results,
552    }
553}
554
555// ── Report: Terminal ────────────────────────────────────────
556
557pub fn format_terminal(b: &ProjectBenchmark) -> String {
558    let mut out = Vec::new();
559    let sep = "\u{2550}".repeat(66);
560
561    out.push(sep.clone());
562    out.push(format!("  lean-ctx Benchmark — {}", b.root));
563    out.push(sep.clone());
564
565    let lang_summary: Vec<String> = b
566        .languages
567        .iter()
568        .take(5)
569        .map(|l| format!("{} {}", l.count, l.ext))
570        .collect();
571    out.push(format!(
572        "  Scanned: {} files ({})",
573        b.files_measured,
574        lang_summary.join(", ")
575    ));
576    out.push(format!(
577        "  Total raw tokens: {}",
578        format_num(b.total_raw_tokens)
579    ));
580    out.push(String::new());
581
582    out.push("  Compression by Language:".to_string());
583    out.push(format!(
584        "  {:<10} {:>6} {:>10} {:>10} {:>10} {:>10}",
585        "Lang", "Files", "Raw Tok", "Best Mode", "Compressed", "Savings"
586    ));
587    out.push(format!("  {}", "\u{2500}".repeat(62)));
588    for l in &b.languages {
589        out.push(format!(
590            "  {:<10} {:>6} {:>10} {:>10} {:>10} {:>9.1}%",
591            l.ext,
592            l.count,
593            format_num(l.total_tokens),
594            l.best_mode,
595            format_num(l.best_mode_tokens),
596            l.best_savings_pct,
597        ));
598    }
599    out.push(String::new());
600
601    out.push("  Mode Performance:".to_string());
602    out.push(format!(
603        "  {:<14} {:>10} {:>10} {:>10} {:>10}",
604        "Mode", "Tokens", "Savings", "Latency", "Quality"
605    ));
606    out.push(format!("  {}", "\u{2500}".repeat(58)));
607
608    for m in &b.mode_summaries {
609        let qual = if m.avg_preservation < 0.0 {
610            "N/A".to_string()
611        } else {
612            format!("{:.1}%", m.avg_preservation * 100.0)
613        };
614        let latency = if m.avg_latency_us > 1000 {
615            format!("{:.1}ms", m.avg_latency_us as f64 / 1000.0)
616        } else {
617            format!("{}μs", m.avg_latency_us)
618        };
619        out.push(format!(
620            "  {:<14} {:>10} {:>9.1}% {:>10} {:>10}",
621            m.mode,
622            format_num(m.total_compressed_tokens),
623            m.avg_savings_pct,
624            latency,
625            qual,
626        ));
627    }
628
629    out.push(String::new());
630    out.push("  Session Simulation (30-min coding):".to_string());
631    out.push(format!(
632        "  {:<24} {:>10} {:>10} {:>10}",
633        "Approach", "Tokens", "Cost", "Savings"
634    ));
635    out.push(format!("  {}", "\u{2500}".repeat(58)));
636
637    let s = &b.session_sim;
638    out.push(format!(
639        "  {:<24} {:>10} {:>10} {:>10}",
640        "Raw (no compression)",
641        format_num(s.raw_tokens),
642        format!("${:.3}", s.raw_cost),
643        "\u{2014}",
644    ));
645
646    let lean_pct = if s.raw_tokens > 0 {
647        (1.0 - s.lean_tokens as f64 / s.raw_tokens as f64) * 100.0
648    } else {
649        0.0
650    };
651    out.push(format!(
652        "  {:<24} {:>10} {:>10} {:>9.1}%",
653        "lean-ctx (no CCP)",
654        format_num(s.lean_tokens),
655        format!("${:.3}", s.lean_cost),
656        lean_pct,
657    ));
658
659    let ccp_pct = if s.raw_tokens > 0 {
660        (1.0 - s.lean_ccp_tokens as f64 / s.raw_tokens as f64) * 100.0
661    } else {
662        0.0
663    };
664    out.push(format!(
665        "  {:<24} {:>10} {:>10} {:>9.1}%",
666        "lean-ctx + CCP",
667        format_num(s.lean_ccp_tokens),
668        format!("${:.3}", s.ccp_cost),
669        ccp_pct,
670    ));
671
672    out.push(sep.clone());
673    out.join("\n")
674}
675
676// ── Report: Markdown ────────────────────────────────────────
677
678pub fn format_markdown(b: &ProjectBenchmark) -> String {
679    let mut out = Vec::new();
680
681    out.push("# lean-ctx Benchmark Report".to_string());
682    out.push(String::new());
683    out.push(format!("**Project:** `{}`", b.root));
684    out.push(format!("**Files measured:** {}", b.files_measured));
685    out.push(format!(
686        "**Total raw tokens:** {}",
687        format_num(b.total_raw_tokens)
688    ));
689    out.push(String::new());
690
691    out.push("## Compression by Language".to_string());
692    out.push(String::new());
693    out.push("| Language | Files | Raw Tokens | Best Mode | Compressed | Savings |".to_string());
694    out.push("|----------|------:|-----------:|-----------|----------:|--------:|".to_string());
695    for l in &b.languages {
696        out.push(format!(
697            "| {} | {} | {} | {} | {} | {:.1}% |",
698            l.ext,
699            l.count,
700            format_num(l.total_tokens),
701            l.best_mode,
702            format_num(l.best_mode_tokens),
703            l.best_savings_pct,
704        ));
705    }
706    out.push(String::new());
707
708    out.push("## Mode Performance".to_string());
709    out.push(String::new());
710    out.push("| Mode | Tokens | Savings | Latency | Quality |".to_string());
711    out.push("|------|-------:|--------:|--------:|--------:|".to_string());
712    for m in &b.mode_summaries {
713        let qual = if m.avg_preservation < 0.0 {
714            "N/A".to_string()
715        } else {
716            format!("{:.1}%", m.avg_preservation * 100.0)
717        };
718        let latency = if m.avg_latency_us > 1000 {
719            format!("{:.1}ms", m.avg_latency_us as f64 / 1000.0)
720        } else {
721            format!("{}μs", m.avg_latency_us)
722        };
723        out.push(format!(
724            "| {} | {} | {:.1}% | {} | {} |",
725            m.mode,
726            format_num(m.total_compressed_tokens),
727            m.avg_savings_pct,
728            latency,
729            qual
730        ));
731    }
732    out.push(String::new());
733
734    out.push("## Session Simulation (30-min coding)".to_string());
735    out.push(String::new());
736    out.push("| Approach | Tokens | Cost | Savings |".to_string());
737    out.push("|----------|-------:|-----:|--------:|".to_string());
738
739    let s = &b.session_sim;
740    out.push(format!(
741        "| Raw (no compression) | {} | ${:.3} | — |",
742        format_num(s.raw_tokens),
743        s.raw_cost
744    ));
745
746    let lean_pct = if s.raw_tokens > 0 {
747        (1.0 - s.lean_tokens as f64 / s.raw_tokens as f64) * 100.0
748    } else {
749        0.0
750    };
751    out.push(format!(
752        "| lean-ctx (no CCP) | {} | ${:.3} | {:.1}% |",
753        format_num(s.lean_tokens),
754        s.lean_cost,
755        lean_pct
756    ));
757
758    let ccp_pct = if s.raw_tokens > 0 {
759        (1.0 - s.lean_ccp_tokens as f64 / s.raw_tokens as f64) * 100.0
760    } else {
761        0.0
762    };
763    out.push(format!(
764        "| lean-ctx + CCP | {} | ${:.3} | {:.1}% |",
765        format_num(s.lean_ccp_tokens),
766        s.ccp_cost,
767        ccp_pct
768    ));
769
770    out.push(String::new());
771    out.push(format!(
772        "*Generated by lean-ctx benchmark v{} — https://leanctx.com*",
773        env!("CARGO_PKG_VERSION")
774    ));
775
776    out.join("\n")
777}
778
779// ── Report: JSON ────────────────────────────────────────────
780
781pub fn format_json(b: &ProjectBenchmark) -> String {
782    let modes: Vec<serde_json::Value> = b.mode_summaries.iter().map(|m| {
783        serde_json::json!({
784            "mode": m.mode,
785            "total_compressed_tokens": m.total_compressed_tokens,
786            "avg_savings_pct": round2(m.avg_savings_pct),
787            "avg_latency_us": m.avg_latency_us,
788            "avg_preservation": if m.avg_preservation < 0.0 { serde_json::Value::Null } else { serde_json::json!(round2(m.avg_preservation * 100.0)) },
789        })
790    }).collect();
791
792    let languages: Vec<serde_json::Value> = b
793        .languages
794        .iter()
795        .map(|l| {
796            serde_json::json!({
797                "ext": l.ext,
798                "count": l.count,
799                "total_tokens": l.total_tokens,
800                "best_mode": l.best_mode,
801                "best_mode_tokens": l.best_mode_tokens,
802                "best_savings_pct": round2(l.best_savings_pct),
803            })
804        })
805        .collect();
806
807    let file_details: Vec<serde_json::Value> = b
808        .file_results
809        .iter()
810        .map(|f| {
811            let file_modes: Vec<serde_json::Value> = f
812                .modes
813                .iter()
814                .map(|m| {
815                    serde_json::json!({
816                        "mode": m.mode,
817                        "tokens": m.tokens,
818                        "savings_pct": round2(m.savings_pct),
819                        "latency_us": m.latency_us,
820                        "preservation": if m.preservation_score < 0.0 {
821                            serde_json::Value::Null
822                        } else {
823                            serde_json::json!(round2(m.preservation_score * 100.0))
824                        },
825                    })
826                })
827                .collect();
828            serde_json::json!({
829                "path": f.path,
830                "ext": f.ext,
831                "raw_tokens": f.raw_tokens,
832                "modes": file_modes,
833            })
834        })
835        .collect();
836
837    let s = &b.session_sim;
838    let report = serde_json::json!({
839        "version": env!("CARGO_PKG_VERSION"),
840        "root": b.root,
841        "files_scanned": b.files_scanned,
842        "files_measured": b.files_measured,
843        "total_raw_tokens": b.total_raw_tokens,
844        "languages": languages,
845        "mode_summaries": modes,
846        "files": file_details,
847        "session_simulation": {
848            "raw_tokens": s.raw_tokens,
849            "lean_tokens": s.lean_tokens,
850            "lean_ccp_tokens": s.lean_ccp_tokens,
851            "raw_cost_usd": round2(s.raw_cost),
852            "lean_cost_usd": round2(s.lean_cost),
853            "ccp_cost_usd": round2(s.ccp_cost),
854        },
855    });
856
857    serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string())
858}
859
860// ── Helpers ─────────────────────────────────────────────────
861
862fn format_num(n: usize) -> String {
863    if n >= 1_000_000 {
864        format!("{:.1}M", n as f64 / 1_000_000.0)
865    } else if n >= 1_000 {
866        format!("{:.1}K", n as f64 / 1_000.0)
867    } else {
868        format!("{n}")
869    }
870}
871
872fn round2(v: f64) -> f64 {
873    (v * 100.0).round() / 100.0
874}
875
876#[cfg(test)]
877mod tests {
878    use super::*;
879
880    fn mock_file(path: &str, ext: &str, raw: usize, modes: Vec<(&str, usize)>) -> FileMeasurement {
881        FileMeasurement {
882            path: path.to_string(),
883            ext: ext.to_string(),
884            raw_tokens: raw,
885            modes: modes
886                .into_iter()
887                .map(|(mode, tokens)| ModeMeasurement {
888                    mode: mode.to_string(),
889                    tokens,
890                    savings_pct: if raw > 0 {
891                        (1.0 - tokens as f64 / raw as f64) * 100.0
892                    } else {
893                        0.0
894                    },
895                    latency_us: 100,
896                    preservation_score: 0.85,
897                })
898                .collect(),
899        }
900    }
901
902    #[test]
903    fn aggregate_languages_computes_best_mode() {
904        let files = vec![
905            mock_file(
906                "a.rs",
907                "rs",
908                1000,
909                vec![("map", 400), ("signatures", 200), ("aggressive", 300)],
910            ),
911            mock_file(
912                "b.rs",
913                "rs",
914                800,
915                vec![("map", 300), ("signatures", 150), ("aggressive", 250)],
916            ),
917            mock_file(
918                "c.py",
919                "py",
920                600,
921                vec![("map", 100), ("signatures", 250), ("aggressive", 200)],
922            ),
923        ];
924
925        let langs = aggregate_languages(&files);
926        assert_eq!(langs.len(), 2);
927
928        let rs = langs.iter().find(|l| l.ext == "rs").unwrap();
929        assert_eq!(rs.count, 2);
930        assert_eq!(rs.total_tokens, 1800);
931        assert_eq!(rs.best_mode, "signatures");
932        assert_eq!(rs.best_mode_tokens, 350);
933        assert!(rs.best_savings_pct > 80.0);
934
935        let py = langs.iter().find(|l| l.ext == "py").unwrap();
936        assert_eq!(py.best_mode, "map");
937        assert_eq!(py.best_mode_tokens, 100);
938    }
939
940    #[test]
941    fn aggregate_modes_averages() {
942        let files = vec![
943            mock_file("a.rs", "rs", 1000, vec![("map", 400), ("aggressive", 300)]),
944            mock_file("b.rs", "rs", 500, vec![("map", 200), ("aggressive", 100)]),
945        ];
946
947        let modes = aggregate_modes(&files);
948        let map = modes.iter().find(|m| m.mode == "map").unwrap();
949        assert_eq!(map.total_compressed_tokens, 600);
950        assert!(map.avg_savings_pct > 50.0);
951    }
952
953    #[test]
954    fn session_sim_empty_files() {
955        let result = simulate_session(&[]);
956        assert_eq!(result.raw_tokens, 0);
957        assert_eq!(result.lean_tokens, 0);
958        assert!((result.raw_cost).abs() < f64::EPSILON);
959    }
960
961    #[test]
962    fn session_sim_basic() {
963        let files: Vec<FileMeasurement> = (0..5)
964            .map(|i| {
965                mock_file(
966                    &format!("file_{i}.rs"),
967                    "rs",
968                    2000,
969                    vec![
970                        ("map", 800),
971                        ("aggressive", 600),
972                        ("cache_hit", cache_hit_tokens()),
973                    ],
974                )
975            })
976            .collect();
977        let result = simulate_session(&files);
978        assert!(result.raw_tokens > 0);
979        assert!(result.lean_tokens < result.raw_tokens);
980        assert!(
981            result.lean_ccp_tokens < result.lean_tokens,
982            "CCP resume ({}) should beat map-based resume ({}) with enough files",
983            result.lean_ccp_tokens,
984            result.lean_tokens
985        );
986    }
987
988    #[test]
989    fn format_json_includes_files_and_language_savings() {
990        let files = vec![mock_file(
991            "src/main.rs",
992            "rs",
993            500,
994            vec![("map", 200), ("signatures", 100), ("cache_hit", 13)],
995        )];
996        let bench = ProjectBenchmark {
997            root: ".".to_string(),
998            files_scanned: 1,
999            files_measured: 1,
1000            total_raw_tokens: 500,
1001            languages: aggregate_languages(&files),
1002            mode_summaries: aggregate_modes(&files),
1003            session_sim: simulate_session(&files),
1004            file_results: files,
1005        };
1006
1007        let json_str = format_json(&bench);
1008        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1009
1010        assert!(parsed["files"].is_array());
1011        assert_eq!(parsed["files"].as_array().unwrap().len(), 1);
1012        assert_eq!(parsed["files"][0]["path"], "src/main.rs");
1013        assert!(parsed["files"][0]["modes"].is_array());
1014
1015        assert!(parsed["languages"][0]["best_mode"].is_string());
1016        assert!(parsed["languages"][0]["best_savings_pct"].is_number());
1017    }
1018
1019    #[test]
1020    fn format_markdown_contains_language_savings() {
1021        let files = vec![mock_file(
1022            "lib.rs",
1023            "rs",
1024            1000,
1025            vec![("map", 300), ("signatures", 200)],
1026        )];
1027        let bench = ProjectBenchmark {
1028            root: ".".to_string(),
1029            files_scanned: 1,
1030            files_measured: 1,
1031            total_raw_tokens: 1000,
1032            languages: aggregate_languages(&files),
1033            mode_summaries: aggregate_modes(&files),
1034            session_sim: simulate_session(&files),
1035            file_results: files,
1036        };
1037
1038        let md = format_markdown(&bench);
1039        assert!(md.contains("Compression by Language"));
1040        assert!(md.contains("Best Mode"));
1041        assert!(md.contains("Savings"));
1042    }
1043
1044    #[test]
1045    fn format_terminal_contains_language_section() {
1046        let files = vec![mock_file(
1047            "app.py",
1048            "py",
1049            800,
1050            vec![("map", 200), ("aggressive", 300)],
1051        )];
1052        let bench = ProjectBenchmark {
1053            root: ".".to_string(),
1054            files_scanned: 1,
1055            files_measured: 1,
1056            total_raw_tokens: 800,
1057            languages: aggregate_languages(&files),
1058            mode_summaries: aggregate_modes(&files),
1059            session_sim: simulate_session(&files),
1060            file_results: files,
1061        };
1062
1063        let out = format_terminal(&bench);
1064        assert!(out.contains("Compression by Language"));
1065        assert!(out.contains("py"));
1066        assert!(out.contains("Best Mode"));
1067    }
1068
1069    #[test]
1070    fn run_project_benchmark_on_multi_language_fixture() {
1071        // A small multi-language fixture exercises the same scan/measure path
1072        // in milliseconds; scanning the real `src/` took ~7 s.
1073        let dir = tempfile::tempdir().unwrap();
1074        let files: &[(&str, &str)] = &[
1075            (
1076                "config.rs",
1077                "use std::collections::HashMap;\n\n/// Parsed configuration.\npub struct Config {\n    pub values: HashMap<String, String>,\n}\n\nimpl Config {\n    pub fn parse(input: &str) -> Result<Self, String> {\n        let mut values = HashMap::new();\n        for line in input.lines() {\n            let (k, v) = line.split_once('=').ok_or_else(|| format!(\"bad line: {line}\"))?;\n            values.insert(k.trim().to_string(), v.trim().to_string());\n        }\n        Ok(Self { values })\n    }\n}\n",
1078            ),
1079            (
1080                "client.ts",
1081                "export interface Options { retries: number; timeoutMs: number }\n\nexport async function fetchWithRetry(url: string, opts: Options): Promise<string> {\n  let lastError: unknown;\n  for (let i = 0; i < opts.retries; i++) {\n    try {\n      const res = await fetch(url);\n      return await res.text();\n    } catch (err) {\n      lastError = err;\n    }\n  }\n  throw lastError;\n}\n",
1082            ),
1083            (
1084                "parse.py",
1085                "def parse(text):\n    \"\"\"Parse key=value configuration lines.\"\"\"\n    result = {}\n    for line in text.splitlines():\n        if '=' not in line:\n            raise ValueError(f'bad line: {line}')\n        key, value = line.split('=', 1)\n        result[key.strip()] = value.strip()\n    return result\n",
1086            ),
1087        ];
1088        for (name, body) in files {
1089            std::fs::write(dir.path().join(name), body).unwrap();
1090        }
1091        let bench = run_project_benchmark(&dir.path().to_string_lossy());
1092        assert!(bench.files_measured > 0);
1093        assert!(bench.total_raw_tokens > 0);
1094        assert!(!bench.languages.is_empty());
1095        assert!(!bench.mode_summaries.is_empty());
1096
1097        for lang in &bench.languages {
1098            assert!(!lang.best_mode.is_empty(), "`lang.best_mode` is empty");
1099            assert!(lang.best_savings_pct >= 0.0);
1100        }
1101
1102        let json = format_json(&bench);
1103        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1104        assert!(
1105            !parsed["files"].as_array().unwrap().is_empty(),
1106            "`parsed[\"files\"].as_array().unwrap()` is empty"
1107        );
1108
1109        let md = format_markdown(&bench);
1110        assert!(md.contains("lean-ctx Benchmark Report"));
1111
1112        let term = format_terminal(&bench);
1113        assert!(term.contains("Session Simulation"));
1114    }
1115}