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