Skip to main content

lean_ctx_cli/
token_report.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::{Path, PathBuf};
3
4use lean_ctx_time::UtcDateTime;
5use serde::{Deserialize, Serialize};
6
7use lean_ctx::core::knowledge::ProjectKnowledge;
8use lean_ctx::core::session::SessionState;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct TokenReport {
12    pub schema_version: u32,
13    pub generated_at: UtcDateTime,
14    pub version: String,
15    pub project_root: String,
16    pub data_dir: String,
17    pub knowledge: Option<ProjectKnowledgeSummary>,
18    pub session: Option<SessionSummary>,
19    pub cep: Option<CepSummary>,
20    pub warnings: Vec<String>,
21    pub errors: Vec<String>,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ProjectKnowledgeSummary {
26    pub project_hash: String,
27    pub active_facts: usize,
28    pub archived_facts: usize,
29    pub patterns: usize,
30    pub history: usize,
31    pub updated_at: UtcDateTime,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct SessionSummary {
36    pub id: String,
37    pub started_at: UtcDateTime,
38    pub updated_at: UtcDateTime,
39    pub tool_calls: u32,
40    pub tokens_saved: u64,
41    pub tokens_input: u64,
42    pub cache_hits: u32,
43    pub files_read: u32,
44    pub commands_run: u32,
45    pub repeated_files: u32,
46    pub intents_total: u32,
47    pub intents_inferred: u32,
48    pub intents_explicit: u32,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct CepSummary {
53    pub sessions: u64,
54    pub total_cache_hits: u64,
55    pub total_cache_reads: u64,
56    pub total_tokens_original: u64,
57    pub total_tokens_compressed: u64,
58    pub last_snapshot: Option<CepSnapshot>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct CepSnapshot {
63    pub timestamp: String,
64    pub score: u32,
65    pub cache_hit_rate: u32,
66    pub mode_diversity: u32,
67    pub compression_rate: u32,
68    pub tool_calls: u64,
69    pub tokens_saved: u64,
70    pub complexity: String,
71}
72
73pub fn run_cli(args: &[String]) -> i32 {
74    let json = args.iter().any(|a| a == "--json");
75    let help = args.iter().any(|a| a == "--help" || a == "-h");
76    if help {
77        println!("Usage:");
78        println!("  lean-ctx token-report [--json] [--project-root <path>]");
79        return 0;
80    }
81
82    let project_root = extract_flag(args, "--project-root");
83
84    match build_report(project_root.as_deref()) {
85        Ok((mut report, path)) => {
86            let saved =
87                crate::status::save_report(&report, &path).map_err(|e| report.errors.push(e));
88            let text = serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string());
89
90            if json {
91                println!("{text}");
92            } else {
93                print_human(&report, saved.is_ok().then_some(path.as_path()));
94            }
95
96            i32::from(!report.errors.is_empty())
97        }
98        Err(e) => {
99            eprintln!("{e}");
100            2
101        }
102    }
103}
104
105fn build_report(project_root_override: Option<&str>) -> Result<(TokenReport, PathBuf), String> {
106    let generated_at = UtcDateTime::now();
107    let version = env!("CARGO_PKG_VERSION").to_string();
108
109    let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()?;
110
111    let cwd = std::env::current_dir()
112        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string());
113    let project_root = project_root_override.map_or_else(
114        || lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd),
115        std::string::ToString::to_string,
116    );
117
118    let mut warnings: Vec<String> = Vec::new();
119    let errors: Vec<String> = Vec::new();
120
121    let knowledge = ProjectKnowledge::load(&project_root).map(|k| ProjectKnowledgeSummary {
122        project_hash: k.project_hash.clone(),
123        active_facts: k.facts.iter().filter(|f| f.is_current()).count(),
124        archived_facts: k.facts.iter().filter(|f| !f.is_current()).count(),
125        patterns: k.patterns.len(),
126        history: k.history.len(),
127        updated_at: k.updated_at,
128    });
129
130    if knowledge.is_none() {
131        warnings.push("no project knowledge found".to_string());
132    }
133
134    let session = SessionState::load_latest().map(|s| {
135        let repeated_files = s.files_touched.iter().filter(|f| f.read_count > 1).count() as u32;
136        SessionSummary {
137            id: s.id,
138            started_at: s.started_at,
139            updated_at: s.updated_at,
140            tool_calls: s.stats.total_tool_calls,
141            tokens_saved: s.stats.total_tokens_saved,
142            tokens_input: s.stats.total_tokens_input,
143            cache_hits: s.stats.cache_hits,
144            files_read: s.stats.files_read,
145            commands_run: s.stats.commands_run,
146            repeated_files,
147            intents_total: s.intents.len() as u32,
148            intents_inferred: s.stats.intents_inferred,
149            intents_explicit: s.stats.intents_explicit,
150        }
151    });
152
153    if session.is_none() {
154        warnings.push("no active session found".to_string());
155    }
156
157    let store = lean_ctx::core::stats::load_for_display();
158    let last_snapshot = store.cep.scores.last().map(|s| CepSnapshot {
159        timestamp: s.timestamp.clone(),
160        score: s.score,
161        cache_hit_rate: s.cache_hit_rate,
162        mode_diversity: s.mode_diversity,
163        compression_rate: s.compression_rate,
164        tool_calls: s.tool_calls,
165        tokens_saved: s.tokens_saved,
166        complexity: s.complexity.clone(),
167    });
168
169    let cep = CepSummary {
170        sessions: store.cep.sessions,
171        total_cache_hits: store.cep.total_cache_hits,
172        total_cache_reads: store.cep.total_cache_reads,
173        total_tokens_original: store.cep.total_tokens_original,
174        total_tokens_compressed: store.cep.total_tokens_compressed,
175        last_snapshot,
176    };
177
178    let report_path = data_dir.join("report").join("latest.json");
179
180    let report = TokenReport {
181        schema_version: 1,
182        generated_at,
183        version,
184        project_root,
185        data_dir: data_dir.to_string_lossy().to_string(),
186        knowledge,
187        session,
188        cep: Some(cep),
189        warnings,
190        errors,
191    };
192
193    Ok((report, report_path))
194}
195
196fn print_human(report: &TokenReport, saved_to: Option<&Path>) {
197    println!("lean-ctx token-report  v{}", report.version);
198    println!("  project: {}", report.project_root);
199    println!("  data:    {}", report.data_dir);
200
201    if let Some(k) = &report.knowledge {
202        println!(
203            "  knowledge: {} active, {} archived, {} patterns, {} history",
204            k.active_facts, k.archived_facts, k.patterns, k.history
205        );
206    } else {
207        println!("  knowledge: (none)");
208    }
209
210    if let Some(s) = &report.session {
211        println!(
212            "  session: {} calls, {} tok saved, {} files read ({} repeated), {} intents ({} inferred, {} explicit)",
213            s.tool_calls,
214            s.tokens_saved,
215            s.files_read,
216            s.repeated_files,
217            s.intents_total,
218            s.intents_inferred,
219            s.intents_explicit
220        );
221    } else {
222        println!("  session: (none)");
223    }
224
225    if let Some(cep) = &report.cep {
226        if let Some(last) = &cep.last_snapshot {
227            println!(
228                "  cep(last): score={} cache_hit_rate={} mode_diversity={} compression_rate={} tool_calls={} tok_saved={}",
229                last.score,
230                last.cache_hit_rate,
231                last.mode_diversity,
232                last.compression_rate,
233                last.tool_calls,
234                last.tokens_saved
235            );
236        } else {
237            println!("  cep(last): (none)");
238        }
239    }
240
241    if !report.warnings.is_empty() {
242        println!("  warnings: {}", report.warnings.len());
243    }
244    if !report.errors.is_empty() {
245        println!("  errors: {}", report.errors.len());
246    }
247    for error in &report.errors {
248        eprintln!("error: {error}");
249    }
250    if let Some(path) = saved_to {
251        println!("  report saved: {}", path.display());
252    }
253}
254
255fn extract_flag(args: &[String], flag: &str) -> Option<String> {
256    args.windows(2).find(|w| w[0] == flag).map(|w| w[1].clone())
257}