1use crate::config::ProxyConfig;
6use firstpass_core::{Mode, Trace};
7
8#[derive(Debug, PartialEq, Eq)]
10pub enum CheckStatus {
11 Ok,
13 Warn,
15 Fail,
17}
18
19#[derive(Debug)]
21pub struct Check {
22 pub name: String,
24 pub status: CheckStatus,
26 pub detail: String,
28}
29
30impl Check {
31 fn new(name: impl Into<String>, status: CheckStatus, detail: impl Into<String>) -> Self {
32 Self {
33 name: name.into(),
34 status,
35 detail: detail.into(),
36 }
37 }
38}
39
40#[derive(Debug)]
42pub struct DoctorReport {
43 pub checks: Vec<Check>,
45}
46
47impl DoctorReport {
48 #[must_use]
50 pub fn healthy(&self) -> bool {
51 self.checks.iter().all(|c| c.status != CheckStatus::Fail)
52 }
53
54 #[must_use]
56 pub fn render(&self) -> String {
57 let mut out = String::new();
58 for c in &self.checks {
59 let mark = match c.status {
60 CheckStatus::Ok => "✓",
61 CheckStatus::Warn => "!",
62 CheckStatus::Fail => "✗",
63 };
64 out.push_str(&format!("{mark} {}: {}\n", c.name, c.detail));
65 }
66 out.push_str(if self.healthy() {
67 "\nhealthy — ready to route.\n"
68 } else {
69 "\nnot healthy — fix the ✗ items above.\n"
70 });
71 out
72 }
73}
74
75#[must_use]
79pub fn doctor(config: &ProxyConfig, env: impl Fn(&str) -> Option<String>) -> DoctorReport {
80 let mut checks = Vec::new();
81
82 let route_count = config.routing.as_ref().map_or(0, |c| c.routes.len());
84 checks.push(Check::new(
85 "config",
86 CheckStatus::Ok,
87 format!("default mode {:?}, {route_count} route(s)", config.mode),
88 ));
89
90 let enforce_routes = config.routing.as_ref().map_or(0, |c| {
92 c.routes.iter().filter(|r| r.mode == Mode::Enforce).count()
93 });
94 if config.mode == Mode::Enforce && enforce_routes == 0 {
95 checks.push(Check::new(
96 "routing",
97 CheckStatus::Warn,
98 "mode is enforce but no enforce route is defined — all traffic will observe",
99 ));
100 } else {
101 checks.push(Check::new(
102 "routing",
103 CheckStatus::Ok,
104 format!("{enforce_routes} enforce route(s)"),
105 ));
106 }
107
108 if env("ANTHROPIC_API_KEY").is_some_and(|k| !k.is_empty()) {
110 checks.push(Check::new("anthropic-key", CheckStatus::Ok, "present"));
111 } else {
112 checks.push(Check::new(
113 "anthropic-key",
114 CheckStatus::Warn,
115 "ANTHROPIC_API_KEY not set — observe uses the caller's key; enforce needs one reachable",
116 ));
117 }
118
119 let path = env("PATH");
121 let gate_defs = config.routing.as_ref().map_or(&[][..], |c| &c.gate_defs);
122 for def in gate_defs {
123 match def.cmd.first() {
124 Some(program) if command_on_path(program, path.as_deref()) => checks.push(Check::new(
125 format!("gate:{}", def.id),
126 CheckStatus::Ok,
127 format!("`{program}` found"),
128 )),
129 Some(program) => checks.push(Check::new(
130 format!("gate:{}", def.id),
131 CheckStatus::Fail,
132 format!("`{program}` not found on PATH"),
133 )),
134 None => checks.push(Check::new(
135 format!("gate:{}", def.id),
136 CheckStatus::Fail,
137 "empty command",
138 )),
139 }
140 }
141
142 if can_write_db(&config.db_path) {
144 checks.push(Check::new(
145 "trace-store",
146 CheckStatus::Ok,
147 format!("{} is writable", config.db_path),
148 ));
149 } else {
150 checks.push(Check::new(
151 "trace-store",
152 CheckStatus::Fail,
153 format!("cannot write near {}", config.db_path),
154 ));
155 }
156
157 DoctorReport { checks }
158}
159
160#[must_use]
163pub fn command_on_path(program: &str, path_var: Option<&str>) -> bool {
164 if program.contains('/') || program.contains('\\') {
165 return std::path::Path::new(program).is_file();
166 }
167 let Some(path) = path_var else { return false };
168 std::env::split_paths(path).any(|dir| dir.join(program).is_file())
169}
170
171fn can_write_db(db_path: &str) -> bool {
173 let path = std::path::Path::new(db_path);
174 let dir = path
175 .parent()
176 .filter(|d| !d.as_os_str().is_empty())
177 .map_or_else(
178 || std::path::PathBuf::from("."),
179 std::path::Path::to_path_buf,
180 );
181 let probe = dir.join(format!(".firstpass-doctor-probe-{}", std::process::id()));
182 match std::fs::File::create(&probe) {
183 Ok(_) => {
184 let _ = std::fs::remove_file(&probe);
185 true
186 }
187 Err(_) => false,
188 }
189}
190
191#[must_use]
194pub fn format_traces(traces: &[Trace], limit: usize) -> String {
195 let mut lines: Vec<String> = traces
196 .iter()
197 .rev()
198 .take(limit)
199 .filter_map(|t| serde_json::to_string(t).ok())
200 .collect();
201 lines.reverse();
202 if lines.is_empty() {
203 "no traces recorded yet".to_owned()
204 } else {
205 lines.join("\n")
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 fn config_with(toml: Option<&str>, db_path: &str) -> ProxyConfig {
214 ProxyConfig::from_lookup(|k| match k {
215 "FIRSTPASS_MODE" if toml.is_some() => Some("enforce".to_owned()),
216 "FIRSTPASS_CONFIG_TOML" => toml.map(str::to_owned),
217 "FIRSTPASS_DB" => Some(db_path.to_owned()),
218 _ => None,
219 })
220 .unwrap()
221 }
222
223 #[test]
224 fn command_on_path_finds_real_and_rejects_fake() {
225 let path = std::env::var("PATH").ok();
226 assert!(command_on_path("sh", path.as_deref()), "sh is on PATH");
227 assert!(!command_on_path(
228 "firstpass-definitely-not-a-real-binary",
229 path.as_deref()
230 ));
231 assert!(!command_on_path("/nonexistent/abs/path", None));
232 }
233
234 #[test]
235 fn doctor_flags_a_missing_gate_binary() {
236 let toml = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\ngates = [\"good\", \"bad\"]\n\
237 [[gate]]\nid = \"good\"\ncmd = [\"sh\"]\n\
238 [[gate]]\nid = \"bad\"\ncmd = [\"firstpass-nope-not-real\"]\n";
239 let db = std::env::temp_dir().join("firstpass-doctor-test.db");
240 let config = config_with(Some(toml), db.to_str().unwrap());
241
242 let report = doctor(&config, |k| match k {
244 "PATH" => std::env::var("PATH").ok(),
245 _ => None,
246 });
247
248 assert!(
249 !report.healthy(),
250 "a missing gate binary must fail the report"
251 );
252 let bad = report.checks.iter().find(|c| c.name == "gate:bad").unwrap();
253 assert_eq!(bad.status, CheckStatus::Fail);
254 let good = report
255 .checks
256 .iter()
257 .find(|c| c.name == "gate:good")
258 .unwrap();
259 assert_eq!(good.status, CheckStatus::Ok);
260 let key = report
261 .checks
262 .iter()
263 .find(|c| c.name == "anthropic-key")
264 .unwrap();
265 assert_eq!(key.status, CheckStatus::Warn);
266 }
267
268 #[test]
269 fn doctor_is_healthy_for_a_plain_observe_setup() {
270 let db = std::env::temp_dir().join("firstpass-doctor-ok.db");
271 let config = config_with(None, db.to_str().unwrap());
272 let report = doctor(&config, |k| {
273 (k == "ANTHROPIC_API_KEY").then(|| "sk-test".to_owned())
274 });
275 assert!(report.healthy(), "{}", report.render());
276 }
277
278 #[test]
279 fn format_traces_handles_empty() {
280 assert_eq!(format_traces(&[], 10), "no traces recorded yet");
281 }
282}