1use serde::Serialize;
13
14use super::checks::{
15 capacity_warnings, mcp_config_outcome, mcp_server_cwd_outcome, shell_aliases_outcome,
16 skill_files_outcome,
17};
18use super::common::{path_in_path_env, resolve_lean_ctx_binary};
19use super::deprecations::deprecations_outcome;
20
21#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)]
23#[serde(rename_all = "lowercase")]
24pub enum HealthLevel {
25 Good,
27 Warnings,
29 Issues,
31}
32
33#[derive(Serialize)]
35pub struct HealthCheck {
36 pub id: &'static str,
37 pub ok: bool,
38 pub detail: String,
39}
40
41#[derive(Serialize)]
43pub struct HealthReport {
44 pub level: HealthLevel,
45 pub passed: u32,
46 pub total: u32,
47 pub checks: Vec<HealthCheck>,
48 pub warnings: Vec<String>,
49}
50
51impl HealthReport {
52 fn classify(passed: u32, total: u32, has_warnings: bool) -> HealthLevel {
56 if passed < total {
57 HealthLevel::Issues
58 } else if has_warnings {
59 HealthLevel::Warnings
60 } else {
61 HealthLevel::Good
62 }
63 }
64}
65
66fn check(id: &'static str, ok: bool, pass: &str, fail: &str) -> HealthCheck {
67 HealthCheck {
68 id,
69 ok,
70 detail: if ok { pass } else { fail }.to_string(),
71 }
72}
73
74fn strip_ansi(s: &str) -> String {
77 let mut out = String::with_capacity(s.len());
78 let mut chars = s.chars();
79 while let Some(c) = chars.next() {
80 if c == '\u{1b}' {
81 for next in chars.by_ref() {
83 if next == 'm' {
84 break;
85 }
86 }
87 } else {
88 out.push(c);
89 }
90 }
91 out.split_whitespace().collect::<Vec<_>>().join(" ")
92}
93
94#[must_use]
96pub fn health_report() -> HealthReport {
97 let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
98
99 let binary_ok = resolve_lean_ctx_binary().is_some() || path_in_path_env();
100 let data_dir_ok = data_dir.as_ref().is_some_and(|p| p.is_dir());
101 let stats_ok = data_dir
102 .as_ref()
103 .map(|d| d.join("stats.json"))
104 .and_then(|p| std::fs::metadata(p).ok())
105 .is_some_and(|m| m.is_file());
106
107 let shell_ok = shell_aliases_outcome().ok;
111 let mcp_ok = mcp_config_outcome().ok;
112 let skills_ok = skill_files_outcome().ok;
113
114 let checks = vec![
115 check(
116 "binary",
117 binary_ok,
118 "lean-ctx is on your PATH",
119 "lean-ctx is not on your PATH — run `lean-ctx init`",
120 ),
121 check(
122 "data_dir",
123 data_dir_ok,
124 "data directory present",
125 "data directory missing — it is created on first use",
126 ),
127 check(
128 "stats",
129 stats_ok,
130 "usage statistics are being recorded",
131 "no usage statistics yet — route a few commands through lean-ctx",
132 ),
133 check(
134 "shell",
135 shell_ok,
136 "shell integration active",
137 "shell integration not detected — run `lean-ctx init --global`",
138 ),
139 check(
140 "mcp",
141 mcp_ok,
142 "MCP server registered",
143 "MCP server not registered — click Fix or run `lean-ctx doctor --fix`",
144 ),
145 check(
146 "skills",
147 skills_ok,
148 "agent skill files installed",
149 "agent skill files missing — click Fix or run `lean-ctx doctor --fix`",
150 ),
151 ];
152
153 let passed = u32::try_from(checks.iter().filter(|c| c.ok).count()).unwrap_or(u32::MAX);
154 let total = u32::try_from(checks.len()).unwrap_or(u32::MAX);
155
156 let mut warnings: Vec<String> = capacity_warnings()
159 .into_iter()
160 .filter(|o| !o.ok)
161 .map(|o| strip_ansi(&o.line))
162 .collect();
163 let dep = deprecations_outcome();
164 if !dep.ok {
165 warnings.push(strip_ansi(&dep.line));
166 }
167 let mcp_cwd = mcp_server_cwd_outcome();
168 if !mcp_cwd.ok {
169 warnings.push(strip_ansi(&mcp_cwd.line));
170 }
171
172 let level = HealthReport::classify(passed, total, !warnings.is_empty());
173
174 HealthReport {
175 level,
176 passed,
177 total,
178 checks,
179 warnings,
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn strip_ansi_removes_colour_and_collapses_whitespace() {
189 let raw = "\u{1b}[1mShell\u{1b}[0m \u{1b}[32mconfigured\u{1b}[0m\n in ~/.zshrc";
190 assert_eq!(strip_ansi(raw), "Shell configured in ~/.zshrc");
191 }
192
193 #[test]
194 fn strip_ansi_is_idempotent_on_plain_text() {
195 assert_eq!(strip_ansi("already clean"), "already clean");
196 }
197
198 #[test]
199 fn classify_issues_when_any_check_failed() {
200 assert_eq!(
201 HealthReport::classify(5, 6, false),
202 HealthLevel::Issues,
203 "a failed scored check always wins over advisories"
204 );
205 assert_eq!(HealthReport::classify(5, 6, true), HealthLevel::Issues);
206 }
207
208 #[test]
209 fn classify_warnings_when_clean_but_advisories() {
210 assert_eq!(HealthReport::classify(6, 6, true), HealthLevel::Warnings);
211 }
212
213 #[test]
214 fn classify_good_when_spotless() {
215 assert_eq!(HealthReport::classify(6, 6, false), HealthLevel::Good);
216 }
217
218 #[test]
222 fn health_report_is_self_consistent() {
223 let r = health_report();
224 assert_eq!(r.total, 6, "six scored install checks");
225 assert_eq!(
226 r.passed,
227 u32::try_from(r.checks.iter().filter(|c| c.ok).count()).unwrap(),
228 "passed must equal the number of green checks"
229 );
230 let expected = HealthReport::classify(r.passed, r.total, !r.warnings.is_empty());
231 assert_eq!(
232 r.level, expected,
233 "level must follow the classification rule"
234 );
235 for c in &r.checks {
236 assert!(!c.detail.contains('\u{1b}'), "no ANSI in check detail");
237 assert!(!c.detail.is_empty(), "`c.detail` is empty");
238 }
239 for w in &r.warnings {
240 assert!(!w.contains('\u{1b}'), "no ANSI in warnings");
241 }
242 }
243
244 #[test]
245 fn report_serializes_with_lowercase_level() {
246 let report = HealthReport {
247 level: HealthLevel::Warnings,
248 passed: 6,
249 total: 6,
250 checks: vec![check("binary", true, "ok", "bad")],
251 warnings: vec!["facts: 206/200 (103%)".to_string()],
252 };
253 let json = serde_json::to_string(&report).unwrap();
254 assert!(json.contains(r#""level":"warnings""#));
255 assert!(json.contains(r#""id":"binary""#));
256 assert!(json.contains(r#""passed":6"#));
257 }
258}