Skip to main content

lean_ctx_cli/cli/
discover_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::fmt::Write as _;
3
4use super::common::load_shell_history;
5
6pub fn cmd_discover(args: &[String]) {
7    let history = load_shell_history();
8    if history.is_empty() {
9        println!("No shell history found.");
10        return;
11    }
12
13    let result = lean_ctx_server::tools::ctx_discover::analyze_history(&history, 20);
14
15    if let Some(path) = card_target(args) {
16        match std::fs::write(
17            &path,
18            lean_ctx_server::tools::ctx_discover::render_before_card(&result),
19        ) {
20            Ok(()) => println!(
21                "Before-card written to {path}\n\
22                 Share it, or open `lean-ctx cockpit` after a week for your real numbers \
23                 (shareable card: `lean-ctx gain --wrapped`)."
24            ),
25            Err(e) => {
26                eprintln!("Failed to write {path}: {e}");
27                std::process::exit(1);
28            }
29        }
30        return;
31    }
32
33    let report = lean_ctx_server::tools::ctx_discover::format_cli_output(&result);
34    super::common::print_released(&released_report(
35        &super::common::detect_project_root(args),
36        report,
37    ));
38}
39
40/// Print a report that ends with its own `\n` (the former `print!`): it is
41/// released without that final newline, which the one observed writer adds
42/// back, so the bytes on stdout are the same and the hand-over is observed.
43fn print_report(out: &str) {
44    let report = out.strip_suffix('\n').unwrap_or(out).to_owned();
45    super::common::print_released(&released_report(
46        &super::common::detect_project_root(&[]),
47        report,
48    ));
49}
50
51/// The discover, ghost and first-run reports are statistics about the user's
52/// own shell history (admitted where it was loaded). They name command
53/// families — the first word of a command line — next to counters, so they
54/// are reports for the person at the terminal: released like every output,
55/// never recorded as a delivery of project sources.
56fn released_report(project_root: &str, report: String) -> String {
57    super::common::CliToolRun::new("ctx_discover", project_root, None)
58        .human_facing()
59        .deliver_text(|| report)
60}
61
62/// Resolves the `--card[=<path>]` output path for the shareable "before" SVG, or `None`
63/// when not requested. A bare `--card` defaults to `lean-ctx-before.svg`.
64fn card_target(args: &[String]) -> Option<String> {
65    let mut requested = false;
66    let mut path: Option<String> = None;
67    for (i, a) in args.iter().enumerate() {
68        if let Some(v) = a.strip_prefix("--card=") {
69            requested = true;
70            path = Some(v.to_string());
71        } else if a == "--card" {
72            requested = true;
73            if let Some(next) = args.get(i + 1)
74                && !next.starts_with('-')
75            {
76                path = Some(next.clone());
77            }
78        }
79    }
80    requested.then(|| path.unwrap_or_else(|| "lean-ctx-before.svg".to_string()))
81}
82
83/// Path of the marker recording that the first-run "aha" was already shown.
84fn first_run_marker() -> Option<std::path::PathBuf> {
85    lean_ctx::core::paths::cache_dir()
86        .ok()
87        .map(|d| d.join(".first_run_wow_done"))
88}
89
90/// Shows the discover "you're leaving X tokens on the table" moment exactly once, right
91/// after setup. Marker-guarded so re-running `setup` never repeats it. Stays silent (but
92/// still marks done) when there is too little history to be meaningful, so it never nags.
93/// Reads only local shell history and prints aggregate estimates — never command contents.
94pub fn show_first_run_wow() {
95    let Some(marker) = first_run_marker() else {
96        return;
97    };
98    if marker.exists() {
99        return;
100    }
101    // Mark immediately so any edge case never reshows on the next setup run.
102    if let Some(parent) = marker.parent() {
103        let _ = std::fs::create_dir_all(parent);
104    }
105    let _ = std::fs::write(&marker, "shown\n");
106
107    let history = load_shell_history();
108    if history.is_empty() {
109        return;
110    }
111    let result = lean_ctx_server::tools::ctx_discover::analyze_history(&history, 20);
112    let total_missed: u32 = result.missed_commands.iter().map(|m| m.count).sum();
113    if total_missed == 0 {
114        return;
115    }
116
117    let bold = "\x1b[1m";
118    let green = "\x1b[32m";
119    let yellow = "\x1b[33m";
120    let dim = "\x1b[2m";
121    let rst = "\x1b[0m";
122
123    let top = result
124        .missed_commands
125        .iter()
126        .take(3)
127        .map(|m| format!("{} {}x", m.prefix, m.count))
128        .collect::<Vec<_>>()
129        .join("   ");
130    let mut out = String::new();
131
132    out.push('\n');
133    let _ = writeln!(
134        out,
135        "  {bold}Here's what lean-ctx is about to start saving you{rst}"
136    );
137    let _ = writeln!(
138        out,
139        "  {dim}estimated from your shell history — nothing leaves your machine{rst}"
140    );
141    out.push('\n');
142    if result.has_measured_data {
143        // Returning user: project their own measured savings onto frequency.
144        let monthly = result.potential_usd * 30.0;
145        let saved = lean_ctx::core::wrapped::format_tokens(result.potential_tokens as u64);
146        let _ = writeln!(
147            out,
148            "  {green}~{saved} tokens{rst}{dim}/month{rst} across {total_missed} uncompressed commands {dim}(~${monthly:.0}/mo, from your measured rate){rst}"
149        );
150    } else {
151        // Fresh install: no measurements yet — show frequency, never a fake $.
152        let _ = writeln!(
153            out,
154            "  {green}{total_missed} commands{rst} {dim}that lean-ctx will now compress automatically{rst}"
155        );
156    }
157    if !top.is_empty() {
158        let _ = writeln!(out, "  {dim}top: {top}{rst}");
159    }
160    out.push('\n');
161    let _ = writeln!(
162        out,
163        "  {yellow}Open {bold}lean-ctx cockpit{rst}{yellow} after a week for your real numbers — {bold}lean-ctx gain --wrapped{rst}{yellow} makes a shareable card.{rst}"
164    );
165    out.push('\n');
166    print_report(&out);
167}
168
169pub fn cmd_ghost(args: &[String]) {
170    let json = args.iter().any(|a| a == "--json");
171
172    let history = load_shell_history();
173    let discover = lean_ctx_server::tools::ctx_discover::analyze_history(&history, 20);
174
175    let session = lean_ctx::core::session::SessionState::load_latest();
176    let store = lean_ctx::core::stats::load();
177
178    let unoptimized_tokens = discover.potential_tokens;
179    let _unoptimized_usd = discover.potential_usd;
180
181    // Redundant reads: every cache hit is a re-read lean-ctx served from cache
182    // instead of re-sending the file. Value it at the user's *measured* average
183    // read size (from the heatmap), never a guessed constant. No heatmap data
184    // yet => 0, so we never invent a figure.
185    let redundant_reads = store.cep.total_cache_hits as usize;
186    let avg_read_tokens = lean_ctx::core::heatmap::HeatMap::load()
187        .avg_original_tokens_per_access()
188        .unwrap_or(0) as usize;
189    let redundant_tokens = redundant_reads.saturating_mul(avg_read_tokens);
190
191    // NOTE: the former "oversized contexts" category was dropped — it was a
192    // fabricated wasted_original/3 heuristic applied to realized (not wasted)
193    // compression savings. The JSON keeps `truncated_contexts: 0` for schema
194    // stability; there is no honest data source to revive it.
195    let total_ghost = unoptimized_tokens + redundant_tokens;
196    let total_usd =
197        total_ghost as f64 * lean_ctx::core::stats::DEFAULT_INPUT_PRICE_PER_M / 1_000_000.0;
198    let monthly_usd = total_usd * 30.0;
199
200    if json {
201        let obj = serde_json::json!({
202            "ghost_tokens": total_ghost,
203            "breakdown": {
204                "unoptimized_shells": unoptimized_tokens,
205                "redundant_reads": redundant_tokens,
206                "truncated_contexts": 0,
207            },
208            "estimated_usd": total_usd,
209            "monthly_usd": monthly_usd,
210            "session_active": session.is_some(),
211            "history_commands": discover.total_commands,
212            "already_optimized": discover.already_optimized,
213        });
214        // Counters only, but a stdout document of this command like the
215        // report below: released as a document and receipted (G08).
216        let document = serde_json::to_string_pretty(&obj).unwrap_or_default();
217        let root = super::common::detect_project_root(&[]);
218        match super::common::CliToolRun::new("ctx_discover", &root, None)
219            .human_facing()
220            .deliver_json(|| document)
221        {
222            Ok(document) => super::common::print_released(&document),
223            Err(reason) => super::common::exit_withheld(&reason),
224        }
225        return;
226    }
227
228    let bold = "\x1b[1m";
229    let green = "\x1b[32m";
230    let yellow = "\x1b[33m";
231    let red = "\x1b[31m";
232    let dim = "\x1b[2m";
233    let rst = "\x1b[0m";
234    let white = "\x1b[97m";
235    let mut out = String::new();
236
237    out.push('\n');
238    let _ = writeln!(out, "  {bold}{white}lean-ctx ghost report{rst}");
239    let _ = writeln!(out, "  {dim}{}{rst}", "=".repeat(40));
240    out.push('\n');
241
242    if total_ghost == 0 {
243        let _ = writeln!(out, "  {green}No ghost tokens detected!{rst}");
244        let _ = writeln!(
245            out,
246            "  {dim}All {} commands optimized.{rst}",
247            discover.total_commands
248        );
249        out.push('\n');
250        print!(
251            "{}",
252            released_report(&super::common::detect_project_root(&[]), out)
253        );
254        return;
255    }
256
257    let severity = if total_ghost > 10000 {
258        red
259    } else if total_ghost > 3000 {
260        yellow
261    } else {
262        green
263    };
264
265    let _ = writeln!(
266        out,
267        "  {bold}Ghost Tokens found:{rst}     {severity}{total_ghost:>8}{rst} tokens {dim}(~${total_usd:.2}){rst}"
268    );
269    out.push('\n');
270
271    if unoptimized_tokens > 0 {
272        let missed_count: u32 = discover.missed_commands.iter().map(|m| m.count).sum();
273        let _ = writeln!(
274            out,
275            "  {dim}  Unoptimized shells:{rst}  {white}{unoptimized_tokens:>8}{rst} {dim}({missed_count} cmds without lean-ctx){rst}"
276        );
277    }
278    if redundant_tokens > 0 {
279        let _ = writeln!(
280            out,
281            "  {dim}  Redundant reads:{rst}     {white}{redundant_tokens:>8}{rst} {dim}({redundant_reads} cache hits = wasted re-reads){rst}"
282        );
283    }
284    out.push('\n');
285    let _ = writeln!(
286        out,
287        "  {bold}Monthly savings potential:{rst} {green}${monthly_usd:.2}{rst}"
288    );
289
290    if !discover.missed_commands.is_empty() {
291        out.push('\n');
292        let _ = writeln!(out, "  {bold}Top unoptimized commands:{rst}");
293        for m in discover.missed_commands.iter().take(5) {
294            let _ = writeln!(
295                out,
296                "    {dim}{:>4}x{rst}  {white}{:<12}{rst} {dim}{}{rst}",
297                m.count, m.prefix, m.description
298            );
299        }
300    }
301
302    out.push('\n');
303    if discover.already_optimized == 0 {
304        let _ = writeln!(
305            out,
306            "  {yellow}Run '{bold}lean-ctx onboard{rst}{yellow}' to eliminate ghost tokens.{rst}"
307        );
308    } else {
309        let _ = writeln!(
310            out,
311            "  {dim}Already optimized: {}/{} commands{rst}",
312            discover.already_optimized, discover.total_commands
313        );
314    }
315    out.push('\n');
316    print_report(&out);
317}
318
319#[cfg(test)]
320mod tests {
321    use crate::cli::common::carrier_tests_support::{AWS_KEY, governed, lineage, project};
322
323    /// The discover report is statistics about shell history: released,
324    /// never registered as a delivery of project sources.
325    #[test]
326    fn the_discover_report_is_human_facing() {
327        let _data = lean_ctx::core::data_dir::isolated_data_dir();
328        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
329        governed();
330        let (_project, root) = project();
331        let report = "Analyzed 120 commands\n  git status  x14";
332        let printed = super::released_report(&root, report.to_string());
333        assert_eq!(printed, report, "the report keeps its bytes");
334        assert_eq!(lineage(&root, &printed), None);
335        let leaked = super::released_report(&root, format!("export KEY={AWS_KEY}  x2"));
336        assert!(!leaked.contains(AWS_KEY), "{leaked}");
337    }
338}