Skip to main content

lean_ctx_ext/
report.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx report-issue` — collects diagnostics and creates a GitHub issue.
3
4use std::path::PathBuf;
5
6const VERSION: &str = env!("CARGO_PKG_VERSION");
7const REPO: &str = "yvgude/lean-ctx";
8const BOLD: &str = "\x1b[1m";
9const RST: &str = "\x1b[0m";
10const DIM: &str = "\x1b[2m";
11const GREEN: &str = "\x1b[32m";
12const YELLOW: &str = "\x1b[33m";
13
14/// Shown before the submit prompt with `--include-tee`: the tee section then
15/// carries real command output from the state dir, and the preview above is
16/// cut at 2000 characters, so it may not show that excerpt at all.
17const INCLUDE_TEE_NOTICE: &str = "--include-tee: this report attaches the saved full output of \
18your latest command (up to 3000 characters). It can contain file contents and paths. Secrets \
19are redacted, but the preview above is truncated: run with --dry-run and review the saved \
20report before sending it.";
21
22/// Characters of the report body shown in the preview before submitting.
23const PREVIEW_CHARS: usize = 2000;
24
25/// The first `limit` characters of `body` and how many characters follow.
26/// Both count `char`s, not bytes, so a multi-byte body is never cut inside
27/// a character and the "more characters" note matches its words.
28fn preview_cut(body: &str, limit: usize) -> (&str, usize) {
29    match body.char_indices().nth(limit) {
30        Some((end, _)) => (&body[..end], body[end..].chars().count()),
31        None => (body, 0),
32    }
33}
34
35pub fn run(args: &[String]) {
36    let title = extract_flag(args, "--title");
37    let description = extract_flag(args, "--description");
38    let dry_run = args.iter().any(|a| a == "--dry-run");
39    let include_tee = args.iter().any(|a| a == "--include-tee");
40
41    println!("{BOLD}lean-ctx report-issue{RST}\n");
42
43    let title = title.unwrap_or_else(|| prompt_input("Issue title"));
44    if title.trim().is_empty() {
45        eprintln!("Title is required. Aborting.");
46        std::process::exit(1);
47    }
48    let description = description.unwrap_or_else(|| prompt_input("Describe the problem"));
49
50    println!("\n{DIM}Collecting diagnostics...{RST}");
51    let body = build_report_body(&title, &description, include_tee);
52
53    println!("\n{BOLD}=== Preview ==={RST}\n");
54    let (preview, more) = preview_cut(&body, PREVIEW_CHARS);
55    println!("{preview}");
56    if more > 0 {
57        println!("{DIM}... ({more} more characters){RST}");
58    }
59
60    if include_tee {
61        println!("\n{YELLOW}{INCLUDE_TEE_NOTICE}{RST}");
62    }
63
64    if include_tee {
65        println!("\n{YELLOW}{INCLUDE_TEE_NOTICE}{RST}");
66    }
67
68    if dry_run {
69        println!("\n{YELLOW}--dry-run: not submitting.{RST}");
70        if let Some(dir) = lean_ctx_dir() {
71            let path = dir.join("last-report.md");
72            let _ = std::fs::write(&path, &body);
73            println!("Report saved to {}", path.display());
74        }
75        return;
76    }
77
78    println!("\n{BOLD}Submit this as a GitHub issue to {REPO}?{RST} [y/N]");
79    let mut answer = String::new();
80    let _ = std::io::stdin().read_line(&mut answer);
81    if !answer.trim().eq_ignore_ascii_case("y") {
82        println!("Aborted.");
83        if let Some(dir) = lean_ctx_dir() {
84            let path = dir.join("last-report.md");
85            let _ = std::fs::write(&path, &body);
86            println!("Report saved to {}", path.display());
87        }
88        return;
89    }
90
91    if try_gh_cli(&title, &body) {
92        return;
93    }
94    try_ureq_api(&title, &body);
95}
96
97fn build_report_body(_title: &str, description: &str, include_tee: bool) -> String {
98    let mut sections = Vec::new();
99
100    sections.push(format!("## Description\n\n{description}"));
101    sections.push(section_environment());
102    sections.push(section_recent_crashes());
103    sections.push(section_configuration());
104    sections.push(section_mcp_status());
105    sections.push(section_tool_calls());
106    sections.push(section_session());
107    sections.push(section_performance());
108    sections.push(section_slow_commands());
109    sections.push(section_tee_logs(include_tee));
110    sections.push(section_project_context());
111
112    let body = sections.join("\n\n---\n\n");
113    // The report can become a public GitHub issue: every section, the raw
114    // `--include-tee` excerpt included, goes through the engine's always-on
115    // persistence redaction (the same pass the shell tee log uses), regardless
116    // of role or `[secret_detection]` settings.
117    crate::core::redaction::redact_text(&anonymize_report(&body))
118}
119
120// ── Section Builders ──────────────────────────────────────────────────────
121
122/// The last entries of the panic-hook crash log (`<data_dir>/logs/crash.log`).
123/// Without this, crash reports arrive with no location/payload and are not
124/// actionable (GitHub #386 shipped an empty report for a reproducible panic).
125fn section_recent_crashes() -> String {
126    let mut out = String::from("## Recent Crashes\n\n");
127    let log_path = crate::core::data_dir::lean_ctx_data_dir()
128        .ok()
129        .map(|d| d.join("logs").join("crash.log"));
130    let content = log_path
131        .as_ref()
132        .and_then(|p| std::fs::read_to_string(p).ok());
133    let Some(content) = content else {
134        out.push_str("No crash log found — no panics recorded on this machine.");
135        return out;
136    };
137
138    // Entries are separated by the `=== panic at` header; keep the newest 3
139    // and cap each backtrace so the report stays reviewable.
140    let entries: Vec<&str> = content
141        .split("=== panic at ")
142        .filter(|e| !e.trim().is_empty())
143        .collect();
144    if entries.is_empty() {
145        out.push_str("Crash log present but empty.");
146        return out;
147    }
148
149    out.push_str("```\n");
150    for entry in entries.iter().rev().take(3).rev() {
151        out.push_str("=== panic at ");
152        for line in entry.lines().take(14) {
153            out.push_str(line);
154            out.push('\n');
155        }
156        out.push_str("…\n\n");
157    }
158    out.push_str("```");
159    out
160}
161
162fn section_environment() -> String {
163    let os = std::env::consts::OS;
164    let arch = std::env::consts::ARCH;
165    let shell = std::env::var("SHELL").unwrap_or_else(|_| "unknown".into());
166    let ide = detect_ide();
167
168    format!(
169        "## Environment\n\n\
170         | Field | Value |\n|---|---|\n\
171         | lean-ctx | {VERSION} |\n\
172         | OS | {os} {arch} |\n\
173         | Shell | {shell} |\n\
174         | IDE | {ide} |"
175    )
176}
177
178fn section_configuration() -> String {
179    let mut out = String::from("## Configuration\n\n```toml\n");
180    if let Some(dir) = lean_ctx_dir() {
181        let config_path = dir.join("config.toml");
182        if let Ok(content) = std::fs::read_to_string(&config_path) {
183            let clean = mask_secrets(&content);
184            out.push_str(&clean);
185        } else {
186            out.push_str("# config.toml not found — using defaults");
187        }
188    }
189    out.push_str("\n```");
190    out
191}
192
193fn section_mcp_status() -> String {
194    let mut lines = vec!["## MCP Integration Status\n".to_string()];
195
196    let binary_ok = which_lean_ctx().is_some();
197    lines.push(format!(
198        "- Binary on PATH: {}",
199        if binary_ok { "yes" } else { "no" }
200    ));
201
202    let hooks = check_shell_hooks();
203    lines.push(format!("- Shell hooks: {hooks}"));
204
205    let ides = check_mcp_configs();
206    lines.push(format!("- MCP configured for: {ides}"));
207
208    lines.join("\n")
209}
210
211fn section_tool_calls() -> String {
212    let mut out = String::from("## Recent Tool Calls\n\n```\n");
213    if let Some(dir) = lean_ctx_dir() {
214        let log_path = dir.join("tool-calls.log");
215        if let Ok(content) = std::fs::read_to_string(&log_path) {
216            let lines: Vec<&str> = content.lines().collect();
217            let start = lines.len().saturating_sub(20);
218            for line in &lines[start..] {
219                out.push_str(line);
220                out.push('\n');
221            }
222        } else {
223            out.push_str("# No tool call log found\n");
224        }
225    }
226    out.push_str("```");
227    out
228}
229
230fn section_session() -> String {
231    let mut out = String::from("## Session State\n\n");
232    if let Some(dir) = lean_ctx_dir() {
233        let latest = dir.join("sessions").join("latest.json");
234        if let Ok(content) = std::fs::read_to_string(&latest) {
235            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
236                if let Some(task) = val.get("task") {
237                    out.push_str(&format!(
238                        "- Task: {}\n",
239                        task.get("description")
240                            .and_then(|d| d.as_str())
241                            .unwrap_or("-")
242                    ));
243                }
244                if let Some(stats) = val.get("stats") {
245                    out.push_str(&format!("- Stats: {stats}\n"));
246                }
247                if let Some(files) = val.get("files_touched").and_then(|f| f.as_object()) {
248                    out.push_str(&format!("- Files touched: {}\n", files.len()));
249                }
250            }
251        } else {
252            out.push_str("No active session found.\n");
253        }
254    }
255    out
256}
257
258fn section_performance() -> String {
259    let mut out = String::from("## Performance Metrics\n\n");
260    if let Some(dir) = lean_ctx_dir() {
261        let mcp_live = dir.join("mcp-live.json");
262        if let Ok(content) = std::fs::read_to_string(&mcp_live)
263            && let Ok(val) = serde_json::from_str::<serde_json::Value>(&content)
264        {
265            let fields = [
266                "cep_score",
267                "cache_utilization",
268                "compression_rate",
269                "tokens_saved",
270                "tokens_original",
271                "tool_calls",
272            ];
273            out.push_str("| Metric | Value |\n|---|---|\n");
274            for field in fields {
275                if let Some(v) = val.get(field) {
276                    out.push_str(&format!("| {field} | {v} |\n"));
277                }
278            }
279        }
280
281        let stats_path = dir.join("stats.json");
282        if let Ok(content) = std::fs::read_to_string(&stats_path)
283            && let Ok(val) = serde_json::from_str::<serde_json::Value>(&content)
284            && let Some(cmds) = val.get("commands").and_then(|c| c.as_object())
285        {
286            let mut top: Vec<_> = cmds
287                .iter()
288                .filter_map(|(k, v)| {
289                    v.get("count")
290                        .and_then(serde_json::Value::as_u64)
291                        .map(|c| (k, c))
292                })
293                .collect();
294            top.sort_by_key(|x| std::cmp::Reverse(x.1));
295            top.truncate(5);
296            out.push_str("\n**Top 5 tools:**\n");
297            for (name, count) in top {
298                out.push_str(&format!("- {name}: {count} calls\n"));
299            }
300        }
301    }
302    out
303}
304
305fn section_slow_commands() -> String {
306    let mut out = String::from("## Slow Commands\n\n```\n");
307    if let Some(dir) = lean_ctx_dir() {
308        let log_path = dir.join("slow-commands.log");
309        if let Ok(content) = std::fs::read_to_string(&log_path) {
310            let lines: Vec<&str> = content.lines().collect();
311            let start = lines.len().saturating_sub(10);
312            for line in &lines[start..] {
313                out.push_str(line);
314                out.push('\n');
315            }
316        } else {
317            out.push_str("# No slow commands logged\n");
318        }
319    }
320    out.push_str("```");
321    out
322}
323
324fn section_tee_logs(include_content: bool) -> String {
325    let mut out = String::from("## Tee Logs (last 24h)\n\n");
326    if let Some(tee_dir) = tee_dir() {
327        if tee_dir.is_dir() {
328            let cutoff = std::time::SystemTime::now() - std::time::Duration::from_hours(24);
329            let mut entries: Vec<_> = std::fs::read_dir(&tee_dir)
330                .into_iter()
331                .flatten()
332                .filter_map(std::result::Result::ok)
333                .filter(|e| {
334                    e.metadata()
335                        .ok()
336                        .and_then(|m| m.modified().ok())
337                        .is_some_and(|t| t > cutoff)
338                })
339                .collect();
340            entries.sort_by_key(|e| {
341                std::cmp::Reverse(
342                    e.metadata()
343                        .ok()
344                        .and_then(|m| m.modified().ok())
345                        .unwrap_or(std::time::SystemTime::UNIX_EPOCH),
346                )
347            });
348
349            if entries.is_empty() {
350                out.push_str("No tee logs in the last 24h.\n");
351            } else {
352                for entry in entries.iter().take(10) {
353                    let name = entry.file_name();
354                    let size = entry.metadata().map_or(0, |m| m.len());
355                    out.push_str(&format!("- `{}` ({size} bytes)\n", name.to_string_lossy()));
356                }
357                if include_content
358                    && let Some(latest) = entries.first()
359                    && let Ok(content) = std::fs::read_to_string(latest.path())
360                {
361                    let truncated: String = content.chars().take(3000).collect();
362                    out.push_str(&format!(
363                        "\n**Latest tee content (`{}`):**\n```\n{truncated}\n```",
364                        latest.file_name().to_string_lossy()
365                    ));
366                }
367            }
368        } else {
369            out.push_str("No tee directory found.\n");
370        }
371    }
372    out
373}
374
375fn section_project_context() -> String {
376    let mut out = String::from("## Project Context\n\n");
377    let cwd = std::env::current_dir()
378        .map_or_else(|_| "unknown".into(), |p| p.to_string_lossy().to_string());
379    out.push_str(&format!("- Working directory: {cwd}\n"));
380
381    if let Ok(entries) = std::fs::read_dir(".") {
382        let count = entries.filter_map(std::result::Result::ok).count();
383        out.push_str(&format!("- Files in root: {count}\n"));
384    }
385    out
386}
387
388// ── Anonymization ─────────────────────────────────────────────────────────
389
390fn anonymize_report(text: &str) -> String {
391    let home = dirs::home_dir()
392        .map(|h| h.to_string_lossy().to_string())
393        .unwrap_or_default();
394
395    let mut result = text.to_string();
396    if !home.is_empty() {
397        result = result.replace(&home, "~");
398    }
399
400    let user = std::env::var("USER")
401        .or_else(|_| std::env::var("USERNAME"))
402        .unwrap_or_default();
403    if user.len() > 2 {
404        result = result.replace(&user, "<user>");
405    }
406
407    result
408}
409
410fn mask_secrets(text: &str) -> String {
411    let mut out = String::new();
412    for line in text.lines() {
413        if line.contains("token")
414            || line.contains("key")
415            || line.contains("secret")
416            || line.contains("password")
417            || line.contains("api_key")
418        {
419            if let Some(eq) = line.find('=') {
420                out.push_str(&line[..=eq]);
421                out.push_str(" \"[REDACTED]\"");
422            } else {
423                out.push_str(line);
424            }
425        } else {
426            out.push_str(line);
427        }
428        out.push('\n');
429    }
430    out
431}
432
433// ── GitHub Submission ─────────────────────────────────────────────────────
434
435fn find_gh_binary() -> Option<std::path::PathBuf> {
436    let candidates = [
437        "/opt/homebrew/bin/gh",
438        "/usr/local/bin/gh",
439        "/usr/bin/gh",
440        "/home/linuxbrew/.linuxbrew/bin/gh",
441    ];
442    for c in &candidates {
443        let p = std::path::Path::new(c);
444        if p.exists() {
445            return Some(p.to_path_buf());
446        }
447    }
448    if let Ok(output) = std::process::Command::new("which").arg("gh").output()
449        && output.status.success()
450    {
451        let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
452        if !path.is_empty() {
453            return Some(std::path::PathBuf::from(path));
454        }
455    }
456    None
457}
458
459fn try_gh_cli(title: &str, body: &str) -> bool {
460    let Some(gh) = find_gh_binary() else {
461        return false;
462    };
463
464    let tmp = std::env::temp_dir().join("lean-ctx-report.md");
465    if std::fs::write(&tmp, body).is_err() {
466        return false;
467    }
468
469    let result = std::process::Command::new(&gh)
470        .args([
471            "issue",
472            "create",
473            "--repo",
474            REPO,
475            "--title",
476            title,
477            "--body-file",
478            &tmp.to_string_lossy(),
479            "--label",
480            "bug,auto-report",
481        ])
482        .output();
483
484    if let Ok(ref output) = result
485        && !output.status.success()
486    {
487        let stderr = String::from_utf8_lossy(&output.stderr);
488        if stderr.contains("not found") && stderr.contains("label") {
489            let _ = std::fs::remove_file(&tmp);
490            let fallback = std::process::Command::new(&gh)
491                .args([
492                    "issue",
493                    "create",
494                    "--repo",
495                    REPO,
496                    "--title",
497                    title,
498                    "--body-file",
499                    &tmp.to_string_lossy(),
500                ])
501                .output();
502            let _ = std::fs::remove_file(&tmp);
503            if let Ok(fb_out) = fallback
504                && fb_out.status.success()
505            {
506                let url = String::from_utf8_lossy(&fb_out.stdout);
507                println!("\n{GREEN}Issue created:{RST} {}", url.trim());
508                return true;
509            }
510            return false;
511        }
512    }
513
514    let _ = std::fs::remove_file(&tmp);
515
516    match result {
517        Ok(output) if output.status.success() => {
518            let url = String::from_utf8_lossy(&output.stdout);
519            println!("\n{GREEN}Issue created:{RST} {}", url.trim());
520            true
521        }
522        Ok(output) => {
523            let stderr = String::from_utf8_lossy(&output.stderr);
524            if stderr.contains("not logged") || stderr.contains("auth login") {
525                eprintln!("{YELLOW}gh CLI found but not authenticated. Run: gh auth login{RST}");
526            } else {
527                eprintln!("{YELLOW}gh issue create failed: {}{RST}", stderr.trim());
528            }
529            false
530        }
531        Err(e) => {
532            eprintln!("{YELLOW}Failed to run gh: {e}{RST}");
533            false
534        }
535    }
536}
537
538fn try_ureq_api(title: &str, body: &str) {
539    println!("\n{YELLOW}gh CLI not available. Using GitHub API directly.{RST}");
540    println!("Enter a GitHub Personal Access Token (needs 'repo' scope):");
541    println!("{DIM}Create one at: https://github.com/settings/tokens/new{RST}");
542
543    // Read without echo so the token never appears on screen or in a
544    // terminal recording; no TTY means no token (the report is saved).
545    let token = rpassword::prompt_password("Token (input hidden): ").unwrap_or_default();
546    let token = token.trim();
547
548    if token.is_empty() {
549        eprintln!("No token provided. Saving report locally.");
550        save_report_locally(body);
551        return;
552    }
553
554    let url = format!("https://api.github.com/repos/{REPO}/issues");
555    let payload = serde_json::json!({
556        "title": title,
557        "body": body,
558        "labels": ["bug", "auto-report"]
559    });
560
561    let payload_bytes = serde_json::to_vec(&payload).unwrap_or_default();
562    match ureq::post(&url)
563        .header("Authorization", &format!("Bearer {token}"))
564        .header("Accept", "application/vnd.github.v3+json")
565        .header("Content-Type", "application/json")
566        .header("User-Agent", &format!("lean-ctx/{VERSION}"))
567        .send(payload_bytes.as_slice())
568    {
569        Ok(resp) => {
570            let resp_body = resp.into_body().read_to_string().unwrap_or_default();
571            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&resp_body)
572                && let Some(html_url) = val.get("html_url").and_then(|u| u.as_str())
573            {
574                println!("\n{GREEN}Issue created:{RST} {html_url}");
575                return;
576            }
577            println!("{GREEN}Issue created successfully.{RST}");
578        }
579        Err(e) => {
580            eprintln!("GitHub API error: {e}");
581            save_report_locally(body);
582        }
583    }
584}
585
586fn save_report_locally(body: &str) {
587    if let Some(dir) = lean_ctx_dir() {
588        let path = dir.join("last-report.md");
589        let _ = std::fs::write(&path, body);
590        println!("Report saved to {}", path.display());
591    }
592}
593
594// ── Helpers ───────────────────────────────────────────────────────────────
595
596fn lean_ctx_dir() -> Option<PathBuf> {
597    dirs::home_dir().map(|h| h.join(".lean-ctx"))
598}
599
600/// The tee store every writer uses (`<state>/tee`, honouring
601/// `LEAN_CTX_STATE_DIR`), resolved without creating directories. The legacy
602/// `~/.lean-ctx/tee` holds no live tee logs.
603fn tee_dir() -> Option<PathBuf> {
604    crate::core::paths::state_dir_read_only()
605        .ok()
606        .map(|state| state.join("tee"))
607}
608
609fn which_lean_ctx() -> Option<PathBuf> {
610    let cmd = if cfg!(windows) { "where" } else { "which" };
611    std::process::Command::new(cmd)
612        .arg("lean-ctx")
613        .output()
614        .ok()
615        .filter(|o| o.status.success())
616        .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim().to_string()))
617}
618
619fn check_shell_hooks() -> String {
620    let Some(home) = dirs::home_dir() else {
621        return "unknown".into();
622    };
623
624    let mut found = Vec::new();
625    let shells = [
626        (".zshrc", "zsh"),
627        (".bashrc", "bash"),
628        (".config/fish/config.fish", "fish"),
629    ];
630    for (file, name) in shells {
631        let path = home.join(file);
632        if let Ok(content) = std::fs::read_to_string(&path)
633            && content.contains("lean-ctx")
634        {
635            found.push(name);
636        }
637    }
638
639    if found.is_empty() {
640        "none detected".into()
641    } else {
642        found.join(", ")
643    }
644}
645
646fn check_mcp_configs() -> String {
647    let Some(home) = dirs::home_dir() else {
648        return "unknown".into();
649    };
650
651    let mut found = Vec::new();
652    let claude_cfg = crate::core::editor_registry::claude_mcp_json_path(&home);
653    let codebuddy_cfg = crate::core::editor_registry::codebuddy_mcp_json_path(&home);
654    let configs: Vec<(std::path::PathBuf, &str)> = vec![
655        (home.join(".cursor/mcp.json"), "Cursor"),
656        (claude_cfg, "Claude Code"),
657        (codebuddy_cfg, "CodeBuddy"),
658        (home.join(".codeium/windsurf/mcp_config.json"), "Windsurf"),
659    ];
660
661    for (full, name) in &configs {
662        if let Ok(content) = std::fs::read_to_string(full)
663            && content.contains("lean-ctx")
664        {
665            found.push(*name);
666        }
667    }
668
669    if found.is_empty() {
670        "none".into()
671    } else {
672        found.join(", ")
673    }
674}
675
676fn detect_ide() -> String {
677    if std::env::var("CURSOR_SESSION").is_ok() || std::env::var("CURSOR_TRACE_DIR").is_ok() {
678        return "Cursor".into();
679    }
680    if std::env::var("VSCODE_PID").is_ok() {
681        return "VS Code".into();
682    }
683    "unknown".into()
684}
685
686fn extract_flag(args: &[String], flag: &str) -> Option<String> {
687    args.windows(2).find(|w| w[0] == flag).map(|w| w[1].clone())
688}
689
690fn prompt_input(label: &str) -> String {
691    eprint!("{BOLD}{label}:{RST} ");
692    let mut input = String::new();
693    let _ = std::io::stdin().read_line(&mut input);
694    input.trim().to_string()
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700
701    /// The preview cut and its "more characters" count both count chars:
702    /// a byte count overstated the remainder of a multi-byte body.
703    #[test]
704    fn preview_cut_counts_characters_of_multi_byte_text() {
705        let body = "äöü€😀".repeat(3); // 15 chars, 42 bytes
706        assert_eq!(body.chars().count(), 15);
707
708        let (head, more) = preview_cut(&body, 7);
709        assert_eq!(head, "äöü€😀äö");
710        assert_eq!(more, 8, "remaining characters, not bytes");
711
712        assert_eq!(preview_cut(&body, 15), (body.as_str(), 0));
713        assert_eq!(preview_cut(&body, 2000), (body.as_str(), 0));
714        assert_eq!(preview_cut("", PREVIEW_CHARS), ("", 0));
715    }
716
717    #[test]
718    fn report_body_redacts_secrets_before_submission() {
719        let github = format!("ghp_{}", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8");
720        let aws = format!("AKIA{}", "IOSFODNN7EXAMPLE");
721        let description = format!("tee showed GITHUB_TOKEN={github}\naws {aws}");
722        let body = build_report_body("t", &description, true);
723        assert!(!body.contains(&github), "GitHub token leaked into report");
724        assert!(!body.contains(&aws), "AWS key leaked into report");
725        assert!(body.contains("[REDACTED"), "no redaction marker in report");
726    }
727
728    /// The report lists the tee logs the writers produced: under
729    /// `LEAN_CTX_STATE_DIR/tee`, not the legacy `~/.lean-ctx/tee`.
730    #[test]
731    fn tee_section_reads_the_state_dir_tee_store() {
732        let state = tempfile::tempdir().expect("state dir");
733        // Holds the test env lock and restores the previous value on drop.
734        let _state_env = crate::test_env::EnvVarGuard::set(
735            "LEAN_CTX_STATE_DIR",
736            state.path().to_str().expect("utf-8 temp path"),
737        );
738        let tee = state.path().join("tee");
739        std::fs::create_dir_all(&tee).expect("tee dir");
740        std::fs::write(tee.join("proxy_0123456789abcdef.log"), "state tee body\n")
741            .expect("tee log");
742
743        let resolved = tee_dir();
744        let section = section_tee_logs(true);
745
746        assert_eq!(resolved.as_deref(), Some(tee.as_path()));
747        assert!(
748            section.contains("proxy_0123456789abcdef.log") && section.contains("state tee body"),
749            "report must list the state-dir tee log: {section}"
750        );
751    }
752
753    /// `--include-tee` puts real command output from the state dir into the
754    /// issue body; a secret in that output must be redacted like the rest.
755    #[test]
756    fn include_tee_content_is_redacted_in_the_report_body() {
757        let state = tempfile::tempdir().expect("state dir");
758        let _state_env = crate::test_env::EnvVarGuard::set(
759            "LEAN_CTX_STATE_DIR",
760            state.path().to_str().expect("utf-8 temp path"),
761        );
762        let tee = state.path().join("tee");
763        std::fs::create_dir_all(&tee).expect("tee dir");
764        // Obviously fake, built at runtime so no literal token sits in source.
765        let fake = format!("sk-test-{}", "FAKEFAKEFAKE");
766        std::fs::write(
767            tee.join("shell_fedcba9876543210.log"),
768            format!("$ env\nOPENAI_API_KEY={fake}\nok\n"),
769        )
770        .expect("tee log");
771
772        let body = build_report_body("t", "d", true);
773
774        assert!(
775            body.contains("shell_fedcba9876543210.log") && body.contains("Latest tee content"),
776            "tee excerpt missing from report: {body}"
777        );
778        assert!(!body.contains(&fake), "tee secret leaked into report");
779        assert!(body.contains("[REDACTED"), "no redaction marker in report");
780    }
781}