firstpass-proxy 0.2.7

Drop-in, Anthropic-compatible LLM proxy that routes each request to the cheapest model that provably passes a quality gate, escalates on failure, and records a tamper-evident audit trace.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! `firstpass` — the unified CLI (SPEC §7.3/§7.4): start the proxy, validate a setup, or read the
//! audit trail. Every subcommand reads the same environment as the server, so onboarding is one
//! `base_url` swap and offboarding is one `unset`.

use firstpass_core::RoutingMode;
use firstpass_proxy::calibrate::{calibrate_from_store, calibrate_from_store_ltt};
use firstpass_proxy::ope::{CandidatePolicy, ips_from_store, ope_from_store};
use firstpass_proxy::{ProxyConfig, cli, run, store};

const HELP: &str = "\
firstpass — the cheapest model that provably passes, with a receipt for every call.

USAGE:
    firstpass upgrade             upgrade in place, or print the exact command for however
                                  this copy was installed (brew / uv / npm / docker / cargo)
    firstpass demo                no keys, no config: run one real gated decision and print
                                  its receipt (local mock upstream, real proxy)
    firstpass onboard [--apply]   agentic setup: ask three questions, write firstpass.toml,
                                  start the proxy, route your agent, verify
        [--provider anthropic|openai|google|local] [--shape json|code|prose|mixed]
        [--mode observe|enforce]  answer non-interactively (an agent piping input never blocks)
        [--yes] [--no-config]     take the defaults / skip config generation entirely
    firstpass offboard            undo it: strip the rc line, stop the proxy, print the unset
    firstpass up                  start the proxy (serves until Ctrl-C)
    firstpass doctor              validate config, provider key, and gate binaries
    firstpass trace [--limit N]   print recent audit traces as JSON lines (default 20)
    firstpass savings [--json]    spend vs the always-top counterfactual, from your own receipts
    firstpass evals [--json]      per-gate verdict rates + escalation + serve-by-rung, from receipts
    firstpass predictor-eval [--json] [--lr L] [--l2 R]
                                   prequential AUC/Brier of the per-query P(pass) predictor
    firstpass explain <trace-id>  [--json]  why one routing decision went the way it did
    firstpass export [--out F]    write the sealed receipt log as JSONL (hand to an auditor)
    firstpass verify [--file F] [--json]
                                   independently re-derive the receipt hash chain; exit 1 if broken
    firstpass calibrate [--alpha A] [--delta D] [--min-n N] [--method conformal|ltt]
                                   recalibrate the serving threshold from deferred feedback
                                   (default method: conformal; ltt = Learn-then-Test / RCPS)
    firstpass ope --config <candidate.toml> [--db <path>] [--tenant <id>]
                                   evaluate a candidate policy against logged traffic before enforcing
    firstpass ope --start-rung N [--db <path>] [--tenant <id>]
                                   IPS/SNIPS/DR estimate for a fixed start-rung (requires propensity-logged traffic)
    firstpass modes               list routing-mode profiles, what each sets, and honest tradeoffs
    firstpass mcp                 serve MCP over stdio (agent reads traces + submits feedback)
    firstpass --help | --version

ENVIRONMENT (shared by every subcommand):
    FIRSTPASS_MODE=observe|enforce       FIRSTPASS_BIND=127.0.0.1:8080
    FIRSTPASS_MODE_PROFILE=balanced|...  global routing-mode preset (default: balanced)
    FIRSTPASS_CONFIG=./firstpass.toml (or FIRSTPASS_CONFIG_TOML=<inline>)
    FIRSTPASS_DB=./firstpass.db          RUST_LOG=info

Point your agent at it:  export ANTHROPIC_BASE_URL=http://127.0.0.1:8080
Offboard any time:       unset ANTHROPIC_BASE_URL";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().collect();
    match args.get(1).map(String::as_str).unwrap_or("--help") {
        "up" => {
            run::init_tracing();
            run::serve(ProxyConfig::from_env()?).await
        }
        "demo" => firstpass_proxy::demo::run().await,
        "upgrade" => cmd_upgrade(),
        "onboard" => cmd_onboard(args.iter().any(|a| a == "--apply")),
        "offboard" => cmd_offboard(),
        "doctor" => cmd_doctor(),
        "trace" => cmd_trace(&args),
        "savings" => cmd_savings(&args),
        "evals" => cmd_evals(&args),
        "predictor-eval" => cmd_predictor_eval(&args),
        "explain" => cmd_explain(&args),
        "export" => cmd_export(&args),
        "verify" => cmd_verify(&args),
        "calibrate" => cmd_calibrate(&args),
        "ope" => cmd_ope(&args),
        "modes" => cmd_modes(),
        "mcp" => {
            // Synchronous stdio server; run it off the async runtime so nothing else contends.
            // Scoped to a single tenant (ADR 0004 §D3): `--tenant <id>` or the configured default.
            let config = ProxyConfig::from_env()?;
            let tenant = tenant_arg(&args, &config);
            let db = config.db_path;
            tokio::task::spawn_blocking(move || firstpass_proxy::mcp::serve_stdio(&db, &tenant))
                .await??;
            Ok(())
        }
        "--help" | "-h" | "help" => {
            println!("{HELP}");
            Ok(())
        }
        "--version" | "-V" => {
            println!("firstpass {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        other => {
            eprintln!("firstpass: unknown command `{other}`\n\n{HELP}");
            std::process::exit(2);
        }
    }
}

/// `firstpass modes` — print each routing-mode profile: what knobs it sets and its tradeoff.
/// Pure: reads no config and touches no store. Useful as a quick reference before setting
/// FIRSTPASS_MODE_PROFILE, route-level routing_mode, or x-firstpass-mode.
fn cmd_modes() -> Result<(), Box<dyn std::error::Error>> {
    println!(
        "Routing-mode profiles — set via x-firstpass-mode header, \
         route `routing_mode`, or FIRSTPASS_MODE_PROFILE env var.\n"
    );
    for mode in RoutingMode::ALL {
        let p = mode.preset();
        println!("  {:8}  {}", mode.as_str(), p.description);
        println!("           tradeoff: {}", p.tradeoff);
        let mut overrides = Vec::new();
        if let Some(s) = p.speculation {
            overrides.push(format!("speculation={s}"));
        }
        if let Some(d) = p.max_rungs_delta {
            overrides.push(format!("max_rungs+={d}"));
        }
        if p.start_at_top {
            overrides.push("start_at_top=true".to_owned());
        }
        if !overrides.is_empty() {
            println!("           sets:     {}", overrides.join(", "));
        }
        println!();
    }
    Ok(())
}

/// `firstpass doctor` — a config error is itself a finding, so report it and exit non-zero rather
/// than bubbling a raw error.
fn cmd_doctor() -> Result<(), Box<dyn std::error::Error>> {
    match ProxyConfig::from_env() {
        Ok(config) => {
            let report = cli::doctor(&config, |k| std::env::var(k).ok());
            print!("{}", report.render());
            if report.healthy() {
                Ok(())
            } else {
                std::process::exit(1);
            }
        }
        Err(e) => {
            println!("✗ config: {e}\n\nnot healthy — fix the config error above.");
            std::process::exit(1);
        }
    }
}

/// `firstpass upgrade` — the discoverable front door to updating. Only the installer-script
/// channel ships an updater we own, so that one runs in place; every other channel is owned by a
/// package manager and gets its exact command printed rather than mutated behind its back.
fn cmd_upgrade() -> Result<(), Box<dyn std::error::Error>> {
    // Resolve symlinks before matching. `current_exe()` hands back the path the binary was
    // launched through, not the file itself — and pipx (plus uv tool, and Homebrew) put a
    // symlink on PATH pointing into a private directory. Matching the link means seeing
    // `~/.local/bin` and concluding nothing, which is exactly what happened in the field.
    let exe = std::env::current_exe().unwrap_or_default();
    let exe = std::fs::canonicalize(&exe).unwrap_or(exe);
    let in_container = std::path::Path::new("/.dockerenv").exists();
    let path_var = std::env::var("PATH").ok();
    // The updater sits beside the binary the installer placed, or on PATH.
    let updater_present = exe
        .parent()
        .is_some_and(|d| d.join("firstpass-update").is_file())
        || cli::command_on_path("firstpass-update", path_var.as_deref());

    let channel = cli::detect_channel(&exe, updater_present, in_container);
    print!(
        "{}",
        cli::upgrade_report(channel, env!("CARGO_PKG_VERSION"))
    );

    if channel == cli::Channel::Dist {
        let updater = exe
            .parent()
            .map(|d| d.join("firstpass-update"))
            .filter(|p| p.is_file())
            .unwrap_or_else(|| "firstpass-update".into());
        let status = std::process::Command::new(updater).status()?;
        if !status.success() {
            eprintln!("\nupdater exited with {status} — see the output above");
            std::process::exit(status.code().unwrap_or(1));
        }
    }
    Ok(())
}

/// Ask one question and return the chosen variant. Only ever called when stdin is a terminal.
fn ask<T: Copy>(prompt: &str, opts: &[(T, &str, &str)], default_ix: usize) -> T {
    use std::io::Write as _;
    println!("\n{prompt}");
    for (i, (_, id, blurb)) in opts.iter().enumerate() {
        let mark = if i == default_ix { "*" } else { " " };
        println!("  {mark} {}) {id:<9} {blurb}", i + 1);
    }
    print!(
        "  choice [1-{}, enter = {}]: ",
        opts.len(),
        opts[default_ix].1
    );
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    if std::io::stdin().read_line(&mut line).is_err() {
        return opts[default_ix].0;
    }
    let line = line.trim();
    if line.is_empty() {
        return opts[default_ix].0;
    }
    // Accept either the number or the id itself, so an agent piping answers can use words.
    line.parse::<usize>()
        .ok()
        .filter(|n| (1..=opts.len()).contains(n))
        .map_or_else(
            || {
                opts.iter()
                    .find(|(_, id, _)| *id == line)
                    .map_or(opts[default_ix].0, |o| o.0)
            },
            |n| opts[n - 1].0,
        )
}

/// Resolve the three ladder answers: explicit flags win, then an interactive prompt when stdin is
/// a terminal, then the do-nothing defaults. The non-interactive path never blocks — an agent
/// running `onboard --apply` in a pipe must not hang waiting on a question.
fn resolve_choice(
    args: &[String],
    interactive: bool,
) -> (firstpass_proxy::onboard::LadderChoice, bool) {
    use firstpass_core::Mode;
    use firstpass_proxy::onboard::{LadderChoice, Provider, Shape};
    let flag = |name: &str| -> Option<String> {
        args.iter()
            .position(|a| a == name)
            .and_then(|i| args.get(i + 1))
            .cloned()
    };
    let d = LadderChoice::default();
    let provider = flag("--provider")
        .and_then(|v| Provider::ALL.into_iter().find(|p| p.id() == v))
        .unwrap_or(d.provider);
    let shape = flag("--shape")
        .and_then(|v| Shape::ALL.into_iter().find(|s| s.id() == v))
        .unwrap_or(d.shape);
    let mode = match flag("--mode").as_deref() {
        Some("enforce") => Mode::Enforce,
        Some("observe") => Mode::Observe,
        _ => d.mode,
    };
    let all_given =
        flag("--provider").is_some() && flag("--shape").is_some() && flag("--mode").is_some();
    if !interactive || all_given || args.iter().any(|a| a == "--yes" || a == "-y") {
        return (
            LadderChoice {
                provider,
                shape,
                mode,
            },
            false,
        );
    }
    println!("\nThree questions and onboarding writes your firstpass.toml.");
    let provider = ask(
        "1/3 · Which provider should the ladder open on?",
        &Provider::ALL.map(|p| (p, p.id(), p.blurb())),
        0,
    );
    let shape = ask(
        "2/3 · What do these requests produce? (this picks the gate)",
        &Shape::ALL.map(|s| (s, s.id(), s.blurb())),
        0,
    );
    let mode = ask(
        "3/3 · Start in which mode?",
        &[
            (
                Mode::Observe,
                "observe",
                "forward unchanged, just collect receipts (recommended)",
            ),
            (
                Mode::Enforce,
                "enforce",
                "serve from the cheap rung once a gate passes",
            ),
        ],
        0,
    );
    (
        LadderChoice {
            provider,
            shape,
            mode,
        },
        true,
    )
}

/// `firstpass onboard [--apply]` — agentic setup: detect the environment, ask the three questions
/// that decide a starting ladder, plan the exact steps, execute them under `--apply` (dry run
/// otherwise), and verify end-to-end.
fn cmd_onboard(apply: bool) -> Result<(), Box<dyn std::error::Error>> {
    use firstpass_proxy::onboard;
    let env = onboard::detect(
        |k| std::env::var(k).ok(),
        |bin| {
            std::env::var("PATH")
                .is_ok_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
        },
        || {
            let bind = std::env::var("FIRSTPASS_BIND").unwrap_or_else(|_| "127.0.0.1:8080".into());
            std::net::TcpStream::connect_timeout(
                &bind
                    .parse()
                    .unwrap_or_else(|_| ([127, 0, 0, 1], 8080).into()),
                std::time::Duration::from_millis(400),
            )
            .is_ok()
        },
    );
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()));
    let (rc, _) = onboard::shell_wiring(&env.shell, &home, &env.bind);

    // Config generation. Skipped entirely with --no-config, and never when a firstpass.toml is
    // already there — onboarding must be safe to re-run, and clobbering an operator's routing
    // file is the one mistake there is no undo for.
    let args: Vec<String> = std::env::args().collect();
    let cfg_path = std::path::PathBuf::from("firstpass.toml");
    let config = if args.iter().any(|a| a == "--no-config") {
        None
    } else if cfg_path.exists() {
        println!("firstpass.toml already present — leaving it alone (--no-config to silence).\n");
        None
    } else {
        let interactive = std::io::IsTerminal::is_terminal(&std::io::stdin());
        let (choice, asked) = resolve_choice(&args, interactive);
        if !asked {
            println!(
                "config: provider={} shape={} mode={} \
                 (set with --provider/--shape/--mode; asked interactively on a terminal)\n",
                choice.provider.id(),
                choice.shape.id(),
                if choice.mode == firstpass_core::Mode::Enforce {
                    "enforce"
                } else {
                    "observe"
                },
            );
        }
        Some(onboard::ConfigPlan {
            path: cfg_path,
            choice,
        })
    };

    let steps = onboard::plan(&env, &home, onboard::rc_wired(&rc), config.as_ref());
    print!("{}", onboard::render(&env, &steps, apply));
    if apply {
        print!("\n{}", onboard::execute(&env, &steps)?);
    }
    // The code gate ships as a placeholder on purpose (see `Shape::gate_block`), so say plainly
    // that one step remains rather than letting `doctor` be the first to mention it.
    if let Some(c) = &config
        && c.choice.shape == firstpass_proxy::onboard::Shape::Code
    {
        println!(
            "\nnext: the `unit-tests` gate is a placeholder. Point its `cmd` at a wrapper that \
             reads\n      the candidate as JSON on stdin and prints a verdict on stdout, then run \
             `firstpass doctor`."
        );
    }
    Ok(())
}

/// `firstpass offboard` — the mirror: strip the marked rc line(s), stop the proxy onboard started,
/// print the one command for this shell.
fn cmd_offboard() -> Result<(), Box<dyn std::error::Error>> {
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()));
    print!("{}", firstpass_proxy::onboard::offboard(&home)?);
    Ok(())
}

/// The tenant a read-side CLI scopes to: `--tenant <id>` if given, else the configured default
/// (ADR 0004 §D3). Keeps single-operator use zero-config while never silently reading across tenants.
fn tenant_arg(args: &[String], config: &ProxyConfig) -> String {
    args.iter()
        .position(|a| a == "--tenant")
        .and_then(|i| args.get(i + 1))
        .cloned()
        .unwrap_or_else(|| config.tenant_id.clone())
}

/// `firstpass trace [--limit N] [--tenant ID]` — read recent audit records, scoped to one tenant.
fn cmd_trace(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let limit = args
        .iter()
        .position(|a| a == "--limit")
        .and_then(|i| args.get(i + 1))
        .and_then(|n| n.parse::<usize>().ok())
        .unwrap_or(20);
    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);
    let traces = store::load_tenant_traces(std::path::Path::new(&config.db_path), &tenant)
        .unwrap_or_default();
    println!("{}", cli::format_traces(&traces, limit));
    Ok(())
}

/// `firstpass savings [--json] [--tenant ID]` — aggregate spend vs the always-top counterfactual
/// from the trace store: the operator's own measured number, not a marketing claim. Empty or
/// missing store prints the zero state and exits 0, like `trace`.
fn cmd_savings(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);
    let traces = store::load_tenant_traces(std::path::Path::new(&config.db_path), &tenant)
        .unwrap_or_default();
    let summary = cli::summarize_savings(&traces);
    if args.iter().any(|a| a == "--json") {
        println!("{}", serde_json::to_string_pretty(&summary)?);
    } else {
        println!("{}", cli::format_savings(&summary));
    }
    Ok(())
}

/// `firstpass evals [--json] [--tenant ID]` — the live eval suite computed from receipts:
/// per-gate pass/fail/abstain, escalation count, and which rung serves. Empty store → zero
/// state, exit 0, like `savings`.
fn cmd_evals(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);
    let traces = store::load_tenant_traces(std::path::Path::new(&config.db_path), &tenant)
        .unwrap_or_default();
    let summary = cli::summarize_evals(&traces);
    if args.iter().any(|a| a == "--json") {
        println!("{}", serde_json::to_string_pretty(&summary)?);
    } else {
        println!("{}", cli::format_evals(&summary));
    }
    Ok(())
}

/// `firstpass predictor-eval [--json] [--lr L] [--l2 R] [--tenant ID]` — prequential AUC +
/// Brier of the per-query gate-pass predictor over the trace store (predict-before-update on each
/// labeled attempt). The honest check of whether the predictor beats a coin flip before it is ever
/// allowed to influence routing. Empty store → n=0, exit 0.
fn cmd_predictor_eval(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);
    let flag = |name: &str, default: f64| -> f64 {
        args.iter()
            .position(|a| a == name)
            .and_then(|i| args.get(i + 1))
            .and_then(|v| v.parse::<f64>().ok())
            .unwrap_or(default)
    };
    let (lr, l2) = (flag("--lr", 0.05), flag("--l2", 1e-4));
    let traces = store::load_tenant_traces(std::path::Path::new(&config.db_path), &tenant)
        .unwrap_or_default();
    let eval = cli::evaluate_predictor(&traces, lr, l2);
    if args.iter().any(|a| a == "--json") {
        println!("{}", serde_json::to_string_pretty(&eval)?);
    } else {
        let auc = eval
            .auc
            .map_or("n/a (one class)".to_owned(), |a| format!("{a:.3}"));
        println!(
            "predictor-eval: n={} auc={} brier={:.4} (lr={lr} l2={l2})\n  AUC 0.5=no signal, >0.65 usable; Brier 0.25=coin-flip baseline, lower is better",
            eval.n, auc, eval.brier
        );
    }
    Ok(())
}

/// `firstpass explain <trace-id> [--json] [--tenant ID]` — explain a single routing decision
/// from its sealed receipt: served model, per-rung verdicts, escalations, cost vs the always-top
/// baseline, and the savings. Unknown id exits 1.
fn cmd_explain(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let trace_id = args
        .get(2)
        .filter(|a| !a.starts_with("--"))
        .ok_or("usage: firstpass explain <trace-id> [--json]")?;
    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);
    match store::load_trace_view(std::path::Path::new(&config.db_path), &tenant, trace_id)? {
        Some(trace) => {
            let ex = cli::explain_trace(&trace);
            if args.iter().any(|a| a == "--json") {
                println!("{}", serde_json::to_string_pretty(&ex)?);
            } else {
                println!("{}", ex.summary);
                for a in &ex.attempts {
                    let gates: Vec<String> =
                        a.gates.iter().map(|(g, v)| format!("{g}={v}")).collect();
                    println!(
                        "  rung {} {}{} [{}]",
                        a.rung,
                        a.model,
                        a.verdict,
                        gates.join(", ")
                    );
                }
            }
            Ok(())
        }
        None => {
            eprintln!("unknown trace_id {trace_id:?}");
            std::process::exit(1);
        }
    }
}

/// `firstpass export [--out FILE]` — write the operator-wide sealed receipt log as JSONL
/// (one receipt per line, in chain order), to a file or stdout. This is the artifact an
/// operator hands an external auditor; it carries only the hashed bodies, never the deferred
/// verdicts. Empty/missing store writes nothing and exits 0.
fn cmd_export(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let config = ProxyConfig::from_env()?;
    // Operator-wide (the chain spans all tenants — a per-tenant view can't be chain-verified).
    let traces = store::load_all_traces(std::path::Path::new(&config.db_path)).unwrap_or_default();
    let jsonl = cli::export_receipts_jsonl(&traces);
    match args
        .iter()
        .position(|a| a == "--out")
        .and_then(|i| args.get(i + 1))
    {
        Some(path) => {
            std::fs::write(path, jsonl)?;
            eprintln!("exported {} receipts to {path}", traces.len());
        }
        None => print!("{jsonl}"),
    }
    Ok(())
}

/// `firstpass verify [--file FILE] [--json]` — independently re-derive the receipt hash chain
/// from genesis and report whether it is intact. With `--file` it verifies an exported JSONL
/// log (the auditor's path: no proxy, no database, no trust); without it, the local store.
/// **Exits 1 if the chain is broken** so it drops straight into CI / compliance gates.
fn cmd_verify(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let traces = match args
        .iter()
        .position(|a| a == "--file")
        .and_then(|i| args.get(i + 1))
    {
        Some(path) => {
            let text = std::fs::read_to_string(path)?;
            cli::parse_receipt_jsonl(&text).map_err(|e| format!("{path}: {e}"))?
        }
        None => {
            let config = ProxyConfig::from_env()?;
            store::load_all_traces(std::path::Path::new(&config.db_path)).unwrap_or_default()
        }
    };
    let report = cli::verify_receipts(&traces);
    if args.iter().any(|a| a == "--json") {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else if report.valid {
        println!(
            "OK: {} receipts, hash chain intact from genesis",
            report.receipts
        );
    } else {
        println!(
            "TAMPERED: chain broke at receipt {}{}",
            report.broken_at.map_or("?".to_owned(), |i| i.to_string()),
            report.detail.as_deref().unwrap_or("unknown")
        );
    }
    if !report.valid {
        std::process::exit(1);
    }
    Ok(())
}

/// `firstpass calibrate [--alpha A] [--delta D] [--min-n N] [--method conformal|ltt]` —
/// recalibrate the serving threshold from real deferred feedback recorded in the trace store.
/// An empty or not-yet-created store reports 0 pairs (feasible: false) and exits 0, like
/// `trace`; only a genuine store read error exits non-zero.
fn cmd_calibrate(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let flag = |name: &str, default: f64| -> f64 {
        args.iter()
            .position(|a| a == name)
            .and_then(|i| args.get(i + 1))
            .and_then(|v| v.parse::<f64>().ok())
            .unwrap_or(default)
    };
    let alpha = flag("--alpha", 0.1);
    let delta = flag("--delta", 0.05);
    let min_n = flag("--min-n", 30.0) as usize;
    let method = args
        .iter()
        .position(|a| a == "--method")
        .and_then(|i| args.get(i + 1))
        .map(String::as_str)
        .unwrap_or("conformal");

    let config = ProxyConfig::from_env()?;
    let tenant = tenant_arg(args, &config);

    // Infeasible is a valid finding (not enough clean feedback yet, or a weak gate) — the
    // report says `feasible: false`. Only a store read error bubbles up as non-zero exit.
    match method {
        "ltt" => {
            let report = calibrate_from_store_ltt(&config.db_path, &tenant, alpha, delta, min_n)?;
            print!("{}", report.render());
        }
        _ => {
            let report = calibrate_from_store(&config.db_path, &tenant, alpha, delta, min_n)?;
            print!("{}", report.render());
        }
    }
    Ok(())
}

/// `firstpass ope` — off-policy evaluation in two modes:
///
/// - `--config <candidate.toml>`: direct-method replay (ladder / threshold changes).
/// - `--start-rung N`: IPS/SNIPS estimate for a fixed start rung (requires propensity-logged
///   traffic from `[escalation.exploration]`). Mutually exclusive with `--config`.
///
/// Empty/missing store is treated as zero traces and exits 0, matching `calibrate`.
fn cmd_ope(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    // Env config provides defaults for db and tenant; --db / --tenant override them.
    let env_config = ProxyConfig::from_env()?;
    let db_path = args
        .iter()
        .position(|a| a == "--db")
        .and_then(|i| args.get(i + 1))
        .cloned()
        .unwrap_or_else(|| env_config.db_path.clone());
    let tenant = tenant_arg(args, &env_config);

    // --start-rung N: IPS/SNIPS path (takes precedence over --config when both given).
    if let Some(n_str) = args
        .iter()
        .position(|a| a == "--start-rung")
        .and_then(|i| args.get(i + 1))
    {
        let start_rung: u32 = n_str.parse().map_err(|e| {
            format!("firstpass ope: --start-rung must be a non-negative integer: {e}")
        })?;
        let report = ips_from_store(&db_path, &tenant, start_rung)?;
        print!("{}", report.render());
        return Ok(());
    }

    // --config <candidate.toml>: direct-method replay path (required if no --start-rung).
    let config_path = args
        .iter()
        .position(|a| a == "--config")
        .and_then(|i| args.get(i + 1))
        .ok_or_else(|| {
            eprintln!(
                "firstpass ope: one of --config <candidate.toml> or --start-rung N is required"
            );
            std::process::exit(1);
            // Unreachable, but satisfies the type: exit(1) never returns.
            #[allow(unreachable_code)]
            "unreachable"
        })?;

    let toml = std::fs::read_to_string(config_path)
        .map_err(|e| format!("firstpass ope: cannot read --config {config_path:?}: {e}"))?;
    let policy = CandidatePolicy::from_toml(&toml)
        .map_err(|e| format!("firstpass ope: invalid candidate config: {e}"))?;

    let report = ope_from_store(&db_path, &tenant, &policy)?;
    print!("{}", report.render());
    Ok(())
}