1use std::io::Write as _;
12use std::path::PathBuf;
13
14pub const RC_MARKER: &str = "# added by `firstpass onboard`";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Environment {
22 pub shell: String,
24 pub proxy_running: bool,
26 pub already_routed: bool,
28 pub has_api_key: bool,
30 pub has_claude_cli: bool,
32 pub bind: String,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Provider {
40 Anthropic,
42 OpenAi,
44 Google,
46 Local,
48}
49
50impl Provider {
51 pub const ALL: [Self; 4] = [Self::Anthropic, Self::OpenAi, Self::Google, Self::Local];
53
54 #[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 #[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 #[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 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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum Shape {
132 Json,
134 Code,
136 Prose,
138 Mixed,
140}
141
142impl Shape {
143 pub const ALL: [Self; 4] = [Self::Json, Self::Code, Self::Prose, Self::Mixed];
145
146 #[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 #[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 #[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 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct LadderChoice {
226 pub provider: Provider,
228 pub shape: Shape,
230 pub mode: firstpass_core::Mode,
232}
233
234impl Default for LadderChoice {
235 fn default() -> Self {
238 Self {
239 provider: Provider::Anthropic,
240 shape: Shape::Json,
241 mode: firstpass_core::Mode::Observe,
242 }
243 }
244}
245
246#[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#[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
322fn 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#[derive(Debug, Clone, PartialEq, Eq)]
342pub enum Step {
343 WriteConfig {
345 path: PathBuf,
347 toml: String,
349 },
350 StartProxy {
352 config: Option<PathBuf>,
355 },
356 WireShell {
358 rc: PathBuf,
360 line: String,
362 },
363 SuggestClaudeMcp,
366 Verify,
368 AlreadyDone(&'static str),
370}
371
372pub 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#[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" => (
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#[derive(Debug, Clone)]
423pub struct ConfigPlan {
424 pub path: PathBuf,
426 pub choice: LadderChoice,
428}
429
430#[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#[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
523pub 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 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 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 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
612fn 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#[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
649pub 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); };
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
666pub 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 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"), ]),
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 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, already_routed: false,
835 has_api_key: true,
836 has_claude_cli: false,
837 bind: "127.0.0.1:1".into(), };
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 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 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 #[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 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 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 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 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 #[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 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 #[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, 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 #[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 #[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 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 #[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}