Skip to main content

lean_ctx_cli/
status.rs

1// SPDX-License-Identifier: Apache-2.0
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct StatusReport {
7    pub schema_version: u32,
8    pub generated_at: DateTime<Utc>,
9    pub version: String,
10    pub setup_report: Option<lean_ctx::core::setup_report::SetupReport>,
11    pub doctor_compact_passed: u32,
12    pub doctor_compact_total: u32,
13    pub mcp_targets: Vec<McpTargetStatus>,
14    pub rules_targets: Vec<lean_ctx::rules_inject::RulesTargetStatus>,
15    pub warnings: Vec<String>,
16    pub errors: Vec<String>,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct McpTargetStatus {
21    pub name: String,
22    pub detected: bool,
23    pub config_path: String,
24    pub state: String,
25    pub note: Option<String>,
26}
27
28pub fn run_cli(args: &[String]) -> i32 {
29    let json = args.iter().any(|a| a == "--json");
30    let help = args.iter().any(|a| a == "--help" || a == "-h");
31    if help {
32        println!("Usage:");
33        println!("  lean-ctx status [--json]");
34        return 0;
35    }
36
37    // Refresh the latest-version cache opportunistically (#563) so the
38    // update hint below never advertises a stale "latest".
39    lean_ctx::core::version_check::check_background();
40
41    match build_status_report() {
42        Ok((mut report, path)) => {
43            let saved = save_report(&report, &path).map_err(|error| report.errors.push(error));
44            let text = serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string());
45
46            if json {
47                println!("{text}");
48            } else {
49                print_human(&report, saved.is_ok().then_some(path.as_path()));
50                if let Some(banner) = lean_ctx::core::version_check::get_update_banner() {
51                    println!("\n{banner}");
52                }
53            }
54
55            i32::from(!report.errors.is_empty())
56        }
57        Err(e) => {
58            eprintln!("{e}");
59            2
60        }
61    }
62}
63
64/// Persist a report as pretty JSON. A failed write is the report's error:
65/// it was the one thing the command could not do, so it must not exit 0
66/// (shared with `token-report`).
67pub(crate) fn save_report<T: Serialize>(report: &T, path: &std::path::Path) -> Result<(), String> {
68    let text = serde_json::to_string_pretty(report)
69        .map_err(|error| format!("cannot serialize the report: {error}"))?;
70    lean_ctx::config_io::write_atomic_with_backup(path, &text)
71        .map_err(|error| format!("cannot save the report to {}: {error}", path.display()))
72}
73
74fn build_status_report() -> Result<(StatusReport, std::path::PathBuf), String> {
75    let generated_at = Utc::now();
76    let version = env!("CARGO_PKG_VERSION").to_string();
77    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
78
79    let mut warnings: Vec<String> = Vec::new();
80    let errors: Vec<String> = Vec::new();
81
82    let setup_report = {
83        let path = lean_ctx::core::setup_report::SetupReport::default_path()?;
84        if path.exists() {
85            match std::fs::read_to_string(&path) {
86                Ok(s) => {
87                    match serde_json::from_str::<lean_ctx::core::setup_report::SetupReport>(&s) {
88                        Ok(r) => Some(r),
89                        Err(e) => {
90                            warnings.push(format!("setup report parse error: {e}"));
91                            None
92                        }
93                    }
94                }
95                Err(e) => {
96                    warnings.push(format!("setup report read error: {e}"));
97                    None
98                }
99            }
100        } else {
101            None
102        }
103    };
104
105    let (doctor_compact_passed, doctor_compact_total) = crate::doctor::compact_score();
106
107    // MCP targets (registry based)
108    let targets = lean_ctx::core::editor_registry::build_targets(&home);
109    let mut mcp_targets: Vec<McpTargetStatus> = Vec::new();
110    for t in &targets {
111        let detected = t.detect_path.exists();
112        let config_path = t.config_path.to_string_lossy().to_string();
113
114        let state = if !detected {
115            "not_detected".to_string()
116        } else if !t.config_path.exists() {
117            "missing_file".to_string()
118        } else {
119            match std::fs::read_to_string(&t.config_path) {
120                Ok(s) => {
121                    if s.contains("lean-ctx") {
122                        "configured".to_string()
123                    } else {
124                        "missing_entry".to_string()
125                    }
126                }
127                Err(e) => {
128                    warnings.push(format!("mcp config read error for {}: {e}", t.name));
129                    "read_error".to_string()
130                }
131            }
132        };
133
134        if detected {
135            mcp_targets.push(McpTargetStatus {
136                name: t.name.to_string(),
137                detected,
138                config_path,
139                state,
140                note: None,
141            });
142        }
143    }
144
145    if mcp_targets.is_empty() {
146        warnings.push("no supported AI tools detected".to_string());
147    }
148
149    let rules_targets = lean_ctx::rules_inject::collect_rules_status(&home);
150
151    let path = lean_ctx::core::setup_report::status_report_path()?;
152
153    let report = StatusReport {
154        schema_version: 1,
155        generated_at,
156        version,
157        setup_report,
158        doctor_compact_passed,
159        doctor_compact_total,
160        mcp_targets,
161        rules_targets,
162        warnings,
163        errors,
164    };
165
166    Ok((report, path))
167}
168
169fn print_human(report: &StatusReport, saved_to: Option<&std::path::Path>) {
170    println!("lean-ctx status  v{}", report.version);
171    let cfg = lean_ctx::core::config::Config::load();
172    let hosts = dirs::home_dir()
173        .map(|home| crate::doctor::shadow_hosts(&home))
174        .unwrap_or_default();
175    let (state, detail) = crate::doctor::shadow_status(cfg.shadow_mode, &hosts);
176    if state == "active" && !lean_ctx::core::theme::no_color() {
177        println!("  shadow_mode: \x1b[32m{state}\x1b[0m {detail}");
178    } else {
179        println!("  shadow_mode: {state} {detail}");
180    }
181    println!(
182        "  doctor: {}/{}",
183        report.doctor_compact_passed, report.doctor_compact_total
184    );
185
186    if let Some(setup) = &report.setup_report {
187        println!(
188            "  last setup: {}  success={}",
189            setup.finished_at.to_rfc3339(),
190            setup.success
191        );
192    } else if report.doctor_compact_passed == report.doctor_compact_total {
193        println!("  last setup: (manual install — all checks pass)");
194    } else {
195        println!("  last setup: (none) — run `lean-ctx onboard` to configure");
196    }
197
198    let detected = report.mcp_targets.len();
199    let configured = report
200        .mcp_targets
201        .iter()
202        .filter(|t| t.state == "configured")
203        .count();
204    println!("  mcp: {configured}/{detected} configured (detected tools)");
205
206    let rules_detected = report.rules_targets.iter().filter(|t| t.detected).count();
207    let rules_up_to_date = report
208        .rules_targets
209        .iter()
210        .filter(|t| t.detected && t.state == "up_to_date")
211        .count();
212    println!("  rules: {rules_up_to_date}/{rules_detected} up-to-date (detected tools)");
213
214    if !report.warnings.is_empty() {
215        println!("  warnings: {}", report.warnings.len());
216    }
217    if !report.errors.is_empty() {
218        println!("  errors: {}", report.errors.len());
219    }
220    for error in &report.errors {
221        eprintln!("error: {error}");
222    }
223    if let Some(path) = saved_to {
224        println!("  report saved: {}", path.display());
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    /// F9c: `status`/`token-report` used to ignore a failed report write and
231    /// always exit 0. The failure is now the report's error.
232    #[test]
233    fn a_failed_report_write_is_an_error() {
234        let dir = tempfile::tempdir().unwrap();
235        let blocker = dir.path().join("blocker");
236        std::fs::write(&blocker, "a file, not a directory").unwrap();
237        let error =
238            super::save_report(&serde_json::json!({}), &blocker.join("status.json")).unwrap_err();
239        assert!(error.contains("cannot save the report"), "{error}");
240
241        let ok = dir.path().join("status.json");
242        super::save_report(&serde_json::json!({ "a": 1 }), &ok).unwrap();
243        assert!(std::fs::read_to_string(&ok).unwrap().contains("\"a\": 1"));
244    }
245}