Skip to main content

lean_ctx/cli/
discover_cmd.rs

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