Skip to main content

lean_ctx/
report.rs

1//! `lean-ctx report-issue` — collects diagnostics and creates a GitHub issue.
2
3use std::path::PathBuf;
4
5const VERSION: &str = env!("CARGO_PKG_VERSION");
6const REPO: &str = "yvgude/lean-ctx";
7const BOLD: &str = "\x1b[1m";
8const RST: &str = "\x1b[0m";
9const DIM: &str = "\x1b[2m";
10const GREEN: &str = "\x1b[32m";
11const YELLOW: &str = "\x1b[33m";
12
13pub fn run(args: &[String]) {
14    let title = extract_flag(args, "--title");
15    let description = extract_flag(args, "--description");
16    let dry_run = args.iter().any(|a| a == "--dry-run");
17    let include_tee = args.iter().any(|a| a == "--include-tee");
18
19    println!("{BOLD}lean-ctx report-issue{RST}\n");
20
21    let title = title.unwrap_or_else(|| prompt_input("Issue title"));
22    if title.trim().is_empty() {
23        eprintln!("Title is required. Aborting.");
24        return;
25    }
26    let description = description.unwrap_or_else(|| prompt_input("Describe the problem"));
27
28    println!("\n{DIM}Collecting diagnostics...{RST}");
29    let body = build_report_body(&title, &description, include_tee);
30
31    println!("\n{BOLD}=== Preview ==={RST}\n");
32    let preview: String = body.chars().take(2000).collect();
33    println!("{preview}");
34    if body.len() > 2000 {
35        println!("{DIM}... ({} more characters){RST}", body.len() - 2000);
36    }
37
38    if dry_run {
39        println!("\n{YELLOW}--dry-run: not submitting.{RST}");
40        if let Some(dir) = lean_ctx_dir() {
41            let path = dir.join("last-report.md");
42            let _ = std::fs::write(&path, &body);
43            println!("Report saved to {}", path.display());
44        }
45        return;
46    }
47
48    println!("\n{BOLD}Submit this as a GitHub issue to {REPO}?{RST} [y/N]");
49    let mut answer = String::new();
50    let _ = std::io::stdin().read_line(&mut answer);
51    if !answer.trim().eq_ignore_ascii_case("y") {
52        println!("Aborted.");
53        if let Some(dir) = lean_ctx_dir() {
54            let path = dir.join("last-report.md");
55            let _ = std::fs::write(&path, &body);
56            println!("Report saved to {}", path.display());
57        }
58        return;
59    }
60
61    if try_gh_cli(&title, &body) {
62        return;
63    }
64    try_ureq_api(&title, &body);
65}
66
67fn build_report_body(_title: &str, description: &str, include_tee: bool) -> String {
68    let mut sections = Vec::new();
69
70    sections.push(format!("## Description\n\n{description}"));
71    sections.push(section_environment());
72    sections.push(section_configuration());
73    sections.push(section_mcp_status());
74    sections.push(section_tool_calls());
75    sections.push(section_session());
76    sections.push(section_performance());
77    sections.push(section_slow_commands());
78    sections.push(section_tee_logs(include_tee));
79    sections.push(section_project_context());
80
81    let body = sections.join("\n\n---\n\n");
82    anonymize_report(&body)
83}
84
85// ── Section Builders ──────────────────────────────────────────────────────
86
87fn section_environment() -> String {
88    let os = std::env::consts::OS;
89    let arch = std::env::consts::ARCH;
90    let shell = std::env::var("SHELL").unwrap_or_else(|_| "unknown".into());
91    let ide = detect_ide();
92
93    format!(
94        "## Environment\n\n\
95         | Field | Value |\n|---|---|\n\
96         | lean-ctx | {VERSION} |\n\
97         | OS | {os} {arch} |\n\
98         | Shell | {shell} |\n\
99         | IDE | {ide} |"
100    )
101}
102
103fn section_configuration() -> String {
104    let mut out = String::from("## Configuration\n\n```toml\n");
105    if let Some(dir) = lean_ctx_dir() {
106        let config_path = dir.join("config.toml");
107        if let Ok(content) = std::fs::read_to_string(&config_path) {
108            let clean = mask_secrets(&content);
109            out.push_str(&clean);
110        } else {
111            out.push_str("# config.toml not found — using defaults");
112        }
113    }
114    out.push_str("\n```");
115    out
116}
117
118fn section_mcp_status() -> String {
119    let mut lines = vec!["## MCP Integration Status\n".to_string()];
120
121    let binary_ok = which_lean_ctx().is_some();
122    lines.push(format!(
123        "- Binary on PATH: {}",
124        if binary_ok { "yes" } else { "no" }
125    ));
126
127    let hooks = check_shell_hooks();
128    lines.push(format!("- Shell hooks: {hooks}"));
129
130    let ides = check_mcp_configs();
131    lines.push(format!("- MCP configured for: {ides}"));
132
133    lines.join("\n")
134}
135
136fn section_tool_calls() -> String {
137    let mut out = String::from("## Recent Tool Calls\n\n```\n");
138    if let Some(dir) = lean_ctx_dir() {
139        let log_path = dir.join("tool-calls.log");
140        if let Ok(content) = std::fs::read_to_string(&log_path) {
141            let lines: Vec<&str> = content.lines().collect();
142            let start = lines.len().saturating_sub(20);
143            for line in &lines[start..] {
144                out.push_str(line);
145                out.push('\n');
146            }
147        } else {
148            out.push_str("# No tool call log found\n");
149        }
150    }
151    out.push_str("```");
152    out
153}
154
155fn section_session() -> String {
156    let mut out = String::from("## Session State\n\n");
157    if let Some(dir) = lean_ctx_dir() {
158        let latest = dir.join("sessions").join("latest.json");
159        if let Ok(content) = std::fs::read_to_string(&latest) {
160            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
161                if let Some(task) = val.get("task") {
162                    out.push_str(&format!(
163                        "- Task: {}\n",
164                        task.get("description")
165                            .and_then(|d| d.as_str())
166                            .unwrap_or("-")
167                    ));
168                }
169                if let Some(stats) = val.get("stats") {
170                    out.push_str(&format!("- Stats: {}\n", stats));
171                }
172                if let Some(files) = val.get("files_touched").and_then(|f| f.as_object()) {
173                    out.push_str(&format!("- Files touched: {}\n", files.len()));
174                }
175            }
176        } else {
177            out.push_str("No active session found.\n");
178        }
179    }
180    out
181}
182
183fn section_performance() -> String {
184    let mut out = String::from("## Performance Metrics\n\n");
185    if let Some(dir) = lean_ctx_dir() {
186        let mcp_live = dir.join("mcp-live.json");
187        if let Ok(content) = std::fs::read_to_string(&mcp_live) {
188            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
189                let fields = [
190                    "cep_score",
191                    "cache_utilization",
192                    "compression_rate",
193                    "tokens_saved",
194                    "tokens_original",
195                    "tool_calls",
196                ];
197                out.push_str("| Metric | Value |\n|---|---|\n");
198                for field in fields {
199                    if let Some(v) = val.get(field) {
200                        out.push_str(&format!("| {field} | {v} |\n"));
201                    }
202                }
203            }
204        }
205
206        let stats_path = dir.join("stats.json");
207        if let Ok(content) = std::fs::read_to_string(&stats_path) {
208            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
209                if let Some(cmds) = val.get("commands").and_then(|c| c.as_object()) {
210                    let mut top: Vec<_> = cmds
211                        .iter()
212                        .filter_map(|(k, v)| {
213                            v.get("count").and_then(|c| c.as_u64()).map(|c| (k, c))
214                        })
215                        .collect();
216                    top.sort_by(|a, b| b.1.cmp(&a.1));
217                    top.truncate(5);
218                    out.push_str("\n**Top 5 tools:**\n");
219                    for (name, count) in top {
220                        out.push_str(&format!("- {name}: {count} calls\n"));
221                    }
222                }
223            }
224        }
225    }
226    out
227}
228
229fn section_slow_commands() -> String {
230    let mut out = String::from("## Slow Commands\n\n```\n");
231    if let Some(dir) = lean_ctx_dir() {
232        let log_path = dir.join("slow-commands.log");
233        if let Ok(content) = std::fs::read_to_string(&log_path) {
234            let lines: Vec<&str> = content.lines().collect();
235            let start = lines.len().saturating_sub(10);
236            for line in &lines[start..] {
237                out.push_str(line);
238                out.push('\n');
239            }
240        } else {
241            out.push_str("# No slow commands logged\n");
242        }
243    }
244    out.push_str("```");
245    out
246}
247
248fn section_tee_logs(include_content: bool) -> String {
249    let mut out = String::from("## Tee Logs (last 24h)\n\n");
250    if let Some(dir) = lean_ctx_dir() {
251        let tee_dir = dir.join("tee");
252        if tee_dir.is_dir() {
253            let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(24 * 3600);
254            let mut entries: Vec<_> = std::fs::read_dir(&tee_dir)
255                .into_iter()
256                .flatten()
257                .filter_map(|e| e.ok())
258                .filter(|e| {
259                    e.metadata()
260                        .ok()
261                        .and_then(|m| m.modified().ok())
262                        .is_some_and(|t| t > cutoff)
263                })
264                .collect();
265            entries.sort_by_key(|e| {
266                std::cmp::Reverse(
267                    e.metadata()
268                        .ok()
269                        .and_then(|m| m.modified().ok())
270                        .unwrap_or(std::time::SystemTime::UNIX_EPOCH),
271                )
272            });
273
274            if entries.is_empty() {
275                out.push_str("No tee logs in the last 24h.\n");
276            } else {
277                for entry in entries.iter().take(10) {
278                    let name = entry.file_name();
279                    let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
280                    out.push_str(&format!("- `{}` ({size} bytes)\n", name.to_string_lossy()));
281                }
282                if include_content {
283                    if let Some(latest) = entries.first() {
284                        if let Ok(content) = std::fs::read_to_string(latest.path()) {
285                            let truncated: String = content.chars().take(3000).collect();
286                            out.push_str(&format!(
287                                "\n**Latest tee content (`{}`):**\n```\n{truncated}\n```",
288                                latest.file_name().to_string_lossy()
289                            ));
290                        }
291                    }
292                }
293            }
294        } else {
295            out.push_str("No tee directory found.\n");
296        }
297    }
298    out
299}
300
301fn section_project_context() -> String {
302    let mut out = String::from("## Project Context\n\n");
303    let cwd = std::env::current_dir()
304        .map(|p| p.to_string_lossy().to_string())
305        .unwrap_or_else(|_| "unknown".into());
306    out.push_str(&format!("- Working directory: {cwd}\n"));
307
308    if let Ok(entries) = std::fs::read_dir(".") {
309        let count = entries.filter_map(|e| e.ok()).count();
310        out.push_str(&format!("- Files in root: {count}\n"));
311    }
312    out
313}
314
315// ── Anonymization ─────────────────────────────────────────────────────────
316
317fn anonymize_report(text: &str) -> String {
318    let home = dirs::home_dir()
319        .map(|h| h.to_string_lossy().to_string())
320        .unwrap_or_default();
321
322    let mut result = text.to_string();
323    if !home.is_empty() {
324        result = result.replace(&home, "~");
325    }
326
327    let user = std::env::var("USER")
328        .or_else(|_| std::env::var("USERNAME"))
329        .unwrap_or_default();
330    if user.len() > 2 {
331        result = result.replace(&user, "<user>");
332    }
333
334    result
335}
336
337fn mask_secrets(text: &str) -> String {
338    let mut out = String::new();
339    for line in text.lines() {
340        if line.contains("token")
341            || line.contains("key")
342            || line.contains("secret")
343            || line.contains("password")
344            || line.contains("api_key")
345        {
346            if let Some(eq) = line.find('=') {
347                out.push_str(&line[..=eq]);
348                out.push_str(" \"[REDACTED]\"");
349            } else {
350                out.push_str(line);
351            }
352        } else {
353            out.push_str(line);
354        }
355        out.push('\n');
356    }
357    out
358}
359
360// ── GitHub Submission ─────────────────────────────────────────────────────
361
362fn try_gh_cli(title: &str, body: &str) -> bool {
363    let tmp = std::env::temp_dir().join("lean-ctx-report.md");
364    if std::fs::write(&tmp, body).is_err() {
365        return false;
366    }
367
368    let result = std::process::Command::new("gh")
369        .args([
370            "issue",
371            "create",
372            "--repo",
373            REPO,
374            "--title",
375            title,
376            "--body-file",
377            &tmp.to_string_lossy(),
378            "--label",
379            "bug,auto-report",
380        ])
381        .output();
382
383    let _ = std::fs::remove_file(&tmp);
384
385    match result {
386        Ok(output) if output.status.success() => {
387            let url = String::from_utf8_lossy(&output.stdout);
388            println!("\n{GREEN}Issue created:{RST} {}", url.trim());
389            true
390        }
391        Ok(output) => {
392            let stderr = String::from_utf8_lossy(&output.stderr);
393            if stderr.contains("not logged") || stderr.contains("auth login") {
394                eprintln!("{YELLOW}gh CLI found but not authenticated. Run: gh auth login{RST}");
395            }
396            false
397        }
398        Err(_) => false,
399    }
400}
401
402fn try_ureq_api(title: &str, body: &str) {
403    println!("\n{YELLOW}gh CLI not available. Using GitHub API directly.{RST}");
404    println!("Enter a GitHub Personal Access Token (needs 'repo' scope):");
405    println!("{DIM}Create one at: https://github.com/settings/tokens/new{RST}");
406
407    let mut token = String::new();
408    let _ = std::io::stdin().read_line(&mut token);
409    let token = token.trim();
410
411    if token.is_empty() {
412        eprintln!("No token provided. Saving report locally.");
413        save_report_locally(body);
414        return;
415    }
416
417    let url = format!("https://api.github.com/repos/{REPO}/issues");
418    let payload = serde_json::json!({
419        "title": title,
420        "body": body,
421        "labels": ["bug", "auto-report"]
422    });
423
424    let payload_bytes = serde_json::to_vec(&payload).unwrap_or_default();
425    match ureq::post(&url)
426        .header("Authorization", &format!("Bearer {token}"))
427        .header("Accept", "application/vnd.github.v3+json")
428        .header("Content-Type", "application/json")
429        .header("User-Agent", &format!("lean-ctx/{VERSION}"))
430        .send(payload_bytes.as_slice())
431    {
432        Ok(resp) => {
433            let resp_body = resp.into_body().read_to_string().unwrap_or_default();
434            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&resp_body) {
435                if let Some(html_url) = val.get("html_url").and_then(|u| u.as_str()) {
436                    println!("\n{GREEN}Issue created:{RST} {html_url}");
437                    return;
438                }
439            }
440            println!("{GREEN}Issue created successfully.{RST}");
441        }
442        Err(e) => {
443            eprintln!("GitHub API error: {e}");
444            save_report_locally(body);
445        }
446    }
447}
448
449fn save_report_locally(body: &str) {
450    if let Some(dir) = lean_ctx_dir() {
451        let path = dir.join("last-report.md");
452        let _ = std::fs::write(&path, body);
453        println!("Report saved to {}", path.display());
454    }
455}
456
457// ── Helpers ───────────────────────────────────────────────────────────────
458
459fn lean_ctx_dir() -> Option<PathBuf> {
460    dirs::home_dir().map(|h| h.join(".lean-ctx"))
461}
462
463fn which_lean_ctx() -> Option<PathBuf> {
464    let cmd = if cfg!(windows) { "where" } else { "which" };
465    std::process::Command::new(cmd)
466        .arg("lean-ctx")
467        .output()
468        .ok()
469        .filter(|o| o.status.success())
470        .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim().to_string()))
471}
472
473fn check_shell_hooks() -> String {
474    let home = match dirs::home_dir() {
475        Some(h) => h,
476        None => return "unknown".into(),
477    };
478
479    let mut found = Vec::new();
480    let shells = [
481        (".zshrc", "zsh"),
482        (".bashrc", "bash"),
483        (".config/fish/config.fish", "fish"),
484    ];
485    for (file, name) in shells {
486        let path = home.join(file);
487        if let Ok(content) = std::fs::read_to_string(&path) {
488            if content.contains("lean-ctx") {
489                found.push(name);
490            }
491        }
492    }
493
494    if found.is_empty() {
495        "none detected".into()
496    } else {
497        found.join(", ")
498    }
499}
500
501fn check_mcp_configs() -> String {
502    let home = match dirs::home_dir() {
503        Some(h) => h,
504        None => return "unknown".into(),
505    };
506
507    let mut found = Vec::new();
508    let configs: &[(&str, &str)] = &[
509        (".cursor/mcp.json", "Cursor"),
510        (".claude.json", "Claude Code"),
511        (".codeium/windsurf/mcp_config.json", "Windsurf"),
512    ];
513
514    for (path, name) in configs {
515        let full = home.join(path);
516        if let Ok(content) = std::fs::read_to_string(&full) {
517            if content.contains("lean-ctx") {
518                found.push(*name);
519            }
520        }
521    }
522
523    if found.is_empty() {
524        "none".into()
525    } else {
526        found.join(", ")
527    }
528}
529
530fn detect_ide() -> String {
531    if std::env::var("CURSOR_SESSION").is_ok() || std::env::var("CURSOR_TRACE_DIR").is_ok() {
532        return "Cursor".into();
533    }
534    if std::env::var("VSCODE_PID").is_ok() {
535        return "VS Code".into();
536    }
537    "unknown".into()
538}
539
540fn extract_flag(args: &[String], flag: &str) -> Option<String> {
541    args.windows(2).find(|w| w[0] == flag).map(|w| w[1].clone())
542}
543
544fn prompt_input(label: &str) -> String {
545    eprint!("{BOLD}{label}:{RST} ");
546    let mut input = String::new();
547    let _ = std::io::stdin().read_line(&mut input);
548    input.trim().to_string()
549}