Skip to main content

lean_ctx_cli/
status.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx_time::UtcDateTime;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct StatusReport {
7    pub schema_version: u32,
8    pub generated_at: UtcDateTime,
9    pub version: String,
10    pub setup_report: Option<lean_ctx_ext::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 = UtcDateTime::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_ext::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_ext::core::setup_report::SetupReport>(&s)
88                    {
89                        Ok(r) => Some(r),
90                        Err(e) => {
91                            warnings.push(format!("setup report parse error: {e}"));
92                            None
93                        }
94                    }
95                }
96                Err(e) => {
97                    warnings.push(format!("setup report read error: {e}"));
98                    None
99                }
100            }
101        } else {
102            None
103        }
104    };
105
106    let (doctor_compact_passed, doctor_compact_total) = crate::doctor::compact_score();
107
108    // MCP targets (registry based)
109    let targets = lean_ctx::core::editor_registry::build_targets(&home);
110    let mut mcp_targets: Vec<McpTargetStatus> = Vec::new();
111    for t in &targets {
112        let detected = t.detect_path.exists();
113        let config_path = t.config_path.to_string_lossy().to_string();
114
115        let state = if !detected {
116            "not_detected".to_string()
117        } else if !t.config_path.exists() {
118            "missing_file".to_string()
119        } else {
120            match std::fs::read_to_string(&t.config_path) {
121                Ok(s) => {
122                    if s.contains("lean-ctx") {
123                        "configured".to_string()
124                    } else {
125                        "missing_entry".to_string()
126                    }
127                }
128                Err(e) => {
129                    warnings.push(format!("mcp config read error for {}: {e}", t.name));
130                    "read_error".to_string()
131                }
132            }
133        };
134
135        if detected {
136            mcp_targets.push(McpTargetStatus {
137                name: t.name.to_string(),
138                detected,
139                config_path,
140                state,
141                note: None,
142            });
143        }
144    }
145
146    if mcp_targets.is_empty() {
147        warnings.push("no supported AI tools detected".to_string());
148    }
149
150    let rules_targets = lean_ctx::rules_inject::collect_rules_status(&home);
151
152    let path = lean_ctx_ext::core::setup_report::status_report_path()?;
153
154    let report = StatusReport {
155        schema_version: 1,
156        generated_at,
157        version,
158        setup_report,
159        doctor_compact_passed,
160        doctor_compact_total,
161        mcp_targets,
162        rules_targets,
163        warnings,
164        errors,
165    };
166
167    Ok((report, path))
168}
169
170fn print_human(report: &StatusReport, saved_to: Option<&std::path::Path>) {
171    println!("lean-ctx status  v{}", report.version);
172    let cfg = lean_ctx::core::config::Config::load();
173    let hosts = dirs::home_dir()
174        .map(|home| crate::doctor::shadow_hosts(&home))
175        .unwrap_or_default();
176    let (state, detail) = crate::doctor::shadow_status(cfg.shadow_mode, &hosts);
177    if state == "active" && !lean_ctx::core::theme::no_color() {
178        println!("  shadow_mode: \x1b[32m{state}\x1b[0m {detail}");
179    } else {
180        println!("  shadow_mode: {state} {detail}");
181    }
182    println!(
183        "  doctor: {}/{}",
184        report.doctor_compact_passed, report.doctor_compact_total
185    );
186    println!(
187        "  usage: {}",
188        lean_ctx::core::stats::display_calls_saved_line()
189    );
190
191    if let Some(setup) = &report.setup_report {
192        println!(
193            "  last setup: {}  success={}",
194            setup.finished_at.to_rfc3339(),
195            setup.success
196        );
197    } else if report.doctor_compact_passed == report.doctor_compact_total {
198        println!("  last setup: (manual install — all checks pass)");
199    } else {
200        println!("  last setup: (none) — run `lean-ctx onboard` to configure");
201    }
202
203    let detected = report.mcp_targets.len();
204    let configured = report
205        .mcp_targets
206        .iter()
207        .filter(|t| t.state == "configured")
208        .count();
209    println!("  mcp: {configured}/{detected} configured (detected tools)");
210
211    let rules_detected = report.rules_targets.iter().filter(|t| t.detected).count();
212    let rules_up_to_date = report
213        .rules_targets
214        .iter()
215        .filter(|t| t.detected && t.state == "up_to_date")
216        .count();
217    println!("  rules: {rules_up_to_date}/{rules_detected} up-to-date (detected tools)");
218    for line in crate::doctor::empty_session_lines() {
219        println!("  clients: {line}");
220    }
221
222    if !report.warnings.is_empty() {
223        println!("  warnings: {}", report.warnings.len());
224    }
225    if !report.errors.is_empty() {
226        println!("  errors: {}", report.errors.len());
227    }
228    for error in &report.errors {
229        eprintln!("error: {error}");
230    }
231    if let Some(path) = saved_to {
232        println!("  report saved: {}", path.display());
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    /// F9c: `status`/`token-report` used to ignore a failed report write and
239    /// always exit 0. The failure is now the report's error.
240    #[test]
241    fn a_failed_report_write_is_an_error() {
242        let dir = tempfile::tempdir().unwrap();
243        let blocker = dir.path().join("blocker");
244        std::fs::write(&blocker, "a file, not a directory").unwrap();
245        let error =
246            super::save_report(&serde_json::json!({}), &blocker.join("status.json")).unwrap_err();
247        assert!(error.contains("cannot save the report"), "{error}");
248
249        let ok = dir.path().join("status.json");
250        super::save_report(&serde_json::json!({ "a": 1 }), &ok).unwrap();
251        assert!(std::fs::read_to_string(&ok).unwrap().contains("\"a\": 1"));
252    }
253}