Skip to main content

firstpass_proxy/
cli.rs

1//! CLI surfaces for the `firstpass` binary (SPEC §7.3/§7.4): `doctor` validates a setup before
2//! you route real traffic through it, and `trace` reads recent audit records from the store. Both
3//! are kept here (not in the binary) so the judgment is unit-tested.
4
5use crate::config::ProxyConfig;
6use firstpass_core::{Mode, Trace};
7
8/// A single doctor check outcome.
9#[derive(Debug, PartialEq, Eq)]
10pub enum CheckStatus {
11    /// Healthy.
12    Ok,
13    /// Works, but worth knowing (e.g. no key in env — observe still runs).
14    Warn,
15    /// Broken; `firstpass doctor` exits non-zero.
16    Fail,
17}
18
19/// One line of the doctor report.
20#[derive(Debug)]
21pub struct Check {
22    /// Short check name.
23    pub name: String,
24    /// Outcome.
25    pub status: CheckStatus,
26    /// Human-readable detail.
27    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/// The result of `firstpass doctor`.
41#[derive(Debug)]
42pub struct DoctorReport {
43    /// One entry per check, in report order.
44    pub checks: Vec<Check>,
45}
46
47impl DoctorReport {
48    /// Healthy iff no check failed (warnings are fine).
49    #[must_use]
50    pub fn healthy(&self) -> bool {
51        self.checks.iter().all(|c| c.status != CheckStatus::Fail)
52    }
53
54    /// Render the report as human-readable lines (a rendering of the structured checks).
55    #[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/// Validate a loaded config against the environment: routing sanity, provider key presence, and
76/// that every configured gate's command actually exists. `env` looks up environment variables
77/// (injected so this is testable).
78#[must_use]
79pub fn doctor(config: &ProxyConfig, env: impl Fn(&str) -> Option<String>) -> DoctorReport {
80    let mut checks = Vec::new();
81
82    // Config parsed (we hold a ProxyConfig), report the shape.
83    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    // Enforce is only meaningful with an enforce route to activate the engine.
91    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    // A provider key in the environment. Observe uses the caller's key, so absence is a warning.
109    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    // Every configured gate command must resolve, or that gate silently abstains at runtime.
120    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    // The trace store must be writable, or we'd trade the audit trail (or availability) for it.
143    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/// Whether `program` is runnable: an explicit path (contains a separator) that exists, or a bare
161/// name found in one of `PATH`'s directories.
162#[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
171/// Probe whether the trace DB's directory is writable, without creating the DB itself.
172fn 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/// Render the most recent `limit` traces as JSON lines — machine-first (SPEC §0.2): each line is a
192/// full [`Trace`], newest last.
193#[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        // Real PATH so `sh` resolves; no ANTHROPIC_API_KEY -> a warning, not a failure.
243        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}