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            // Deliberately a placeholder, not `cargo test` / `npm test`: a gate is not just any
190            // command. It must read the candidate as JSON on stdin and print
191            // {"verdict":"pass|fail|abstain"} on stdout, so naming a real test runner here would
192            // look wired up while silently abstaining on every call. `doctor` flags this until
193            // it is replaced, which is the intended nudge.
194            Self::Code => {
195                "[[gate]]\n\
196                 # REPLACE ME. A gate reads the candidate as JSON on stdin and prints\n\
197                 #   {\"verdict\":\"pass|fail|abstain\", \"score\"?: 0.0-1.0, \"reason\"?: \"...\"}\n\
198                 # on stdout. Wrap your real test command in that contract — a bare `cargo test`\n\
199                 # or `npm test` will not work, it would abstain on every request.\n\
200                 # `firstpass doctor` fails on this line until you point it at your wrapper.\n\
201                 id  = \"unit-tests\"\n\
202                 cmd = [\"your-test-runner\", \"--from-stdin\"]\n"
203                    .to_owned()
204            }
205            Self::Prose => format!(
206                "[[gate]]                    # judge sits OUTSIDE the ladder: maker != checker\n\
207                 id    = \"judge\"\n\
208                 judge = {{ model = \"{}\", threshold = 0.7, rubric = \"The response fully and \
209                 correctly resolves the request, with no errors.\" }}\n",
210                provider.judge_model()
211            ),
212            Self::Mixed => format!(
213                "[[gate]]                    # k samples; agreement becomes the score\n\
214                 id          = \"uncertainty\"\n\
215                 consistency = {{ model = \"{}\", k = 3, threshold = 0.6 }}\n",
216                provider.ladder()[0]
217            ),
218        }
219    }
220}
221
222/// The three answers that decide a starting ladder. Everything else in the generated file follows
223/// from these, which is why onboarding asks exactly three questions and not a wizard's worth.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct LadderChoice {
226    /// Which provider the ladder opens on.
227    pub provider: Provider,
228    /// What the output is, which picks the gate.
229    pub shape: Shape,
230    /// `observe` forwards unchanged; `enforce` serves from the cheap rung once a gate passes.
231    pub mode: firstpass_core::Mode,
232}
233
234impl Default for LadderChoice {
235    /// The answer set used when nothing is on a terminal to ask: Claude, JSON, and observe — the
236    /// combination that changes no behavior at all.
237    fn default() -> Self {
238        Self {
239            provider: Provider::Anthropic,
240            shape: Shape::Json,
241            mode: firstpass_core::Mode::Observe,
242        }
243    }
244}
245
246/// Render a complete, runnable `firstpass.toml` for these answers — including the `[[provider]]`
247/// and `[[gate]]` blocks the choice requires. Emitting a fragment would be worse than emitting
248/// nothing: only `anthropic`/`openai` are built-in providers and only `non-empty`/`json-valid`
249/// are built-in gates, so anything else must be declared here or the file will not resolve.
250#[must_use]
251pub fn render_config(choice: &LadderChoice) -> String {
252    let enforce = choice.mode == firstpass_core::Mode::Enforce;
253    let mode = if enforce { "enforce" } else { "observe" };
254    let quoted = |xs: [&str; 2]| -> String { format!("\"{}\", \"{}\"", xs[0], xs[1]) };
255    let mut out = format!(
256        "# firstpass.toml — written by `firstpass onboard`. Re-run onboard to regenerate.\n\
257         #   FIRSTPASS_MODE={mode} FIRSTPASS_CONFIG=./firstpass.toml firstpass up\n\n"
258    );
259    if let Some(block) = choice.provider.provider_block() {
260        out.push_str(block);
261        out.push('\n');
262    }
263    out.push_str(&format!(
264        "[[route]]                   # routes match top to bottom; first match wins\n\
265         match  = {{}}                 # everything\n\
266         mode   = \"{mode}\"\n\
267         ladder = [{}]\n\
268         gates  = [{}]\n\n",
269        quoted(choice.provider.ladder()),
270        quoted(choice.shape.gates()),
271    ));
272    out.push_str(&choice.shape.gate_block(choice.provider));
273    if enforce {
274        out.push_str(
275            "\n[escalation]\nmax_rungs_per_request = 2   # one rung up, never a runaway\n",
276        );
277    } else {
278        out.push_str(
279            "\n# observe: every request is forwarded unchanged and a receipt is written off\n\
280             # the hot path. Nothing routes differently until mode = \"enforce\".\n",
281        );
282    }
283    out
284}
285
286/// Render every answer combination as a JavaScript asset for the documentation site.
287///
288/// The docs used to carry their own copy of this template in `docs/assets/docs.js`. Two
289/// implementations of the same config format drift silently — and a docs page that emits config
290/// the binary would reject is worse than a page with no builder at all. So Rust owns the format
291/// and the site consumes what Rust produced; `docs_presets_are_current` fails CI if this output
292/// and the committed asset disagree.
293#[must_use]
294pub fn presets_js() -> String {
295    use firstpass_core::Mode;
296    let mut out = String::from(
297        "// GENERATED by `cargo test -p firstpass-proxy presets` — do not edit by hand.\n\
298         // Source of truth: crates/firstpass-proxy/src/onboard.rs (render_config).\n\
299         // Regenerate: FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets\n\
300         window.FP_LADDER_PRESETS = {\n",
301    );
302    for provider in Provider::ALL {
303        out.push_str(&format!("  {:?}: {{\n", provider.id()));
304        for shape in Shape::ALL {
305            out.push_str(&format!("    {:?}: {{\n", shape.id()));
306            for (mode, key) in [(Mode::Observe, "observe"), (Mode::Enforce, "enforce")] {
307                let toml = render_config(&LadderChoice {
308                    provider,
309                    shape,
310                    mode,
311                });
312                out.push_str(&format!("      {key:?}: {},\n", js_string(&toml)));
313            }
314            out.push_str("    },\n");
315        }
316        out.push_str("  },\n");
317    }
318    out.push_str("};\n");
319    out
320}
321
322/// Encode a string as a JS double-quoted literal. Hand-rolled rather than pulling in a
323/// serialiser: the payload is our own generated TOML, and the escape set is small and fixed.
324fn js_string(s: &str) -> String {
325    let mut out = String::with_capacity(s.len() + 16);
326    out.push('"');
327    for c in s.chars() {
328        match c {
329            '"' => out.push_str("\\\""),
330            '\\' => out.push_str("\\\\"),
331            '\n' => out.push_str("\\n"),
332            '\r' => {}
333            c => out.push(c),
334        }
335    }
336    out.push('"');
337    out
338}
339
340/// One onboarding step: what it is, and whether it's already satisfied.
341#[derive(Debug, Clone, PartialEq, Eq)]
342pub enum Step {
343    /// Write the generated routing config. Never overwrites an existing file — the caller checks.
344    WriteConfig {
345        /// Where the file goes (`./firstpass.toml`).
346        path: PathBuf,
347        /// Full rendered contents.
348        toml: String,
349    },
350    /// Spawn `firstpass up` detached (observe mode), logging to `firstpass-proxy.log`.
351    StartProxy {
352        /// Config to hand the child via `FIRSTPASS_CONFIG`. The proxy has no default config path,
353        /// so a written file is inert unless it is passed explicitly.
354        config: Option<PathBuf>,
355    },
356    /// Append the marked `ANTHROPIC_BASE_URL` export to the shell rc file.
357    WireShell {
358        /// Rc file the line goes into.
359        rc: PathBuf,
360        /// The exact line (shell-dialect aware).
361        line: String,
362    },
363    /// Print the `claude mcp add` command so Claude Code can query traces/savings as tools.
364    /// (Printed, not executed — mutating another tool's config uninvited isn't onboarding.)
365    SuggestClaudeMcp,
366    /// Probe `/healthz` and `/v1/capabilities` and report what's routed.
367    Verify,
368    /// Nothing to do — with the reason shown to the user.
369    AlreadyDone(&'static str),
370}
371
372/// Detect the environment via injected lookups: `env(key)` for env vars, `on_path(bin)` for PATH
373/// probes, `healthz()` for a live proxy probe. Pure decision logic; all I/O behind the closures.
374pub fn detect(
375    env: impl Fn(&str) -> Option<String>,
376    on_path: impl Fn(&str) -> bool,
377    healthz: impl Fn() -> bool,
378) -> Environment {
379    let bind = env("FIRSTPASS_BIND").unwrap_or_else(|| "127.0.0.1:8080".to_owned());
380    let base_url = format!("http://{bind}");
381    let shell = env("SHELL")
382        .and_then(|s| s.rsplit('/').next().map(str::to_owned))
383        .unwrap_or_else(|| "sh".to_owned());
384    Environment {
385        shell,
386        proxy_running: healthz(),
387        already_routed: env("ANTHROPIC_BASE_URL").is_some_and(|v| v == base_url),
388        has_api_key: env("ANTHROPIC_API_KEY").is_some(),
389        has_claude_cli: on_path("claude"),
390        bind,
391    }
392}
393
394/// The shell-dialect line that routes agents through the proxy, plus the rc file it belongs in.
395/// `home` is injected so tests never touch a real home directory.
396#[must_use]
397pub fn shell_wiring(shell: &str, home: &std::path::Path, bind: &str) -> (PathBuf, String) {
398    let url = format!("http://{bind}");
399    match shell {
400        "fish" => (
401            home.join(".config/fish/config.fish"),
402            format!("set -gx ANTHROPIC_BASE_URL {url}  {RC_MARKER}"),
403        ),
404        "bash" => (
405            home.join(".bashrc"),
406            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
407        ),
408        // zsh and anything else POSIX-ish: default to ~/.zshrc only for zsh, else ~/.profile.
409        "zsh" => (
410            home.join(".zshrc"),
411            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
412        ),
413        _ => (
414            home.join(".profile"),
415            format!("export ANTHROPIC_BASE_URL={url}  {RC_MARKER}"),
416        ),
417    }
418}
419
420/// A config the caller wants written: where it goes and the answers behind it. `None` means the
421/// step is skipped — either a `firstpass.toml` is already there or the user opted out.
422#[derive(Debug, Clone)]
423pub struct ConfigPlan {
424    /// Destination, normally `./firstpass.toml`.
425    pub path: PathBuf,
426    /// The three answers.
427    pub choice: LadderChoice,
428}
429
430/// Build the ordered plan for this environment. `rc_already_wired` is whether the rc file already
431/// carries the marker line (checked by the caller, injected here to stay pure). `config` is the
432/// routing file to generate, if any — it is written *before* the proxy starts so the child can be
433/// handed it, since a config the proxy never loads is worse than no config at all.
434#[must_use]
435pub fn plan(
436    env: &Environment,
437    home: &std::path::Path,
438    rc_already_wired: bool,
439    config: Option<&ConfigPlan>,
440) -> Vec<Step> {
441    let mut steps = Vec::new();
442    if let Some(c) = config {
443        steps.push(Step::WriteConfig {
444            path: c.path.clone(),
445            toml: render_config(&c.choice),
446        });
447    }
448    if env.proxy_running {
449        steps.push(Step::AlreadyDone("proxy already answering /healthz"));
450    } else {
451        steps.push(Step::StartProxy {
452            config: config.map(|c| c.path.clone()),
453        });
454    }
455    if env.already_routed || rc_already_wired {
456        steps.push(Step::AlreadyDone("ANTHROPIC_BASE_URL already wired"));
457    } else {
458        let (rc, line) = shell_wiring(&env.shell, home, &env.bind);
459        steps.push(Step::WireShell { rc, line });
460    }
461    if env.has_claude_cli {
462        steps.push(Step::SuggestClaudeMcp);
463    }
464    steps.push(Step::Verify);
465    steps
466}
467
468/// Render the plan for the dry run (default) or as the running commentary under `--apply`.
469#[must_use]
470pub fn render(env: &Environment, steps: &[Step], apply: bool) -> String {
471    let mut out = String::new();
472    out.push_str(&format!(
473        "detected: shell={} · proxy_running={} · routed={} · api_key={} · claude_cli={}\n\n",
474        env.shell, env.proxy_running, env.already_routed, env.has_api_key, env.has_claude_cli
475    ));
476    for (i, s) in steps.iter().enumerate() {
477        let n = i + 1;
478        match s {
479            Step::WriteConfig { path, toml } => {
480                out.push_str(&format!("{n}. write {} —\n", path.display()));
481                for line in toml.lines() {
482                    out.push_str(&format!("     {line}\n"));
483                }
484            }
485            Step::StartProxy { config } => {
486                out.push_str(&format!(
487                    "{n}. start the proxy — `firstpass up` (observe mode: watches, changes nothing), log → firstpass-proxy.log\n"
488                ));
489                if let Some(c) = config {
490                    out.push_str(&format!(
491                        "     with FIRSTPASS_CONFIG={} — the proxy has no default config path\n",
492                        c.display()
493                    ));
494                }
495            }
496            Step::WireShell { rc, line } => out.push_str(&format!(
497                "{n}. route your agents — append to {}:\n     {line}\n",
498                rc.display()
499            )),
500            Step::SuggestClaudeMcp => out.push_str(&format!(
501                "{n}. (optional) let Claude Code query receipts as tools:\n     claude mcp add firstpass -- firstpass mcp\n"
502            )),
503            Step::Verify => out.push_str(&format!(
504                "{n}. verify — probe /healthz and /v1/capabilities, report what's routed\n"
505            )),
506            Step::AlreadyDone(why) => out.push_str(&format!("{n}. ✓ {why}\n")),
507        }
508    }
509    if !env.has_api_key {
510        out.push_str(
511            "\nnote: ANTHROPIC_API_KEY is not set — observe mode passes your agent's own key \
512             through (BYOK), so this only matters for enforce mode.\n",
513        );
514    }
515    if !apply {
516        out.push_str(
517            "\ndry run — nothing changed. Re-run with `firstpass onboard --apply` to execute.\n",
518        );
519    }
520    out
521}
522
523/// Execute the side-effectful steps. Returns a human report. Failures are reported per step —
524/// onboarding never half-dies silently.
525///
526/// # Errors
527/// Only on I/O failures writing the rc file; every other issue is reported in the returned text.
528pub fn execute(env: &Environment, steps: &[Step]) -> Result<String, std::io::Error> {
529    let mut out = String::new();
530    for s in steps {
531        match s {
532            Step::WriteConfig { path, toml } => {
533                // Never clobber a config the operator already has; the caller only plans this
534                // step when the path is free, but re-check rather than trust the gap between.
535                if path.exists() {
536                    out.push_str(&format!(
537                        "✓ {} already present — left untouched\n",
538                        path.display()
539                    ));
540                } else {
541                    std::fs::write(path, toml)?;
542                    out.push_str(&format!("✓ wrote {}\n", path.display()));
543                }
544            }
545            Step::StartProxy { config } => {
546                let log = std::fs::File::create("firstpass-proxy.log")?;
547                let exe = std::env::current_exe()?;
548                let mut cmd = std::process::Command::new(exe);
549                cmd.arg("up");
550                if let Some(c) = config {
551                    // A written config is inert unless it is named: `ProxyConfig::from_env` reads
552                    // `FIRSTPASS_CONFIG` and has no default path to fall back on.
553                    cmd.env("FIRSTPASS_CONFIG", c);
554                }
555                let child = cmd
556                    .stdin(std::process::Stdio::null())
557                    .stdout(std::process::Stdio::from(log.try_clone()?))
558                    .stderr(std::process::Stdio::from(log))
559                    .spawn();
560                match child {
561                    Ok(c) => {
562                        // Pidfile makes `firstpass offboard` able to stop what onboard started.
563                        let _ = std::fs::write("firstpass-proxy.pid", c.id().to_string());
564                        out.push_str(&format!(
565                            "✓ proxy started (pid {}, observe mode) — log: firstpass-proxy.log\n",
566                            c.id()
567                        ));
568                    }
569                    Err(e) => out.push_str(&format!("✗ could not start proxy: {e}\n")),
570                }
571            }
572            Step::WireShell { rc, line } => {
573                if let Some(parent) = rc.parent() {
574                    std::fs::create_dir_all(parent)?;
575                }
576                let mut f = std::fs::OpenOptions::new()
577                    .create(true)
578                    .append(true)
579                    .open(rc)?;
580                writeln!(f, "{line}")?;
581                out.push_str(&format!(
582                    "✓ wired {} — takes effect in new shells; for this one:\n     {}\n",
583                    rc.display(),
584                    line.trim_end_matches(RC_MARKER).trim_end()
585                ));
586            }
587            Step::SuggestClaudeMcp => {
588                out.push_str("→ optional: claude mcp add firstpass -- firstpass mcp\n");
589            }
590            Step::Verify => {
591                let url = format!("http://{}/healthz", env.bind);
592                let ok = wait_healthz(&url, std::time::Duration::from_secs(6));
593                if ok {
594                    out.push_str(&format!(
595                        "✓ verified — proxy healthy at http://{} · capabilities: http://{}/v1/capabilities\n",
596                        env.bind, env.bind
597                    ));
598                } else {
599                    out.push_str(&format!(
600                        "✗ proxy not answering http://{} after 6s — check firstpass-proxy.log\n",
601                        env.bind
602                    ));
603                }
604            }
605            Step::AlreadyDone(why) => out.push_str(&format!("✓ {why}\n")),
606        }
607    }
608    out.push_str("\noffboard any time: unset ANTHROPIC_BASE_URL (and remove the marked rc line)\n");
609    Ok(out)
610}
611
612/// Poll `/healthz` until it answers 200 or the deadline passes. Blocking + std-only (the CLI calls
613/// this off the async runtime): a plain TCP connect + minimal HTTP/1.1 GET, no client dependency.
614fn wait_healthz(url: &str, deadline: std::time::Duration) -> bool {
615    let Some(addr) = url
616        .strip_prefix("http://")
617        .and_then(|r| r.split('/').next())
618        .map(str::to_owned)
619    else {
620        return false;
621    };
622    let start = std::time::Instant::now();
623    while start.elapsed() < deadline {
624        if let Ok(mut s) = std::net::TcpStream::connect(&addr) {
625            let _ = s.set_read_timeout(Some(std::time::Duration::from_millis(500)));
626            let req = format!("GET /healthz HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
627            if s.write_all(req.as_bytes()).is_ok() {
628                let mut buf = [0u8; 64];
629                use std::io::Read as _;
630                if let Ok(n) = s.read(&mut buf)
631                    && n > 0
632                    && String::from_utf8_lossy(&buf[..n]).contains("200")
633                {
634                    return true;
635                }
636            }
637        }
638        std::thread::sleep(std::time::Duration::from_millis(200));
639    }
640    false
641}
642
643/// Whether the rc file already carries the onboard marker (idempotence check for [`plan`]).
644#[must_use]
645pub fn rc_wired(rc: &std::path::Path) -> bool {
646    std::fs::read_to_string(rc).is_ok_and(|s| s.contains(RC_MARKER))
647}
648
649/// Remove every marked onboard line from `rc`. Returns whether anything was removed. Only lines
650/// carrying [`RC_MARKER`] are touched — nothing else in the user's rc is ever rewritten.
651///
652/// # Errors
653/// Only on I/O failures reading/writing the rc file.
654pub fn offboard_rc(rc: &std::path::Path) -> Result<bool, std::io::Error> {
655    let Ok(content) = std::fs::read_to_string(rc) else {
656        return Ok(false); // no file → nothing to offboard
657    };
658    if !content.contains(RC_MARKER) {
659        return Ok(false);
660    }
661    let kept: Vec<&str> = content.lines().filter(|l| !l.contains(RC_MARKER)).collect();
662    std::fs::write(rc, kept.join("\n") + "\n")?;
663    Ok(true)
664}
665
666/// `firstpass offboard` — the exact mirror of onboard: strip the marked line from every candidate
667/// rc file, stop the proxy onboard started (pidfile), and print the one command for this shell.
668/// Fully idempotent; reports what it found either way.
669///
670/// # Errors
671/// Only on rc-file I/O failures.
672pub fn offboard(home: &std::path::Path) -> Result<String, std::io::Error> {
673    let mut out = String::new();
674    for rc in [
675        home.join(".zshrc"),
676        home.join(".bashrc"),
677        home.join(".profile"),
678        home.join(".config/fish/config.fish"),
679    ] {
680        if offboard_rc(&rc)? {
681            out.push_str(&format!("✓ removed firstpass line from {}\n", rc.display()));
682        }
683    }
684    // Stop the proxy onboard spawned, if its pidfile is present.
685    if let Ok(pid) = std::fs::read_to_string("firstpass-proxy.pid") {
686        let pid = pid.trim().to_owned();
687        #[cfg(unix)]
688        {
689            let killed = std::process::Command::new("kill")
690                .arg(&pid)
691                .status()
692                .is_ok_and(|s| s.success());
693            if killed {
694                out.push_str(&format!("✓ stopped proxy (pid {pid})\n"));
695            } else {
696                out.push_str(&format!(
697                    "→ proxy pid {pid} not running (already stopped)\n"
698                ));
699            }
700        }
701        let _ = std::fs::remove_file("firstpass-proxy.pid");
702    }
703    if out.is_empty() {
704        out.push_str("nothing to offboard — no marked rc lines, no pidfile.\n");
705    }
706    out.push_str("for this shell: unset ANTHROPIC_BASE_URL\n");
707    Ok(out)
708}
709
710#[cfg(test)]
711mod tests {
712    #![allow(clippy::unwrap_used)]
713    use super::*;
714
715    fn env_of<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
716        move |k| {
717            pairs
718                .iter()
719                .find(|(a, _)| *a == k)
720                .map(|(_, v)| (*v).to_owned())
721        }
722    }
723
724    #[test]
725    fn detect_reads_shell_routing_and_tools() {
726        let e = detect(
727            env_of(&[
728                ("SHELL", "/bin/zsh"),
729                ("ANTHROPIC_BASE_URL", "http://127.0.0.1:8080"),
730                ("ANTHROPIC_API_KEY", "sk-x"),
731            ]),
732            |bin| bin == "claude",
733            || true,
734        );
735        assert_eq!(e.shell, "zsh");
736        assert!(e.proxy_running && e.already_routed && e.has_api_key && e.has_claude_cli);
737        assert_eq!(e.bind, "127.0.0.1:8080");
738    }
739
740    #[test]
741    fn detect_respects_custom_bind_and_mismatched_base_url() {
742        let e = detect(
743            env_of(&[
744                ("FIRSTPASS_BIND", "127.0.0.1:9999"),
745                ("ANTHROPIC_BASE_URL", "http://127.0.0.1:8080"), // points elsewhere
746            ]),
747            |_| false,
748            || false,
749        );
750        assert_eq!(e.bind, "127.0.0.1:9999");
751        assert!(
752            !e.already_routed,
753            "routed to a different port is not routed"
754        );
755    }
756
757    #[test]
758    fn shell_wiring_speaks_each_dialect() {
759        let home = std::path::Path::new("/home/u");
760        let (rc, line) = shell_wiring("fish", home, "127.0.0.1:8080");
761        assert!(rc.ends_with(".config/fish/config.fish"));
762        assert!(line.starts_with("set -gx ANTHROPIC_BASE_URL http://127.0.0.1:8080"));
763
764        let (rc, line) = shell_wiring("zsh", home, "127.0.0.1:8080");
765        assert!(rc.ends_with(".zshrc"));
766        assert!(line.starts_with("export ANTHROPIC_BASE_URL="));
767
768        let (rc, _) = shell_wiring("dash", home, "127.0.0.1:8080");
769        assert!(
770            rc.ends_with(".profile"),
771            "unknown shells fall back to .profile"
772        );
773    }
774
775    #[test]
776    fn plan_covers_fresh_machine_and_is_idempotent_when_done() {
777        let home = std::path::Path::new("/home/u");
778        let fresh = Environment {
779            shell: "zsh".into(),
780            proxy_running: false,
781            already_routed: false,
782            has_api_key: false,
783            has_claude_cli: true,
784            bind: "127.0.0.1:8080".into(),
785        };
786        let steps = plan(&fresh, home, false, None);
787        assert!(matches!(steps[0], Step::StartProxy { .. }));
788        assert!(matches!(steps[1], Step::WireShell { .. }));
789        assert!(matches!(steps[2], Step::SuggestClaudeMcp));
790        assert!(matches!(steps.last(), Some(Step::Verify)));
791
792        // Everything already set up → only AlreadyDone + Verify, nothing mutating.
793        let done = Environment {
794            proxy_running: true,
795            already_routed: true,
796            has_claude_cli: false,
797            ..fresh
798        };
799        let steps = plan(&done, home, true, None);
800        assert!(
801            steps
802                .iter()
803                .all(|s| matches!(s, Step::AlreadyDone(_) | Step::Verify))
804        );
805    }
806
807    #[test]
808    fn render_dry_run_says_nothing_changed_and_flags_missing_key() {
809        let home = std::path::Path::new("/home/u");
810        let e = Environment {
811            shell: "bash".into(),
812            proxy_running: false,
813            already_routed: false,
814            has_api_key: false,
815            has_claude_cli: false,
816            bind: "127.0.0.1:8080".into(),
817        };
818        let text = render(&e, &plan(&e, home, false, None), false);
819        assert!(text.contains("dry run — nothing changed"));
820        assert!(text.contains("ANTHROPIC_API_KEY is not set"));
821        assert!(text.contains(".bashrc"));
822    }
823
824    #[test]
825    fn rc_wired_detects_the_marker_and_execute_appends_it_once() {
826        let dir = std::env::temp_dir().join(format!("fp-onboard-{}", uuid::Uuid::now_v7()));
827        std::fs::create_dir_all(&dir).unwrap();
828        let rc = dir.join(".zshrc");
829        assert!(!rc_wired(&rc), "missing file is not wired");
830
831        let e = Environment {
832            shell: "zsh".into(),
833            proxy_running: true, // no spawn in this test
834            already_routed: false,
835            has_api_key: true,
836            has_claude_cli: false,
837            bind: "127.0.0.1:1".into(), // verify step will fail fast — that's fine, we assert wiring
838        };
839        let (rc_path, line) = shell_wiring("zsh", &dir, &e.bind);
840        let steps = vec![Step::WireShell {
841            rc: rc_path.clone(),
842            line,
843        }];
844        let report = execute(&e, &steps).unwrap();
845        assert!(report.contains("✓ wired"));
846        assert!(rc_wired(&rc_path), "marker written");
847        // Re-planning with the marker present must not wire again (idempotent onboarding).
848        let steps = plan(&e, &dir, rc_wired(&rc_path), None);
849        assert!(!steps.iter().any(|s| matches!(s, Step::WireShell { .. })));
850
851        let _ = std::fs::remove_dir_all(&dir);
852    }
853
854    #[test]
855    fn offboard_removes_only_the_marked_line_and_is_idempotent() {
856        let dir = std::env::temp_dir().join(format!("fp-offboard-{}", uuid::Uuid::now_v7()));
857        std::fs::create_dir_all(&dir).unwrap();
858        let rc = dir.join(".zshrc");
859        std::fs::write(
860            &rc,
861            format!("alias ll='ls -l'\nexport ANTHROPIC_BASE_URL=http://127.0.0.1:8080  {RC_MARKER}\nexport EDITOR=vim\n"),
862        )
863        .unwrap();
864
865        assert!(offboard_rc(&rc).unwrap(), "marked line removed");
866        let after = std::fs::read_to_string(&rc).unwrap();
867        assert!(!after.contains(RC_MARKER));
868        assert!(
869            after.contains("alias ll") && after.contains("EDITOR=vim"),
870            "user lines untouched"
871        );
872        assert!(!offboard_rc(&rc).unwrap(), "second offboard is a no-op");
873
874        // The full offboard reports the rc removal and the unset line.
875        std::fs::write(&rc, format!("x  {RC_MARKER}\n")).unwrap();
876        let report = offboard(&dir).unwrap();
877        assert!(report.contains("removed firstpass line"));
878        assert!(report.contains("unset ANTHROPIC_BASE_URL"));
879
880        let _ = std::fs::remove_dir_all(&dir);
881    }
882
883    /// The whole point of generating a config is that it runs. Every answer combination must
884    /// survive the real parser — including the `[[provider]]`/`[[gate]]` blocks each one implies,
885    /// since only `anthropic`/`openai` and `non-empty`/`json-valid` are built in.
886    #[test]
887    fn every_generated_config_parses_and_resolves() {
888        use firstpass_core::Mode;
889        let mut n = 0;
890        for provider in Provider::ALL {
891            for shape in Shape::ALL {
892                for mode in [Mode::Observe, Mode::Enforce] {
893                    n += 1;
894                    let choice = LadderChoice {
895                        provider,
896                        shape,
897                        mode,
898                    };
899                    let toml = render_config(&choice);
900                    let cfg = firstpass_core::Config::parse(&toml).unwrap_or_else(|e| {
901                        panic!(
902                            "{}/{}/{mode:?} did not parse: {e}\n{toml}",
903                            provider.id(),
904                            shape.id()
905                        )
906                    });
907                    let route = &cfg.routes[0];
908                    assert_eq!(
909                        route.mode, mode,
910                        "route mode is what actually gates enforcement"
911                    );
912                    assert_eq!(
913                        route.ladder.len(),
914                        2,
915                        "a ladder needs somewhere to escalate to"
916                    );
917
918                    // Every gate the route names must be built in or declared here.
919                    for g in &route.gates {
920                        let builtin = g == "non-empty" || g == "json-valid";
921                        assert!(
922                            builtin || cfg.gate_defs.iter().any(|d| &d.id == g),
923                            "{}/{}: gate {g:?} is neither built in nor declared",
924                            provider.id(),
925                            shape.id()
926                        );
927                    }
928                    // Same for every provider a rung names.
929                    for rung in &route.ladder {
930                        let pid = rung.split('/').next().unwrap();
931                        let builtin = pid == "anthropic" || pid == "openai";
932                        assert!(
933                            builtin || cfg.providers.iter().any(|d| d.id == pid),
934                            "{}/{}: provider {pid:?} is neither built in nor declared",
935                            provider.id(),
936                            shape.id()
937                        );
938                    }
939                    // maker != checker: a judge drawn from the ladder would be rejected at runtime.
940                    if let Some(j) = cfg.gate_defs.iter().find_map(|d| d.judge.as_ref()) {
941                        assert!(
942                            !route.ladder.contains(&j.model),
943                            "{}: judge {} is on its own ladder",
944                            provider.id(),
945                            j.model
946                        );
947                    }
948                    // Observe must stay inert — an escalation cap implies enforcement.
949                    assert_eq!(
950                        toml.contains("[escalation]"),
951                        mode == Mode::Enforce,
952                        "escalation block should track enforce only"
953                    );
954                }
955            }
956        }
957        assert_eq!(n, 32, "4 providers x 4 shapes x 2 modes");
958    }
959
960    /// A written config the proxy never loads is worse than no config: `ProxyConfig::from_env`
961    /// reads `FIRSTPASS_CONFIG` and has no default path, so the plan must carry it to the child.
962    #[test]
963    fn planned_config_is_written_before_the_proxy_starts_and_is_handed_to_it() {
964        let home = std::path::Path::new("/home/u");
965        let env = Environment {
966            shell: "zsh".into(),
967            proxy_running: false,
968            already_routed: false,
969            has_api_key: true,
970            has_claude_cli: false,
971            bind: "127.0.0.1:8080".into(),
972        };
973        let cfg = ConfigPlan {
974            path: PathBuf::from("firstpass.toml"),
975            choice: LadderChoice::default(),
976        };
977        let steps = plan(&env, home, false, Some(&cfg));
978        assert!(
979            matches!(&steps[0], Step::WriteConfig { path, .. } if path == &cfg.path),
980            "config is written first, before anything reads it"
981        );
982        assert!(
983            matches!(&steps[1], Step::StartProxy { config: Some(p) } if p == &cfg.path),
984            "the spawned proxy is handed the config explicitly"
985        );
986
987        // Without a config the plan is exactly what it always was.
988        let steps = plan(&env, home, false, None);
989        assert!(matches!(steps[0], Step::StartProxy { config: None }));
990        assert!(!steps.iter().any(|s| matches!(s, Step::WriteConfig { .. })));
991    }
992
993    /// Re-running onboard must never clobber a routing file the operator already edited.
994    #[test]
995    fn write_config_refuses_to_overwrite_an_existing_file() {
996        let dir = std::env::temp_dir().join(format!("fp-cfg-{}", uuid::Uuid::now_v7()));
997        std::fs::create_dir_all(&dir).unwrap();
998        let path = dir.join("firstpass.toml");
999        std::fs::write(&path, "# hand-tuned, do not touch\n").unwrap();
1000        let env = Environment {
1001            shell: "zsh".into(),
1002            proxy_running: true, // no spawn
1003            already_routed: true,
1004            has_api_key: true,
1005            has_claude_cli: false,
1006            bind: "127.0.0.1:1".into(),
1007        };
1008        let steps = vec![Step::WriteConfig {
1009            path: path.clone(),
1010            toml: render_config(&LadderChoice::default()),
1011        }];
1012        let report = execute(&env, &steps).unwrap();
1013        assert!(report.contains("already present"));
1014        assert_eq!(
1015            std::fs::read_to_string(&path).unwrap(),
1016            "# hand-tuned, do not touch\n",
1017            "existing config survived untouched"
1018        );
1019        let _ = std::fs::remove_dir_all(&dir);
1020    }
1021
1022    /// The dry run has to show the actual file, or "onboard asks then writes" is unverifiable
1023    /// before the fact.
1024    #[test]
1025    fn dry_run_shows_the_config_it_would_write() {
1026        let home = std::path::Path::new("/home/u");
1027        let env = Environment {
1028            shell: "bash".into(),
1029            proxy_running: false,
1030            already_routed: false,
1031            has_api_key: true,
1032            has_claude_cli: false,
1033            bind: "127.0.0.1:8080".into(),
1034        };
1035        let cfg = ConfigPlan {
1036            path: PathBuf::from("firstpass.toml"),
1037            choice: LadderChoice {
1038                provider: Provider::Local,
1039                shape: Shape::Code,
1040                mode: firstpass_core::Mode::Enforce,
1041            },
1042        };
1043        let text = render(&env, &plan(&env, home, false, Some(&cfg)), false);
1044        assert!(text.contains("write firstpass.toml"));
1045        assert!(text.contains("ollama"), "provider block is shown");
1046        assert!(text.contains("unit-tests"), "gate block is shown");
1047        assert!(
1048            text.contains("FIRSTPASS_CONFIG="),
1049            "explains how the proxy finds it"
1050        );
1051        assert!(text.contains("dry run — nothing changed"));
1052    }
1053
1054    /// The documentation site must not carry a second implementation of the config format.
1055    /// This pins the committed asset to what Rust generates; if they diverge, CI fails here
1056    /// rather than the site quietly shipping config the binary would reject.
1057    #[test]
1058    fn docs_presets_are_current() {
1059        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1060            .join("../../docs/assets/ladder-presets.js");
1061        let generated = presets_js();
1062
1063        // Regeneration is an explicit opt-in so a normal test run can never rewrite the repo.
1064        if std::env::var("FIRSTPASS_WRITE_PRESETS").is_ok() {
1065            std::fs::write(&path, &generated).expect("write presets");
1066            return;
1067        }
1068
1069        let committed = std::fs::read_to_string(&path).unwrap_or_else(|e| {
1070            panic!(
1071                "{}: {e}\nregenerate with:\n  \
1072                 FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets",
1073                path.display()
1074            )
1075        });
1076        assert_eq!(
1077            committed.replace("\r\n", "\n"),
1078            generated,
1079            "docs/assets/ladder-presets.js is stale — the docs builder and `firstpass onboard` \
1080             would emit different config.\nregenerate with:\n  \
1081             FIRSTPASS_WRITE_PRESETS=1 cargo test -p firstpass-proxy presets"
1082        );
1083    }
1084
1085    /// Every preset the site can hand a user has to parse, for the same reason onboard's output
1086    /// does — the builder's whole value is that its output runs.
1087    #[test]
1088    fn every_docs_preset_parses() {
1089        let js = presets_js();
1090        let mut n = 0;
1091        for raw in js.split("\": \"").skip(1) {
1092            let lit = &raw[..raw.find("\",\n").unwrap_or(raw.len())];
1093            let toml = lit
1094                .replace("\\n", "\n")
1095                .replace("\\\"", "\"")
1096                .replace("\\\\", "\\");
1097            if !toml.contains("[[route]]") {
1098                continue;
1099            }
1100            n += 1;
1101            firstpass_core::Config::parse(&toml)
1102                .unwrap_or_else(|e| panic!("preset #{n} does not parse: {e}\n{toml}"));
1103        }
1104        assert_eq!(n, 32, "expected all 32 presets to be checked, saw {n}");
1105    }
1106}