Skip to main content

firstpass_proxy/
onboard.rs

1//! `firstpass onboard` — fully agentic onboarding (SPEC §0.2: the primary user is an agent, and
2//! the human deserves the same one-command experience). Detect the environment, plan the exact
3//! steps, execute them under `--apply`, and verify end-to-end — so "install firstpass and route
4//! my agent through it" is one command, not a doc to follow.
5//!
6//! Structure: [`detect`] and [`plan`] are pure (injected lookups, no I/O) so the decision logic is
7//! unit-tested offline; [`execute`] performs the side effects (spawn proxy, append one marked line
8//! to the shell rc, probe `/healthz`) and is deliberately thin. Without `--apply` the command is a
9//! dry run that prints the plan — agentic, but never surprising.
10
11use std::io::Write as _;
12use std::path::PathBuf;
13
14/// Marker comment appended with the env line so re-running onboard is idempotent and offboarding
15/// is greppable.
16pub const RC_MARKER: &str = "# added by `firstpass onboard`";
17
18/// What onboarding discovered about this machine. Everything is injected-lookup driven so tests
19/// construct arbitrary environments without touching the real one.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Environment {
22    /// User's login shell binary name (`zsh` / `bash` / `fish` / other).
23    pub shell: String,
24    /// The proxy is already answering `/healthz` on the target port.
25    pub proxy_running: bool,
26    /// `ANTHROPIC_BASE_URL` already points at the target proxy.
27    pub already_routed: bool,
28    /// `ANTHROPIC_API_KEY` is set (needed for enforce-mode upstream calls; observe passes BYOK).
29    pub has_api_key: bool,
30    /// The `claude` CLI (Claude Code) is on PATH — we can offer MCP wiring.
31    pub has_claude_cli: bool,
32    /// Target bind, e.g. `127.0.0.1:8080`.
33    pub bind: String,
34}
35
36/// Which provider the ladder opens on. Only `anthropic` and `openai` are built into the provider
37/// registry; the other two must carry a `[[provider]]` block or the config will not resolve.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Provider {
40    /// Built in.
41    Anthropic,
42    /// Built in.
43    OpenAi,
44    /// Gemini dialect; needs a `[[provider]]` block and `GEMINI_API_KEY`.
45    Google,
46    /// A local OpenAI-compatible server (Ollama), escalating to a frontier rung.
47    Local,
48}
49
50impl Provider {
51    /// Every choice, in prompt order.
52    pub const ALL: [Self; 4] = [Self::Anthropic, Self::OpenAi, Self::Google, Self::Local];
53
54    /// Stable id accepted by `--provider`.
55    #[must_use]
56    pub const fn id(self) -> &'static str {
57        match self {
58            Self::Anthropic => "anthropic",
59            Self::OpenAi => "openai",
60            Self::Google => "google",
61            Self::Local => "local",
62        }
63    }
64
65    /// One-line description shown next to the option when prompting.
66    #[must_use]
67    pub const fn blurb(self) -> &'static str {
68        match self {
69            Self::Anthropic => "Claude — haiku opens, sonnet catches (built in)",
70            Self::OpenAi => "GPT — 4.1-mini opens, 5.5 catches (built in)",
71            Self::Google => "Gemini — flash opens, pro catches (needs GEMINI_API_KEY)",
72            Self::Local => "Ollama on localhost, escalating to Claude sonnet",
73        }
74    }
75
76    /// Cheapest-first ladder. Every id here is priced by the built-in table, so `firstpass savings`
77    /// is meaningful out of the box (the local rung is the exception — it is free to run).
78    #[must_use]
79    pub const fn ladder(self) -> [&'static str; 2] {
80        match self {
81            Self::Anthropic => ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"],
82            Self::OpenAi => ["openai/gpt-4.1-mini", "openai/gpt-5.5"],
83            // Flash-Lite → Flash, not Flash → Pro: Google prices Flash at $1.50/$7.50 and Pro at
84            // $1.25/$10.00, so a Flash→Pro ladder has a ~8% gradient and escalation buys nothing.
85            // Lite→Flash is 5x on input, 3x on output — a ladder worth climbing.
86            Self::Google => ["google/gemini-3.5-flash-lite", "google/gemini-3.6-flash"],
87            Self::Local => ["ollama/qwen2.5-coder:7b", "anthropic/claude-sonnet-5"],
88        }
89    }
90
91    /// A model for the judge gate that is deliberately NOT on the ladder — the runner enforces
92    /// maker != checker, so a judge drawn from the ladder would be rejected.
93    #[must_use]
94    pub const fn judge_model(self) -> &'static str {
95        match self {
96            Self::Anthropic | Self::Local => "anthropic/claude-opus-4-8",
97            Self::OpenAi | Self::Google => "anthropic/claude-haiku-4-5",
98        }
99    }
100
101    /// The `[[provider]]` block this choice requires, if it is not built in.
102    #[must_use]
103    pub const fn provider_block(self) -> Option<&'static str> {
104        match self {
105            Self::Anthropic | Self::OpenAi => None,
106            Self::Google => Some(
107                "[[provider]]                # only anthropic + openai are built in\n\
108                 id          = \"google\"\n\
109                 dialect     = \"gemini\"\n\
110                 base_url    = \"https://generativelanguage.googleapis.com\"\n\
111                 api_key_env = \"GEMINI_API_KEY\"\n",
112            ),
113            Self::Local => Some(
114                "[[provider]]                # local rung; escalates to a frontier model\n\
115                 id       = \"ollama\"\n\
116                 dialect  = \"openai\"\n\
117                 base_url = \"http://localhost:11434\"   # keyless\n\
118                 \n\
119                 [[price]]                   # you host it, so the tokens really are free —\n\
120                 model          = \"ollama/qwen2.5-coder:7b\"   # but the receipt has to SAY so,\n\
121                 input_per_mtok  = 0.0       # rather than infer $0.00 from a missing price\n\
122                 output_per_mtok = 0.0\n",
123            ),
124        }
125    }
126}
127
128/// What the model is being asked to produce. This is what actually picks the gate — the whole
129/// product rests on gating the real output, so it is the one question worth asking carefully.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum Shape {
132    /// Structured output — checked against a schema.
133    Json,
134    /// Code — checked by running the caller's tests.
135    Code,
136    /// Prose — graded by a judge on a different model.
137    Prose,
138    /// Mixed traffic — scored by k-sample self-consistency.
139    Mixed,
140}
141
142impl Shape {
143    /// Every choice, in prompt order.
144    pub const ALL: [Self; 4] = [Self::Json, Self::Code, Self::Prose, Self::Mixed];
145
146    /// Stable id accepted by `--shape`.
147    #[must_use]
148    pub const fn id(self) -> &'static str {
149        match self {
150            Self::Json => "json",
151            Self::Code => "code",
152            Self::Prose => "prose",
153            Self::Mixed => "mixed",
154        }
155    }
156
157    /// One-line description shown next to the option when prompting.
158    #[must_use]
159    pub const fn blurb(self) -> &'static str {
160        match self {
161            Self::Json => "JSON / API responses — schema gate, cheapest proof there is",
162            Self::Code => "Code — your own test suite is the gate",
163            Self::Prose => "Prose — an LLM judge grades it (maker != checker)",
164            Self::Mixed => "Mixed — k-sample self-consistency scores agreement",
165        }
166    }
167
168    /// Gate ids the route names. `non-empty` and `json-valid` are built in; the rest are declared
169    /// by [`Self::gate_block`] below, because a route naming an undeclared gate will not resolve.
170    #[must_use]
171    pub const fn gates(self) -> [&'static str; 2] {
172        match self {
173            Self::Json => ["json-valid", "extract-shape"],
174            Self::Code => ["json-valid", "unit-tests"],
175            Self::Prose => ["non-empty", "judge"],
176            Self::Mixed => ["non-empty", "uncertainty"],
177        }
178    }
179
180    /// The `[[gate]]` block defining this shape's non-built-in gate.
181    #[must_use]
182    pub fn gate_block(self, provider: Provider) -> String {
183        match self {
184            Self::Json => "[[gate]]\n\
185                 id         = \"extract-shape\"\n\
186                 schema     = { type = \"object\", required = [\"id\", \"total\"] }\n\
187                 on_abstain = \"fail_closed\"\n"
188                .to_owned(),
189            // A gate is not just any command: it must read the candidate as JSON on stdin and
190            // print {"verdict":...} on stdout, so a bare `pytest` here would look wired up while
191            // silently abstaining on every call.
192            //
193            // This used to emit a REPLACE-ME placeholder for exactly that reason. Correct, but it
194            // left every new user to implement the contract by hand, which is the single biggest
195            // piece of onboarding friction for a code workload. `scripts/gates/run-tests.py` now
196            // implements the contract, so what is emitted is a WORKING gate with only the user's
197            // own test command left to substitute.
198            Self::Code => {
199                "[[gate]]\n\
200                 # A working gate. `run-tests.py` implements the stdin/stdout contract: it pulls\n\
201                 # the code out of the model's reply, runs your command, and reports the pass\n\
202                 # FRACTION as the score (a graded score is what the conformal bound calibrates\n\
203                 # on; a bare pass/fail gives it only two operating points).\n\
204                 # Swap the command after `--` for yours:\n\
205                 #   jest:  \"--write\", \"solution.js\", \"--\", \"npx\", \"jest\", \"--silent\"\n\
206                 #   cargo: \"--write\", \"src/lib.rs\", \"--\", \"cargo\", \"test\", \"--quiet\"\n\
207                 # Add \"--copy\", \"tests/\" to bring your test files into the run directory, and\n\
208                 # \"--docker\", \"python:3.12-alpine\" to run untrusted code with no network.\n\
209                 id  = \"unit-tests\"\n\
210                 cmd = [\"python3\", \"scripts/gates/run-tests.py\",\n\
211                        \"--write\", \"solution.py\", \"--copy\", \"tests/\",\n\
212                        \"--\", \"python3\", \"-m\", \"pytest\", \"-q\"]\n"
213                    .to_owned()
214            }
215            Self::Prose => format!(
216                "[[gate]]                    # judge sits OUTSIDE the ladder: maker != checker\n\
217                 id    = \"judge\"\n\
218                 judge = {{ model = \"{}\", threshold = 0.7, rubric = \"The response fully and \
219                 correctly resolves the request, with no errors.\" }}\n",
220                provider.judge_model()
221            ),
222            Self::Mixed => format!(
223                "[[gate]]                    # k samples; agreement becomes the score\n\
224                 id          = \"uncertainty\"\n\
225                 consistency = {{ model = \"{}\", k = 3, threshold = 0.6 }}\n",
226                provider.ladder()[0]
227            ),
228        }
229    }
230}
231
232/// The three answers that decide a starting ladder. Everything else in the generated file follows
233/// from these, which is why onboarding asks exactly three questions and not a wizard's worth.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct LadderChoice {
236    /// Which provider the ladder opens on.
237    pub provider: Provider,
238    /// What the output is, which picks the gate.
239    pub shape: Shape,
240    /// `observe` forwards unchanged; `enforce` serves from the cheap rung once a gate passes.
241    pub mode: firstpass_core::Mode,
242}
243
244impl Default for LadderChoice {
245    /// The answer set used when nothing is on a terminal to ask: Claude, JSON, and observe — the
246    /// combination that changes no behavior at all.
247    fn default() -> Self {
248        Self {
249            provider: Provider::Anthropic,
250            shape: Shape::Json,
251            mode: firstpass_core::Mode::Observe,
252        }
253    }
254}
255
256/// Render a complete, runnable `firstpass.toml` for these answers — including the `[[provider]]`
257/// and `[[gate]]` blocks the choice requires. Emitting a fragment would be worse than emitting
258/// nothing: only `anthropic`/`openai` are built-in providers and only `non-empty`/`json-valid`
259/// are built-in gates, so anything else must be declared here or the file will not resolve.
260#[must_use]
261pub fn render_config(choice: &LadderChoice) -> String {
262    let enforce = choice.mode == firstpass_core::Mode::Enforce;
263    let mode = if enforce { "enforce" } else { "observe" };
264    let quoted = |xs: [&str; 2]| -> String { format!("\"{}\", \"{}\"", xs[0], xs[1]) };
265    let mut out = format!(
266        "# firstpass.toml — written by `firstpass onboard`. Re-run onboard to regenerate.\n\
267         #   FIRSTPASS_MODE={mode} FIRSTPASS_CONFIG=./firstpass.toml firstpass up\n\n"
268    );
269    if let Some(block) = choice.provider.provider_block() {
270        out.push_str(block);
271        out.push('\n');
272    }
273    out.push_str(&format!(
274        "[[route]]                   # routes match top to bottom; first match wins\n\
275         match  = {{}}                 # everything\n\
276         mode   = \"{mode}\"\n\
277         ladder = [{}]\n\
278         gates  = [{}]\n\n",
279        quoted(choice.provider.ladder()),
280        quoted(choice.shape.gates()),
281    ));
282    out.push_str(&choice.shape.gate_block(choice.provider));
283    if enforce {
284        out.push_str(
285            "\n[escalation]\nmax_rungs_per_request = 2   # one rung up, never a runaway\n",
286        );
287    } else {
288        out.push_str(
289            "\n# observe: every request is forwarded unchanged and a receipt is written off\n\
290             # the hot path. Nothing routes differently until mode = \"enforce\".\n",
291        );
292    }
293    out
294}
295
296/// Render every answer combination as a JavaScript asset for the documentation site.
297///
298/// The docs used to carry their own copy of this template in `docs/assets/docs.js`. Two
299/// implementations of the same config format drift silently — and a docs page that emits config
300/// the binary would reject is worse than a page with no builder at all. So Rust owns the format
301/// and the site consumes what Rust produced; `docs_presets_are_current` fails CI if this output
302/// and the committed asset disagree.
303#[must_use]
304pub fn presets_js() -> String {
305    use firstpass_core::Mode;
306    let mut out = String::from(
307        "// GENERATED by `cargo test -p firstpass-proxy presets` — do not edit by hand.\n\
308         // Source of truth: crates/firstpass-proxy/src/onboard.rs (render_config).\n\
309         // Regenerate: FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets\n\
310         window.FP_LADDER_PRESETS = {\n",
311    );
312    for provider in Provider::ALL {
313        out.push_str(&format!("  {:?}: {{\n", provider.id()));
314        for shape in Shape::ALL {
315            out.push_str(&format!("    {:?}: {{\n", shape.id()));
316            for (mode, key) in [(Mode::Observe, "observe"), (Mode::Enforce, "enforce")] {
317                let toml = render_config(&LadderChoice {
318                    provider,
319                    shape,
320                    mode,
321                });
322                out.push_str(&format!("      {key:?}: {},\n", js_string(&toml)));
323            }
324            out.push_str("    },\n");
325        }
326        out.push_str("  },\n");
327    }
328    out.push_str("};\n");
329    out
330}
331
332/// Encode a string as a JS double-quoted literal. Hand-rolled rather than pulling in a
333/// serialiser: the payload is our own generated TOML, and the escape set is small and fixed.
334fn js_string(s: &str) -> String {
335    let mut out = String::with_capacity(s.len() + 16);
336    out.push('"');
337    for c in s.chars() {
338        match c {
339            '"' => out.push_str("\\\""),
340            '\\' => out.push_str("\\\\"),
341            '\n' => out.push_str("\\n"),
342            '\r' => {}
343            c => out.push(c),
344        }
345    }
346    out.push('"');
347    out
348}
349
350/// One onboarding step: what it is, and whether it's already satisfied.
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub enum Step {
353    /// Write the generated routing config. Never overwrites an existing file — the caller checks.
354    WriteConfig {
355        /// Where the file goes (`./firstpass.toml`).
356        path: PathBuf,
357        /// Full rendered contents.
358        toml: String,
359    },
360    /// Spawn `firstpass up` detached (observe mode), logging to `firstpass-proxy.log`.
361    StartProxy {
362        /// Config to hand the child via `FIRSTPASS_CONFIG`. The proxy has no default config path,
363        /// so a written file is inert unless it is passed explicitly.
364        config: Option<PathBuf>,
365    },
366    /// Append the marked `ANTHROPIC_BASE_URL` export to the shell rc file.
367    WireShell {
368        /// Rc file the line goes into.
369        rc: PathBuf,
370        /// The exact line (shell-dialect aware).
371        line: String,
372    },
373    /// Print the `claude mcp add` command so Claude Code can query traces/savings as tools.
374    /// (Printed, not executed — mutating another tool's config uninvited isn't onboarding.)
375    SuggestClaudeMcp,
376    /// Probe `/healthz` and `/v1/capabilities` and report what's routed.
377    Verify,
378    /// Nothing to do — with the reason shown to the user.
379    AlreadyDone(&'static str),
380}
381
382/// Detect the environment via injected lookups: `env(key)` for env vars, `on_path(bin)` for PATH
383/// probes, `healthz()` for a live proxy probe. Pure decision logic; all I/O behind the closures.
384pub fn detect(
385    env: impl Fn(&str) -> Option<String>,
386    on_path: impl Fn(&str) -> bool,
387    healthz: impl Fn() -> bool,
388) -> Environment {
389    let bind = env("FIRSTPASS_BIND").unwrap_or_else(|| "127.0.0.1:8080".to_owned());
390    let base_url = format!("http://{bind}");
391    let shell = env("SHELL")
392        .and_then(|s| s.rsplit('/').next().map(str::to_owned))
393        .unwrap_or_else(|| "sh".to_owned());
394    Environment {
395        shell,
396        proxy_running: healthz(),
397        already_routed: env("ANTHROPIC_BASE_URL").is_some_and(|v| v == base_url),
398        has_api_key: env("ANTHROPIC_API_KEY").is_some(),
399        has_claude_cli: on_path("claude"),
400        bind,
401    }
402}
403
404/// The shell-dialect line that routes agents through the proxy, plus the rc file it belongs in.
405/// `home` is injected so tests never touch a real home directory.
406#[must_use]
407pub fn shell_wiring(shell: &str, home: &std::path::Path, bind: &str) -> (PathBuf, String) {
408    let url = format!("http://{bind}");
409    match shell {
410        "fish" => (
411            home.join(".config/fish/config.fish"),
412            format!("set -gx ANTHROPIC_BASE_URL {url}  {RC_MARKER}"),
413        ),
414        "bash" => (
415            home.join(".bashrc"),
416            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
417        ),
418        // zsh and anything else POSIX-ish: default to ~/.zshrc only for zsh, else ~/.profile.
419        "zsh" => (
420            home.join(".zshrc"),
421            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
422        ),
423        _ => (
424            home.join(".profile"),
425            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
426        ),
427    }
428}
429
430/// A config the caller wants written: where it goes and the answers behind it. `None` means the
431/// step is skipped — either a `firstpass.toml` is already there or the user opted out.
432#[derive(Debug, Clone)]
433pub struct ConfigPlan {
434    /// Destination, normally `./firstpass.toml`.
435    pub path: PathBuf,
436    /// The three answers.
437    pub choice: LadderChoice,
438}
439
440/// Build the ordered plan for this environment. `rc_already_wired` is whether the rc file already
441/// carries the marker line (checked by the caller, injected here to stay pure). `config` is the
442/// routing file to generate, if any — it is written *before* the proxy starts so the child can be
443/// handed it, since a config the proxy never loads is worse than no config at all.
444#[must_use]
445pub fn plan(
446    env: &Environment,
447    home: &std::path::Path,
448    rc_already_wired: bool,
449    config: Option<&ConfigPlan>,
450) -> Vec<Step> {
451    let mut steps = Vec::new();
452    if let Some(c) = config {
453        steps.push(Step::WriteConfig {
454            path: c.path.clone(),
455            toml: render_config(&c.choice),
456        });
457    }
458    if env.proxy_running {
459        steps.push(Step::AlreadyDone("proxy already answering /healthz"));
460    } else {
461        steps.push(Step::StartProxy {
462            config: config.map(|c| c.path.clone()),
463        });
464    }
465    if env.already_routed || rc_already_wired {
466        steps.push(Step::AlreadyDone("ANTHROPIC_BASE_URL already wired"));
467    } else {
468        let (rc, line) = shell_wiring(&env.shell, home, &env.bind);
469        steps.push(Step::WireShell { rc, line });
470    }
471    if env.has_claude_cli {
472        steps.push(Step::SuggestClaudeMcp);
473    }
474    steps.push(Step::Verify);
475    steps
476}
477
478/// Render the plan for the dry run (default) or as the running commentary under `--apply`.
479#[must_use]
480pub fn render(env: &Environment, steps: &[Step], apply: bool) -> String {
481    let mut out = String::new();
482    out.push_str(&format!(
483        "detected: shell={} · proxy_running={} · routed={} · api_key={} · claude_cli={}\n\n",
484        env.shell, env.proxy_running, env.already_routed, env.has_api_key, env.has_claude_cli
485    ));
486    for (i, s) in steps.iter().enumerate() {
487        let n = i + 1;
488        match s {
489            Step::WriteConfig { path, toml } => {
490                out.push_str(&format!("{n}. write {} —\n", path.display()));
491                for line in toml.lines() {
492                    out.push_str(&format!("     {line}\n"));
493                }
494            }
495            Step::StartProxy { config } => {
496                out.push_str(&format!(
497                    "{n}. start the proxy — `firstpass up` (observe mode: watches, changes nothing), log → firstpass-proxy.log\n"
498                ));
499                if let Some(c) = config {
500                    out.push_str(&format!(
501                        "     with FIRSTPASS_CONFIG={} — the proxy has no default config path\n",
502                        c.display()
503                    ));
504                }
505            }
506            Step::WireShell { rc, line } => out.push_str(&format!(
507                "{n}. route your agents — append to {}:\n     {line}\n",
508                rc.display()
509            )),
510            Step::SuggestClaudeMcp => out.push_str(&format!(
511                "{n}. (optional) let Claude Code query receipts as tools:\n     claude mcp add firstpass -- firstpass mcp\n"
512            )),
513            Step::Verify => out.push_str(&format!(
514                "{n}. verify — probe /healthz and /v1/capabilities, report what's routed\n"
515            )),
516            Step::AlreadyDone(why) => out.push_str(&format!("{n}. ✓ {why}\n")),
517        }
518    }
519    if !env.has_api_key {
520        out.push_str(
521            "\nnote: ANTHROPIC_API_KEY is not set — observe mode passes your agent's own key \
522             through (BYOK), so this only matters for enforce mode.\n",
523        );
524    }
525    if !apply {
526        out.push_str(
527            "\ndry run — nothing changed. Re-run with `firstpass onboard --apply` to execute.\n",
528        );
529    }
530    out
531}
532
533/// Execute the side-effectful steps. Returns a human report. Failures are reported per step —
534/// onboarding never half-dies silently.
535///
536/// # Errors
537/// Only on I/O failures writing the rc file; every other issue is reported in the returned text.
538pub fn execute(env: &Environment, steps: &[Step]) -> Result<String, std::io::Error> {
539    let mut out = String::new();
540    for s in steps {
541        match s {
542            Step::WriteConfig { path, toml } => {
543                // Never clobber a config the operator already has; the caller only plans this
544                // step when the path is free, but re-check rather than trust the gap between.
545                if path.exists() {
546                    out.push_str(&format!(
547                        "✓ {} already present — left untouched\n",
548                        path.display()
549                    ));
550                } else {
551                    std::fs::write(path, toml)?;
552                    out.push_str(&format!("✓ wrote {}\n", path.display()));
553                }
554            }
555            Step::StartProxy { config } => {
556                let log = std::fs::File::create("firstpass-proxy.log")?;
557                let exe = std::env::current_exe()?;
558                let mut cmd = std::process::Command::new(exe);
559                cmd.arg("up");
560                if let Some(c) = config {
561                    // A written config is inert unless it is named: `ProxyConfig::from_env` reads
562                    // `FIRSTPASS_CONFIG` and has no default path to fall back on.
563                    cmd.env("FIRSTPASS_CONFIG", c);
564                }
565                let child = cmd
566                    .stdin(std::process::Stdio::null())
567                    .stdout(std::process::Stdio::from(log.try_clone()?))
568                    .stderr(std::process::Stdio::from(log))
569                    .spawn();
570                match child {
571                    Ok(c) => {
572                        // Pidfile makes `firstpass offboard` able to stop what onboard started.
573                        let _ = std::fs::write("firstpass-proxy.pid", c.id().to_string());
574                        out.push_str(&format!(
575                            "✓ proxy started (pid {}, observe mode) — log: firstpass-proxy.log\n",
576                            c.id()
577                        ));
578                    }
579                    Err(e) => out.push_str(&format!("✗ could not start proxy: {e}\n")),
580                }
581            }
582            Step::WireShell { rc, line } => {
583                if let Some(parent) = rc.parent() {
584                    std::fs::create_dir_all(parent)?;
585                }
586                let mut f = std::fs::OpenOptions::new()
587                    .create(true)
588                    .append(true)
589                    .open(rc)?;
590                writeln!(f, "{line}")?;
591                out.push_str(&format!(
592                    "✓ wired {} — takes effect in new shells; for this one:\n     {}\n",
593                    rc.display(),
594                    line.trim_end_matches(RC_MARKER).trim_end()
595                ));
596            }
597            Step::SuggestClaudeMcp => {
598                out.push_str("→ optional: claude mcp add firstpass -- firstpass mcp\n");
599            }
600            Step::Verify => {
601                let url = format!("http://{}/healthz", env.bind);
602                let ok = wait_healthz(&url, std::time::Duration::from_secs(6));
603                if ok {
604                    out.push_str(&format!(
605                        "✓ verified — proxy healthy at http://{} · capabilities: http://{}/v1/capabilities\n",
606                        env.bind, env.bind
607                    ));
608                } else {
609                    out.push_str(&format!(
610                        "✗ proxy not answering http://{} after 6s — check firstpass-proxy.log\n",
611                        env.bind
612                    ));
613                }
614            }
615            Step::AlreadyDone(why) => out.push_str(&format!("✓ {why}\n")),
616        }
617    }
618    out.push_str("\noffboard any time: unset ANTHROPIC_BASE_URL (and remove the marked rc line)\n");
619    Ok(out)
620}
621
622/// Whether a `/healthz` response says **Firstpass** is on the other end.
623///
624/// A 200 alone proves only that *something* holds the port. That is not good enough here: onboard
625/// writes `ANTHROPIC_BASE_URL` into the user's shell rc, so accepting a stranger points the agent's
626/// credentialed traffic at an unrelated process, records no receipts, and still reports success.
627/// Found by running this for real — an unrelated dev server on `:8080` answered `/healthz 200` with
628/// its own JSON and onboard reported "verified — proxy healthy".
629///
630/// The proxy names itself in the body for exactly this reason (see `proxy::healthz`), which is the
631/// same discriminator `launch` uses before handing an agent a base url.
632#[must_use]
633pub fn healthz_is_firstpass(status_ok: bool, body: &str) -> bool {
634    if !status_ok {
635        return false;
636    }
637    serde_json::from_str::<serde_json::Value>(body)
638        .ok()
639        .and_then(|v| {
640            v.get("service")
641                .and_then(serde_json::Value::as_str)
642                .map(|s| s == "firstpass")
643        })
644        .unwrap_or(false)
645}
646
647/// One blocking `GET /healthz`, returning `(status_is_200, body)`. Std-only (the CLI calls this off
648/// the async runtime): a plain TCP connect + minimal HTTP/1.1 GET, no client dependency.
649///
650/// Reads to EOF rather than into a small fixed buffer — the identity marker lives in the body, and
651/// the previous 64-byte read could not reach past the status line.
652fn get_healthz(addr: &str) -> Option<(bool, String)> {
653    let mut s = std::net::TcpStream::connect(addr).ok()?;
654    let _ = s.set_read_timeout(Some(std::time::Duration::from_millis(500)));
655    let req = format!("GET /healthz HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
656    s.write_all(req.as_bytes()).ok()?;
657    use std::io::Read as _;
658    let mut raw = Vec::new();
659    // Cap the read so a chatty or hostile listener cannot make this hang on unbounded output.
660    let _ = s.take(64 * 1024).read_to_end(&mut raw);
661    let text = String::from_utf8_lossy(&raw).into_owned();
662    let status_ok = text.lines().next().is_some_and(|l| l.contains(" 200"));
663    let body = text
664        .split_once("\r\n\r\n")
665        .map_or("", |(_, b)| b)
666        .to_owned();
667    Some((status_ok, body))
668}
669
670/// Whether **Firstpass** is answering at `addr` (`host:port`) right now. One probe, no waiting.
671///
672/// This is what the `onboard` environment detector must use: a bare TCP connect cannot tell a
673/// running proxy from any other process holding the port.
674#[must_use]
675pub fn firstpass_listening(addr: &str) -> bool {
676    get_healthz(addr).is_some_and(|(ok, body)| healthz_is_firstpass(ok, &body))
677}
678
679/// Poll until **Firstpass** answers `/healthz` or the deadline passes.
680fn wait_healthz(url: &str, deadline: std::time::Duration) -> bool {
681    let Some(addr) = url
682        .strip_prefix("http://")
683        .and_then(|r| r.split('/').next())
684        .map(str::to_owned)
685    else {
686        return false;
687    };
688    let start = std::time::Instant::now();
689    while start.elapsed() < deadline {
690        if firstpass_listening(&addr) {
691            return true;
692        }
693        std::thread::sleep(std::time::Duration::from_millis(200));
694    }
695    false
696}
697
698/// Whether the rc file already carries the onboard marker (idempotence check for [`plan`]).
699#[must_use]
700pub fn rc_wired(rc: &std::path::Path) -> bool {
701    std::fs::read_to_string(rc).is_ok_and(|s| s.contains(RC_MARKER))
702}
703
704/// Remove every marked onboard line from `rc`. Returns whether anything was removed. Only lines
705/// carrying [`RC_MARKER`] are touched — nothing else in the user's rc is ever rewritten.
706///
707/// # Errors
708/// Only on I/O failures reading/writing the rc file.
709pub fn offboard_rc(rc: &std::path::Path) -> Result<bool, std::io::Error> {
710    let Ok(content) = std::fs::read_to_string(rc) else {
711        return Ok(false); // no file → nothing to offboard
712    };
713    if !content.contains(RC_MARKER) {
714        return Ok(false);
715    }
716    let kept: Vec<&str> = content.lines().filter(|l| !l.contains(RC_MARKER)).collect();
717    std::fs::write(rc, kept.join("\n") + "\n")?;
718    Ok(true)
719}
720
721/// `firstpass offboard` — the exact mirror of onboard: strip the marked line from every candidate
722/// rc file, stop the proxy onboard started (pidfile), and print the one command for this shell.
723/// Fully idempotent; reports what it found either way.
724///
725/// # Errors
726/// Only on rc-file I/O failures.
727pub fn offboard(home: &std::path::Path) -> Result<String, std::io::Error> {
728    let mut out = String::new();
729    for rc in [
730        home.join(".zshrc"),
731        home.join(".bashrc"),
732        home.join(".profile"),
733        home.join(".config/fish/config.fish"),
734    ] {
735        if offboard_rc(&rc)? {
736            out.push_str(&format!("✓ removed firstpass line from {}\n", rc.display()));
737        }
738    }
739    // Stop the proxy onboard spawned, if its pidfile is present.
740    if let Ok(pid) = std::fs::read_to_string("firstpass-proxy.pid") {
741        let pid = pid.trim().to_owned();
742        #[cfg(unix)]
743        {
744            let killed = std::process::Command::new("kill")
745                .arg(&pid)
746                .status()
747                .is_ok_and(|s| s.success());
748            if killed {
749                out.push_str(&format!("✓ stopped proxy (pid {pid})\n"));
750            } else {
751                out.push_str(&format!(
752                    "→ proxy pid {pid} not running (already stopped)\n"
753                ));
754            }
755        }
756        let _ = std::fs::remove_file("firstpass-proxy.pid");
757    }
758    if out.is_empty() {
759        out.push_str("nothing to offboard — no marked rc lines, no pidfile.\n");
760    }
761    out.push_str("for this shell: unset ANTHROPIC_BASE_URL\n");
762    Ok(out)
763}
764
765#[cfg(test)]
766mod tests {
767    #![allow(clippy::unwrap_used)]
768    use super::*;
769
770    fn env_of<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
771        move |k| {
772            pairs
773                .iter()
774                .find(|(a, _)| *a == k)
775                .map(|(_, v)| (*v).to_owned())
776        }
777    }
778
779    #[test]
780    fn detect_reads_shell_routing_and_tools() {
781        let e = detect(
782            env_of(&[
783                ("SHELL", "/bin/zsh"),
784                ("ANTHROPIC_BASE_URL", "http://127.0.0.1:8080"),
785                ("ANTHROPIC_API_KEY", "sk-x"),
786            ]),
787            |bin| bin == "claude",
788            || true,
789        );
790        assert_eq!(e.shell, "zsh");
791        assert!(e.proxy_running && e.already_routed && e.has_api_key && e.has_claude_cli);
792        assert_eq!(e.bind, "127.0.0.1:8080");
793    }
794
795    #[test]
796    fn detect_respects_custom_bind_and_mismatched_base_url() {
797        let e = detect(
798            env_of(&[
799                ("FIRSTPASS_BIND", "127.0.0.1:9999"),
800                ("ANTHROPIC_BASE_URL", "http://127.0.0.1:8080"), // points elsewhere
801            ]),
802            |_| false,
803            || false,
804        );
805        assert_eq!(e.bind, "127.0.0.1:9999");
806        assert!(
807            !e.already_routed,
808            "routed to a different port is not routed"
809        );
810    }
811
812    #[test]
813    fn shell_wiring_speaks_each_dialect() {
814        let home = std::path::Path::new("/home/u");
815        let (rc, line) = shell_wiring("fish", home, "127.0.0.1:8080");
816        assert!(rc.ends_with(".config/fish/config.fish"));
817        assert!(line.starts_with("set -gx ANTHROPIC_BASE_URL http://127.0.0.1:8080"));
818
819        let (rc, line) = shell_wiring("zsh", home, "127.0.0.1:8080");
820        assert!(rc.ends_with(".zshrc"));
821        assert!(line.starts_with("export ANTHROPIC_BASE_URL="));
822
823        let (rc, _) = shell_wiring("dash", home, "127.0.0.1:8080");
824        assert!(
825            rc.ends_with(".profile"),
826            "unknown shells fall back to .profile"
827        );
828    }
829
830    #[test]
831    fn plan_covers_fresh_machine_and_is_idempotent_when_done() {
832        let home = std::path::Path::new("/home/u");
833        let fresh = Environment {
834            shell: "zsh".into(),
835            proxy_running: false,
836            already_routed: false,
837            has_api_key: false,
838            has_claude_cli: true,
839            bind: "127.0.0.1:8080".into(),
840        };
841        let steps = plan(&fresh, home, false, None);
842        assert!(matches!(steps[0], Step::StartProxy { .. }));
843        assert!(matches!(steps[1], Step::WireShell { .. }));
844        assert!(matches!(steps[2], Step::SuggestClaudeMcp));
845        assert!(matches!(steps.last(), Some(Step::Verify)));
846
847        // Everything already set up → only AlreadyDone + Verify, nothing mutating.
848        let done = Environment {
849            proxy_running: true,
850            already_routed: true,
851            has_claude_cli: false,
852            ..fresh
853        };
854        let steps = plan(&done, home, true, None);
855        assert!(
856            steps
857                .iter()
858                .all(|s| matches!(s, Step::AlreadyDone(_) | Step::Verify))
859        );
860    }
861
862    #[test]
863    fn render_dry_run_says_nothing_changed_and_flags_missing_key() {
864        let home = std::path::Path::new("/home/u");
865        let e = Environment {
866            shell: "bash".into(),
867            proxy_running: false,
868            already_routed: false,
869            has_api_key: false,
870            has_claude_cli: false,
871            bind: "127.0.0.1:8080".into(),
872        };
873        let text = render(&e, &plan(&e, home, false, None), false);
874        assert!(text.contains("dry run — nothing changed"));
875        assert!(text.contains("ANTHROPIC_API_KEY is not set"));
876        assert!(text.contains(".bashrc"));
877    }
878
879    #[test]
880    fn rc_wired_detects_the_marker_and_execute_appends_it_once() {
881        let dir = std::env::temp_dir().join(format!("fp-onboard-{}", uuid::Uuid::now_v7()));
882        std::fs::create_dir_all(&dir).unwrap();
883        let rc = dir.join(".zshrc");
884        assert!(!rc_wired(&rc), "missing file is not wired");
885
886        let e = Environment {
887            shell: "zsh".into(),
888            proxy_running: true, // no spawn in this test
889            already_routed: false,
890            has_api_key: true,
891            has_claude_cli: false,
892            bind: "127.0.0.1:1".into(), // verify step will fail fast — that's fine, we assert wiring
893        };
894        let (rc_path, line) = shell_wiring("zsh", &dir, &e.bind);
895        let steps = vec![Step::WireShell {
896            rc: rc_path.clone(),
897            line,
898        }];
899        let report = execute(&e, &steps).unwrap();
900        assert!(report.contains("✓ wired"));
901        assert!(rc_wired(&rc_path), "marker written");
902        // Re-planning with the marker present must not wire again (idempotent onboarding).
903        let steps = plan(&e, &dir, rc_wired(&rc_path), None);
904        assert!(!steps.iter().any(|s| matches!(s, Step::WireShell { .. })));
905
906        let _ = std::fs::remove_dir_all(&dir);
907    }
908
909    #[test]
910    fn offboard_removes_only_the_marked_line_and_is_idempotent() {
911        let dir = std::env::temp_dir().join(format!("fp-offboard-{}", uuid::Uuid::now_v7()));
912        std::fs::create_dir_all(&dir).unwrap();
913        let rc = dir.join(".zshrc");
914        std::fs::write(
915            &rc,
916            format!("alias ll='ls -l'\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:8080  {RC_MARKER}\nexport EDITOR=vim\n"),
917        )
918        .unwrap();
919
920        assert!(offboard_rc(&rc).unwrap(), "marked line removed");
921        let after = std::fs::read_to_string(&rc).unwrap();
922        assert!(!after.contains(RC_MARKER));
923        assert!(
924            after.contains("alias ll") && after.contains("EDITOR=vim"),
925            "user lines untouched"
926        );
927        assert!(!offboard_rc(&rc).unwrap(), "second offboard is a no-op");
928
929        // The full offboard reports the rc removal and the unset line.
930        std::fs::write(&rc, format!("x  {RC_MARKER}\n")).unwrap();
931        let report = offboard(&dir).unwrap();
932        assert!(report.contains("removed firstpass line"));
933        assert!(report.contains("unset ANTHROPIC_BASE_URL"));
934
935        let _ = std::fs::remove_dir_all(&dir);
936    }
937
938    /// The whole point of generating a config is that it runs. Every answer combination must
939    /// survive the real parser — including the `[[provider]]`/`[[gate]]` blocks each one implies,
940    /// since only `anthropic`/`openai` and `non-empty`/`json-valid` are built in.
941    #[test]
942    fn every_generated_config_parses_and_resolves() {
943        use firstpass_core::Mode;
944        let mut n = 0;
945        for provider in Provider::ALL {
946            for shape in Shape::ALL {
947                for mode in [Mode::Observe, Mode::Enforce] {
948                    n += 1;
949                    let choice = LadderChoice {
950                        provider,
951                        shape,
952                        mode,
953                    };
954                    let toml = render_config(&choice);
955                    let cfg = firstpass_core::Config::parse(&toml).unwrap_or_else(|e| {
956                        panic!(
957                            "{}/{}/{mode:?} did not parse: {e}\n{toml}",
958                            provider.id(),
959                            shape.id()
960                        )
961                    });
962                    let route = &cfg.routes[0];
963                    assert_eq!(
964                        route.mode, mode,
965                        "route mode is what actually gates enforcement"
966                    );
967                    assert_eq!(
968                        route.ladder.len(),
969                        2,
970                        "a ladder needs somewhere to escalate to"
971                    );
972
973                    // Every gate the route names must be built in or declared here.
974                    for g in &route.gates {
975                        let builtin = g == "non-empty" || g == "json-valid";
976                        assert!(
977                            builtin || cfg.gate_defs.iter().any(|d| &d.id == g),
978                            "{}/{}: gate {g:?} is neither built in nor declared",
979                            provider.id(),
980                            shape.id()
981                        );
982                    }
983                    // Same for every provider a rung names.
984                    for rung in &route.ladder {
985                        let pid = rung.split('/').next().unwrap();
986                        let builtin = pid == "anthropic" || pid == "openai";
987                        assert!(
988                            builtin || cfg.providers.iter().any(|d| d.id == pid),
989                            "{}/{}: provider {pid:?} is neither built in nor declared",
990                            provider.id(),
991                            shape.id()
992                        );
993                    }
994                    // maker != checker: a judge drawn from the ladder would be rejected at runtime.
995                    if let Some(j) = cfg.gate_defs.iter().find_map(|d| d.judge.as_ref()) {
996                        assert!(
997                            !route.ladder.contains(&j.model),
998                            "{}: judge {} is on its own ladder",
999                            provider.id(),
1000                            j.model
1001                        );
1002                    }
1003                    // Observe must stay inert — an escalation cap implies enforcement.
1004                    assert_eq!(
1005                        toml.contains("[escalation]"),
1006                        mode == Mode::Enforce,
1007                        "escalation block should track enforce only"
1008                    );
1009                }
1010            }
1011        }
1012        assert_eq!(n, 32, "4 providers x 4 shapes x 2 modes");
1013    }
1014
1015    /// A written config the proxy never loads is worse than no config: `ProxyConfig::from_env`
1016    /// reads `FIRSTPASS_CONFIG` and has no default path, so the plan must carry it to the child.
1017    #[test]
1018    fn planned_config_is_written_before_the_proxy_starts_and_is_handed_to_it() {
1019        let home = std::path::Path::new("/home/u");
1020        let env = Environment {
1021            shell: "zsh".into(),
1022            proxy_running: false,
1023            already_routed: false,
1024            has_api_key: true,
1025            has_claude_cli: false,
1026            bind: "127.0.0.1:8080".into(),
1027        };
1028        let cfg = ConfigPlan {
1029            path: PathBuf::from("firstpass.toml"),
1030            choice: LadderChoice::default(),
1031        };
1032        let steps = plan(&env, home, false, Some(&cfg));
1033        assert!(
1034            matches!(&steps[0], Step::WriteConfig { path, .. } if path == &cfg.path),
1035            "config is written first, before anything reads it"
1036        );
1037        assert!(
1038            matches!(&steps[1], Step::StartProxy { config: Some(p) } if p == &cfg.path),
1039            "the spawned proxy is handed the config explicitly"
1040        );
1041
1042        // Without a config the plan is exactly what it always was.
1043        let steps = plan(&env, home, false, None);
1044        assert!(matches!(steps[0], Step::StartProxy { config: None }));
1045        assert!(!steps.iter().any(|s| matches!(s, Step::WriteConfig { .. })));
1046    }
1047
1048    /// Re-running onboard must never clobber a routing file the operator already edited.
1049    #[test]
1050    fn write_config_refuses_to_overwrite_an_existing_file() {
1051        let dir = std::env::temp_dir().join(format!("fp-cfg-{}", uuid::Uuid::now_v7()));
1052        std::fs::create_dir_all(&dir).unwrap();
1053        let path = dir.join("firstpass.toml");
1054        std::fs::write(&path, "# hand-tuned, do not touch\n").unwrap();
1055        let env = Environment {
1056            shell: "zsh".into(),
1057            proxy_running: true, // no spawn
1058            already_routed: true,
1059            has_api_key: true,
1060            has_claude_cli: false,
1061            bind: "127.0.0.1:1".into(),
1062        };
1063        let steps = vec![Step::WriteConfig {
1064            path: path.clone(),
1065            toml: render_config(&LadderChoice::default()),
1066        }];
1067        let report = execute(&env, &steps).unwrap();
1068        assert!(report.contains("already present"));
1069        assert_eq!(
1070            std::fs::read_to_string(&path).unwrap(),
1071            "# hand-tuned, do not touch\n",
1072            "existing config survived untouched"
1073        );
1074        let _ = std::fs::remove_dir_all(&dir);
1075    }
1076
1077    /// The dry run has to show the actual file, or "onboard asks then writes" is unverifiable
1078    /// before the fact.
1079    #[test]
1080    fn dry_run_shows_the_config_it_would_write() {
1081        let home = std::path::Path::new("/home/u");
1082        let env = Environment {
1083            shell: "bash".into(),
1084            proxy_running: false,
1085            already_routed: false,
1086            has_api_key: true,
1087            has_claude_cli: false,
1088            bind: "127.0.0.1:8080".into(),
1089        };
1090        let cfg = ConfigPlan {
1091            path: PathBuf::from("firstpass.toml"),
1092            choice: LadderChoice {
1093                provider: Provider::Local,
1094                shape: Shape::Code,
1095                mode: firstpass_core::Mode::Enforce,
1096            },
1097        };
1098        let text = render(&env, &plan(&env, home, false, Some(&cfg)), false);
1099        assert!(text.contains("write firstpass.toml"));
1100        assert!(text.contains("ollama"), "provider block is shown");
1101        assert!(text.contains("unit-tests"), "gate block is shown");
1102        assert!(
1103            text.contains("FIRSTPASS_CONFIG="),
1104            "explains how the proxy finds it"
1105        );
1106        assert!(text.contains("dry run — nothing changed"));
1107    }
1108
1109    /// The documentation site must not carry a second implementation of the config format.
1110    /// This pins the committed asset to what Rust generates; if they diverge, CI fails here
1111    /// rather than the site quietly shipping config the binary would reject.
1112    #[test]
1113    fn docs_presets_are_current() {
1114        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1115            .join("../../docs/assets/ladder-presets.js");
1116        let generated = presets_js();
1117
1118        // Regeneration is an explicit opt-in so a normal test run can never rewrite the repo.
1119        if std::env::var("FIRSTPASS_WRITE_PRESETS").is_ok() {
1120            std::fs::write(&path, &generated).expect("write presets");
1121            return;
1122        }
1123
1124        let committed = std::fs::read_to_string(&path).unwrap_or_else(|e| {
1125            panic!(
1126                "{}: {e}\nregenerate with:\n  \
1127                 FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets",
1128                path.display()
1129            )
1130        });
1131        assert_eq!(
1132            committed.replace("\r\n", "\n"),
1133            generated,
1134            "docs/assets/ladder-presets.js is stale — the docs builder and `firstpass onboard` \
1135             would emit different config.\nregenerate with:\n  \
1136             FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets"
1137        );
1138    }
1139
1140    /// Every preset the site can hand a user has to parse, for the same reason onboard's output
1141    /// does — the builder's whole value is that its output runs.
1142    #[test]
1143    fn every_docs_preset_parses() {
1144        let js = presets_js();
1145        let mut n = 0;
1146        for raw in js.split("\": \"").skip(1) {
1147            let lit = &raw[..raw.find("\",\n").unwrap_or(raw.len())];
1148            let toml = lit
1149                .replace("\\n", "\n")
1150                .replace("\\\"", "\"")
1151                .replace("\\\\", "\\");
1152            if !toml.contains("[[route]]") {
1153                continue;
1154            }
1155            n += 1;
1156            firstpass_core::Config::parse(&toml)
1157                .unwrap_or_else(|e| panic!("preset #{n} does not parse: {e}\n{toml}"));
1158        }
1159        assert_eq!(n, 32, "expected all 32 presets to be checked, saw {n}");
1160    }
1161
1162    /// A foreign listener on the bind port must never be mistaken for the proxy.
1163    ///
1164    /// This is a regression test for a real incident, not a hypothetical: an unrelated dev server
1165    /// held `:8080`, answered `GET /healthz` with `200` and the body below, and `firstpass onboard`
1166    /// reported "proxy already answering /healthz" and "verified — proxy healthy" — while writing
1167    /// `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` into the shell rc. That points the agent's
1168    /// credentialed traffic at a stranger and records no receipts, which is strictly worse than
1169    /// nothing listening, because it looks like it worked.
1170    #[test]
1171    fn a_foreign_listener_answering_healthz_is_not_accepted_as_the_proxy() {
1172        // Verbatim from the process that caused this.
1173        let foreign = r#"{"status":"ok","llmMode":"api","rlsEnforce":false,"appPoolActive":false}"#;
1174        assert!(
1175            !healthz_is_firstpass(true, foreign),
1176            "a 200 from a stranger must not read as Firstpass"
1177        );
1178
1179        // The real proxy names itself (see proxy::healthz), which is the discriminator.
1180        let ours = r#"{"status":"ok","service":"firstpass","version":"0.6.0"}"#;
1181        assert!(
1182            healthz_is_firstpass(true, ours),
1183            "the real proxy must still be recognised"
1184        );
1185
1186        // A non-200 is never Firstpass regardless of body, and neither is unparseable output.
1187        assert!(!healthz_is_firstpass(false, ours));
1188        assert!(!healthz_is_firstpass(true, "not json at all"));
1189        // A bare ok-status body — the shape the old check accepted — is still not enough.
1190        assert!(!healthz_is_firstpass(true, r#"{"status":"ok"}"#));
1191    }
1192}