Skip to main content

lean_ctx/cli/
eval_cmd.rs

1//! `lean-ctx eval` — deterministic with/without output-quality eval CLI (#238).
2//!
3//! Subcommands:
4//! * `eval init <dir>`     — scaffold a runnable starter suite (one QA + one code task).
5//! * `eval ab --suite P`   — run the A/B comparison and write a signed, reproducible artifact.
6//! * `eval verify <file>`  — verify an artifact's signature + determinism digest offline.
7
8use std::path::{Path, PathBuf};
9
10use crate::core::eval_ab::artifact::{self, SignedAbReportV1};
11use crate::core::eval_ab::conditions::Condition;
12use crate::core::eval_ab::footprint::{
13    Footprint, FootprintConfig, FootprintReport, run_footprint_ab,
14};
15use crate::core::eval_ab::frontier::{self, FrontierReport};
16use crate::core::eval_ab::model::{ModelRunner, OpenAiRunner, RecordedRunner, RecordingRunner};
17use crate::core::eval_ab::report::ReportConfig;
18use crate::core::eval_ab::suite::EvalSuite;
19use crate::core::eval_ab::testbench::lockfile::TestbenchLock;
20use crate::core::eval_ab::testbench::{self, TestbenchConfig, TestbenchReport, findings};
21use crate::core::eval_ab::{AbRunConfig, run_ab};
22
23/// Entry point dispatched from `cli::dispatch`.
24pub fn cmd_eval(args: &[String]) {
25    // `eval --delta [opts]` is sugar for the footprint subcommand.
26    if args.iter().any(|a| a == "--delta") {
27        let rest: Vec<String> = args.iter().filter(|a| *a != "--delta").cloned().collect();
28        return cmd_footprint(&rest);
29    }
30    match args.first().map(String::as_str) {
31        Some("ab") => cmd_ab(&args[1..]),
32        Some("frontier") => cmd_frontier(&args[1..]),
33        Some("footprint" | "delta") => cmd_footprint(&args[1..]),
34        Some("testbench") => cmd_testbench(&args[1..]),
35        Some("verify") => cmd_verify(&args[1..]),
36        Some("init") => cmd_init(&args[1..]),
37        Some("-h" | "--help") | None => print_help(),
38        Some(other) => {
39            eprintln!("eval: unknown subcommand '{other}'\n");
40            print_help();
41            std::process::exit(2);
42        }
43    }
44}
45
46fn print_help() {
47    println!(
48        "lean-ctx eval — deterministic with/without output-quality proof\n\n\
49USAGE:\n\
50  lean-ctx eval init <dir>                 Scaffold a runnable starter suite\n\
51  lean-ctx eval ab --suite <file> [opts]   Run the A/B quality comparison\n\
52  lean-ctx eval footprint --suite <f> [o]  Ablate lean-ctx's OWN injected context (#959)\n\
53  lean-ctx eval testbench --lock <f> [o]   Off-vs-on across pinned real repos (#611)\n\
54  lean-ctx eval verify <artifact.json>     Verify signature + determinism digest\n\n\
55ab OPTIONS:\n\
56  --suite <file>     NDJSON suite (required)\n\
57  --budget <n>       Token budget per condition (default 4000)\n\
58  --margin <f>       Non-inferiority margin for the gate (default 0.0)\n\
59  --out <file>       Artifact path (default: data dir)\n\
60  --replay <file>    Replay a recording instead of calling a live model (deterministic CI)\n\
61  --record <file>    Call the live model and save responses to a recording\n\
62  --gate             Exit non-zero if the verdict is a regression\n\n\
63footprint OPTIONS (also: `eval --delta`):\n\
64  --suite <file>     Footprint-sensitive NDJSON suite (required)\n\
65  --margin <f>       Non-inferiority margin for the per-element gate (default 0.0)\n\
66  --floor <n>        Min marginal tokens before flagging an element to prune (default 50)\n\
67  --replay <file>    Replay a recording (deterministic); --record to capture live\n\
68  --json             Emit the full JSON report instead of the side-by-side table\n\
69  --gate             Exit non-zero if any injected element is actively harmful\n\
70  --export <file>    Write this build's footprint (rules, tool schemas, wakeup) as JSON\n\
71  --compare <file>   Paired run: exported baseline footprint vs. this build's footprint\n\n\
72testbench OPTIONS:\n\
73  --lock <file>      Pinned-repo lockfile (default eval/testbench/testbench.lock.json)\n\
74  --out <dir>        Output dir for FINDINGS.md + regressions.json (default testbench-out)\n\
75  --cache <dir>      Clone cache for remote repos (default <out>/cache)\n\
76  --budget <n>       Token budget per condition (default 4000)\n\
77  --margin <f>       Non-inferiority margin for the per-repo gate (default 0.0)\n\
78  --replay <file>    Replay a recording (deterministic CI); --record to capture live\n\
79  --gate             Exit non-zero if any repo regressed\n\n\
80GATES: --gate fails on REGRESSED and on UNDERPOWERED (too few pairs to show quality).\n\
81  --mechanism        With --gate: wiring check for tiny fixture suites; only REGRESSED fails\n\n\
82LIVE MODEL (when not replaying) is read from the environment:\n\
83  LEAN_CTX_EVAL_MODEL_URL   OpenAI-compatible base URL (e.g. https://api.openai.com/v1)\n\
84  LEAN_CTX_EVAL_MODEL       Model id (e.g. gpt-4o-mini)\n\
85  LEAN_CTX_EVAL_MODEL_KEY   API key (optional for local servers)\n\
86  LEAN_CTX_EVAL_SEED        Decoding seed (default 7)"
87    );
88    println!(
89        "  lean-ctx eval frontier --suite <file> --strategies <csv> [opts]\n\
90frontier strategies: lean_ctx, json_crush, tabular_crush, yaml_crush, read_full, read_map, read_signatures\n\
91frontier options: --limit <n>, --budget <n>, --replay <file>, --record <file>, --json, --gate, --save-evidence"
92    );
93    println!(
94        "Model revision provenance: LEAN_CTX_EVAL_MODEL_VERSION (defaults to a colon-tagged model revision when available)."
95    );
96}
97
98/// Returns the value following `flag` in `args`, if present.
99fn flag_value<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
100    args.iter()
101        .position(|a| a == flag)
102        .and_then(|i| args.get(i + 1))
103        .map(String::as_str)
104}
105
106fn has_flag(args: &[String], flag: &str) -> bool {
107    args.iter().any(|a| a == flag)
108}
109
110fn cmd_ab(args: &[String]) {
111    let Some(suite_path) = flag_value(args, "--suite") else {
112        eprintln!("eval ab: --suite <file> is required");
113        std::process::exit(2);
114    };
115    let suite_path = PathBuf::from(suite_path);
116    let suite = match EvalSuite::load(&suite_path) {
117        Ok(s) => s,
118        Err(e) => {
119            eprintln!("eval ab: {e:#}");
120            std::process::exit(1);
121        }
122    };
123    let suite_name = suite_path
124        .file_name()
125        .map_or_else(|| "suite".to_string(), |s| s.to_string_lossy().into_owned());
126
127    let mut cfg = AbRunConfig::default();
128    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
129        cfg.budget_tokens = b;
130    }
131    cfg.report = ReportConfig {
132        noninferiority_margin: flag_value(args, "--margin")
133            .and_then(|v| v.parse().ok())
134            .unwrap_or(0.0),
135        ..ReportConfig::default()
136    };
137
138    // Runner selection: replay (deterministic) > live + record > live.
139    let report = if let Some(replay) = flag_value(args, "--replay") {
140        let runner = match RecordedRunner::from_file(Path::new(replay)) {
141            Ok(r) => r,
142            Err(e) => {
143                eprintln!("eval ab: {e:#}");
144                std::process::exit(1);
145            }
146        };
147        run_or_exit(&suite, &suite_name, &runner, &cfg)
148    } else {
149        let live = match OpenAiRunner::from_env() {
150            Ok(r) => r,
151            Err(e) => {
152                eprintln!(
153                    "eval ab: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
154                );
155                std::process::exit(1);
156            }
157        };
158        cfg.report.live_model = true;
159        if let Some(record_path) = flag_value(args, "--record") {
160            let recorder = RecordingRunner::new(live);
161            let report = run_or_exit(&suite, &suite_name, &recorder, &cfg);
162            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
163                eprintln!("eval ab: failed to save recording: {e:#}");
164                std::process::exit(1);
165            }
166            println!("Recording saved → {record_path}");
167            report
168        } else {
169            run_or_exit(&suite, &suite_name, &live, &cfg)
170        }
171    };
172
173    // Sign + persist the artifact.
174    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
175    let mut signed = SignedAbReportV1::from_report(report, &agent_id);
176    if let Err(e) = signed.sign(&agent_id) {
177        eprintln!("eval ab: signing failed: {e}");
178        std::process::exit(1);
179    }
180    let out = match flag_value(args, "--out") {
181        Some(p) => PathBuf::from(p),
182        None => match artifact::default_artifact_path() {
183            Ok(p) => p,
184            Err(e) => {
185                eprintln!("eval ab: {e}");
186                std::process::exit(1);
187            }
188        },
189    };
190    if let Err(e) = artifact::write_artifact(&signed, &out) {
191        eprintln!("eval ab: {e}");
192        std::process::exit(1);
193    }
194
195    println!("{}", signed.report.render());
196    println!("determinism digest: {}", signed.determinism_digest);
197    println!("artifact:           {}", out.display());
198
199    if has_flag(args, "--gate") && !signed.verdict.passes_gate(has_flag(args, "--mechanism")) {
200        eprintln!("\nquality gate FAILED: {}", signed.verdict.label());
201        std::process::exit(1);
202    }
203}
204
205fn cmd_frontier(args: &[String]) {
206    let Some(suite_path) = flag_value(args, "--suite") else {
207        eprintln!("eval frontier: --suite <file> is required");
208        std::process::exit(2);
209    };
210    let Some(strategy_names) = flag_value(args, "--strategies") else {
211        eprintln!("eval frontier: --strategies <csv> is required");
212        std::process::exit(2);
213    };
214    let strategies = match frontier::parse_strategies(strategy_names) {
215        Ok(strategies) => strategies,
216        Err(error) => {
217            eprintln!("eval frontier: {error:#}");
218            std::process::exit(2);
219        }
220    };
221
222    let suite_path = PathBuf::from(suite_path);
223    let mut suite = match EvalSuite::load(&suite_path) {
224        Ok(suite) => suite,
225        Err(error) => {
226            eprintln!("eval frontier: {error:#}");
227            std::process::exit(1);
228        }
229    };
230    if let Some(limit) = flag_value(args, "--limit") {
231        let Ok(limit) = limit.parse::<usize>() else {
232            eprintln!("eval frontier: --limit must be a positive integer");
233            std::process::exit(2);
234        };
235        if limit == 0 {
236            eprintln!("eval frontier: --limit must be a positive integer");
237            std::process::exit(2);
238        }
239        suite.tasks.truncate(limit);
240    }
241    let suite_name = suite_path.file_name().map_or_else(
242        || "suite".to_string(),
243        |name| name.to_string_lossy().into_owned(),
244    );
245
246    let mut cfg = AbRunConfig::default();
247    if let Some(budget) = flag_value(args, "--budget").and_then(|value| value.parse().ok()) {
248        cfg.budget_tokens = budget;
249    }
250    cfg.report = ReportConfig {
251        noninferiority_margin: flag_value(args, "--margin")
252            .and_then(|value| value.parse().ok())
253            .unwrap_or(0.0),
254        ..ReportConfig::default()
255    };
256
257    let report = if let Some(replay) = flag_value(args, "--replay") {
258        let runner = match RecordedRunner::from_file(Path::new(replay)) {
259            Ok(runner) => runner,
260            Err(error) => {
261                eprintln!("eval frontier: {error:#}");
262                std::process::exit(1);
263            }
264        };
265        run_frontier_or_exit(&suite, &suite_name, &runner, &cfg, &strategies)
266    } else {
267        let live = match OpenAiRunner::from_env() {
268            Ok(runner) => runner,
269            Err(error) => {
270                eprintln!(
271                    "eval frontier: no live model configured: {error:#}\n(use --replay <file> for an offline run)"
272                );
273                std::process::exit(1);
274            }
275        };
276        cfg.report.live_model = true;
277        if let Some(record_path) = flag_value(args, "--record") {
278            let recorder = RecordingRunner::new(live);
279            let report = run_frontier_or_exit(&suite, &suite_name, &recorder, &cfg, &strategies);
280            if let Err(error) = recorder.into_recording().save(Path::new(record_path)) {
281                eprintln!("eval frontier: failed to save recording: {error:#}");
282                std::process::exit(1);
283            }
284            eprintln!("Recording saved → {record_path}");
285            report
286        } else {
287            run_frontier_or_exit(&suite, &suite_name, &live, &cfg, &strategies)
288        }
289    };
290
291    if has_flag(args, "--json") {
292        println!("{}", report.to_json());
293    } else {
294        print!("{}", report.render_table());
295    }
296    if has_flag(args, "--save-evidence") {
297        match crate::core::eval_ab::strategy_evaluations::save(&report) {
298            Ok(0) => eprintln!(
299                "No read-strategy evaluation to save (use read_full, read_map, read_signatures)."
300            ),
301            Ok(saved) => {
302                eprintln!("Saved {saved} read-strategy evaluation(s) as context-policy evidence.");
303            }
304            Err(error) => {
305                eprintln!("eval frontier: failed to save evidence: {error}");
306                std::process::exit(1);
307            }
308        }
309    }
310    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
311        eprintln!("\nquality gate FAILED: one or more frontier strategies regressed");
312        std::process::exit(1);
313    }
314}
315
316fn run_frontier_or_exit(
317    suite: &EvalSuite,
318    suite_name: &str,
319    runner: &dyn ModelRunner,
320    cfg: &AbRunConfig,
321    strategies: &[Condition],
322) -> FrontierReport {
323    match frontier::run_frontier(suite, suite_name, runner, cfg, strategies) {
324        Ok(report) => report,
325        Err(error) => {
326            eprintln!("eval frontier: run failed: {error:#}");
327            std::process::exit(1);
328        }
329    }
330}
331
332fn run_or_exit(
333    suite: &EvalSuite,
334    suite_name: &str,
335    runner: &dyn crate::core::eval_ab::model::ModelRunner,
336    cfg: &AbRunConfig,
337) -> crate::core::eval_ab::report::AbReport {
338    match run_ab(suite, suite_name, runner, cfg) {
339        Ok(r) => r,
340        Err(e) => {
341            eprintln!("eval ab: run failed: {e:#}");
342            std::process::exit(1);
343        }
344    }
345}
346
347/// `eval footprint` (alias `eval --delta`): ablate each element of lean-ctx's own
348/// injected context (rules / tool schemas / wakeup) and report per-element
349/// pass-rate Δ + token Δ with a prune recommendation (#959).
350/// `eval footprint --compare <baseline.json>`: the exported footprint of another
351/// build against this build's live footprint, paired on the same tasks.
352fn cmd_footprint_compare(
353    args: &[String],
354    suite: &EvalSuite,
355    suite_name: &str,
356    baseline_path: &str,
357    candidate: &Footprint,
358    mut report_cfg: ReportConfig,
359) {
360    let baseline: Footprint = match std::fs::read_to_string(baseline_path)
361        .map_err(|e| e.to_string())
362        .and_then(|raw| serde_json::from_str(&raw).map_err(|e| e.to_string()))
363    {
364        Ok(fp) => fp,
365        Err(e) => {
366            eprintln!("eval footprint: cannot load baseline footprint {baseline_path}: {e}");
367            std::process::exit(1);
368        }
369    };
370    let run = |runner: &dyn crate::core::eval_ab::model::ModelRunner, cfg: ReportConfig| {
371        match crate::core::eval_ab::footprint::run_footprint_compare(
372            suite, suite_name, &baseline, candidate, runner, cfg,
373        ) {
374            Ok(report) => report,
375            Err(e) => {
376                eprintln!("eval footprint: {e:#}");
377                std::process::exit(1);
378            }
379        }
380    };
381    let report = if let Some(replay) = flag_value(args, "--replay") {
382        match RecordedRunner::from_file(Path::new(replay)) {
383            Ok(runner) => run(&runner, report_cfg),
384            Err(e) => {
385                eprintln!("eval footprint: {e:#}");
386                std::process::exit(1);
387            }
388        }
389    } else {
390        let live = match OpenAiRunner::from_env() {
391            Ok(r) => r,
392            Err(e) => {
393                eprintln!(
394                    "eval footprint: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
395                );
396                std::process::exit(1);
397            }
398        };
399        report_cfg.live_model = true;
400        if let Some(record_path) = flag_value(args, "--record") {
401            let recorder = RecordingRunner::new(live);
402            let report = run(&recorder, report_cfg);
403            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
404                eprintln!("eval footprint: failed to save recording: {e:#}");
405                std::process::exit(1);
406            }
407            println!("Recording saved → {record_path}");
408            report
409        } else {
410            run(&live, report_cfg)
411        }
412    };
413    let saved = report
414        .records
415        .first()
416        .map_or(0, |r| r.baseline_tokens as i64 - r.lean_ctx_tokens as i64);
417    println!("Footprint compare: baseline {baseline_path} vs. this build");
418    println!(
419        "Fixed footprint delta: {saved:+} tokens per request (positive = candidate smaller)\n"
420    );
421    println!("{}", report.render());
422    if has_flag(args, "--gate") && !report.verdict.passes_gate(has_flag(args, "--mechanism")) {
423        eprintln!(
424            "\nfootprint compare gate FAILED: {}",
425            report.verdict.label()
426        );
427        std::process::exit(1);
428    }
429}
430
431fn cmd_footprint(args: &[String]) {
432    let Some(suite_path) = flag_value(args, "--suite") else {
433        eprintln!("eval footprint: --suite <file> is required");
434        std::process::exit(2);
435    };
436    let suite_path = PathBuf::from(suite_path);
437    let suite = match EvalSuite::load(&suite_path) {
438        Ok(s) => s,
439        Err(e) => {
440            eprintln!("eval footprint: {e:#}");
441            std::process::exit(1);
442        }
443    };
444    let suite_name = suite_path.file_name().map_or_else(
445        || "footprint".to_string(),
446        |s| s.to_string_lossy().into_owned(),
447    );
448
449    let margin = flag_value(args, "--margin")
450        .and_then(|v| v.parse().ok())
451        .unwrap_or(0.0);
452    let token_floor = flag_value(args, "--floor")
453        .and_then(|v| v.parse().ok())
454        .unwrap_or_else(|| FootprintConfig::default().token_floor);
455    let mut cfg = FootprintConfig {
456        report: ReportConfig {
457            noninferiority_margin: margin,
458            ..ReportConfig::default()
459        },
460        token_floor,
461    };
462
463    // The footprint under test is what this install actually injects.
464    let project_root = std::env::current_dir()
465        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().into_owned());
466    let footprint = Footprint::live(&project_root);
467
468    if let Some(path) = flag_value(args, "--export") {
469        let json = serde_json::to_string_pretty(&footprint).unwrap_or_default();
470        if let Err(e) = std::fs::write(path, json) {
471            eprintln!("eval footprint: cannot write {path}: {e}");
472            std::process::exit(1);
473        }
474        println!("Footprint exported → {path}");
475        return;
476    }
477    if let Some(path) = flag_value(args, "--compare") {
478        cmd_footprint_compare(args, &suite, &suite_name, path, &footprint, cfg.report);
479        return;
480    }
481
482    let mut report = if let Some(replay) = flag_value(args, "--replay") {
483        let runner = match RecordedRunner::from_file(Path::new(replay)) {
484            Ok(r) => r,
485            Err(e) => {
486                eprintln!("eval footprint: {e:#}");
487                std::process::exit(1);
488            }
489        };
490        run_footprint_or_exit(&suite, &suite_name, &footprint, &runner, &cfg)
491    } else {
492        let live = match OpenAiRunner::from_env() {
493            Ok(r) => r,
494            Err(e) => {
495                eprintln!(
496                    "eval footprint: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
497                );
498                std::process::exit(1);
499            }
500        };
501        cfg.report.live_model = true;
502        if let Some(record_path) = flag_value(args, "--record") {
503            let recorder = RecordingRunner::new(live);
504            let report = run_footprint_or_exit(&suite, &suite_name, &footprint, &recorder, &cfg);
505            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
506                eprintln!("eval footprint: failed to save recording: {e:#}");
507                std::process::exit(1);
508            }
509            println!("Recording saved → {record_path}");
510            report
511        } else {
512            run_footprint_or_exit(&suite, &suite_name, &footprint, &live, &cfg)
513        }
514    };
515
516    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
517    if let Err(e) = report.sign(&agent_id) {
518        eprintln!("eval footprint: signing failed: {e}");
519        std::process::exit(1);
520    }
521
522    let out = match flag_value(args, "--out") {
523        Some(p) => PathBuf::from(p),
524        None => match default_footprint_path() {
525            Ok(p) => p,
526            Err(e) => {
527                eprintln!("eval footprint: {e}");
528                std::process::exit(1);
529            }
530        },
531    };
532    if let Some(parent) = out.parent() {
533        let _ = std::fs::create_dir_all(parent);
534    }
535    if let Err(e) = std::fs::write(&out, report.to_json()) {
536        eprintln!("eval footprint: write {}: {e}", out.display());
537        std::process::exit(1);
538    }
539
540    if has_flag(args, "--json") {
541        println!("{}", report.to_json());
542    } else {
543        println!("{}", report.render());
544        println!("artifact:           {}", out.display());
545    }
546
547    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
548        eprintln!("\nfootprint gate FAILED: a harmful injected element is present");
549        std::process::exit(1);
550    }
551}
552
553fn run_footprint_or_exit(
554    suite: &EvalSuite,
555    suite_name: &str,
556    footprint: &Footprint,
557    runner: &dyn ModelRunner,
558    cfg: &FootprintConfig,
559) -> FootprintReport {
560    match run_footprint_ab(suite, suite_name, footprint, runner, cfg) {
561        Ok(r) => r,
562        Err(e) => {
563            eprintln!("eval footprint: run failed: {e:#}");
564            std::process::exit(1);
565        }
566    }
567}
568
569/// Default footprint artifact location: `<data_dir>/eval/footprint-report-v1_<utc>.json`.
570fn default_footprint_path() -> Result<PathBuf, String> {
571    let dir = crate::core::data_dir::lean_ctx_data_dir()?.join("eval");
572    std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir eval: {e}"))?;
573    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
574    Ok(dir.join(format!("footprint-report-v1_{stamp}.json")))
575}
576
577/// `eval testbench`: run the off-vs-on answer-quality benchmark across every pinned
578/// repo in a lockfile, write `FINDINGS.md` + `regressions.json`, and (with `--gate`)
579/// fail the build if any repo regressed (#611).
580fn cmd_testbench(args: &[String]) {
581    let lock_path = flag_value(args, "--lock").map_or_else(
582        || PathBuf::from("eval/testbench/testbench.lock.json"),
583        PathBuf::from,
584    );
585    let lock = match TestbenchLock::load(&lock_path) {
586        Ok(l) => l,
587        Err(e) => {
588            eprintln!("eval testbench: {e:#}\n(use --lock <file> to point at a lockfile)");
589            std::process::exit(1);
590        }
591    };
592
593    let out_dir =
594        flag_value(args, "--out").map_or_else(|| PathBuf::from("testbench-out"), PathBuf::from);
595    let cache_dir =
596        flag_value(args, "--cache").map_or_else(|| out_dir.join("cache"), PathBuf::from);
597
598    let mut cfg = TestbenchConfig::default();
599    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
600        cfg.run.budget_tokens = b;
601    }
602    cfg.run.report = ReportConfig {
603        noninferiority_margin: flag_value(args, "--margin")
604            .and_then(|v| v.parse().ok())
605            .unwrap_or(0.0),
606        ..ReportConfig::default()
607    };
608
609    let report = if let Some(replay) = flag_value(args, "--replay") {
610        let runner = match RecordedRunner::from_file(Path::new(replay)) {
611            Ok(r) => r,
612            Err(e) => {
613                eprintln!("eval testbench: {e:#}");
614                std::process::exit(1);
615            }
616        };
617        run_testbench_or_exit(&lock, &cache_dir, &runner, &cfg)
618    } else {
619        let live = match OpenAiRunner::from_env() {
620            Ok(r) => r,
621            Err(e) => {
622                eprintln!(
623                    "eval testbench: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
624                );
625                std::process::exit(1);
626            }
627        };
628        cfg.run.report.live_model = true;
629        if let Some(record_path) = flag_value(args, "--record") {
630            let recorder = RecordingRunner::new(live);
631            let report = run_testbench_or_exit(&lock, &cache_dir, &recorder, &cfg);
632            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
633                eprintln!("eval testbench: failed to save recording: {e:#}");
634                std::process::exit(1);
635            }
636            println!("Recording saved → {record_path}");
637            report
638        } else {
639            run_testbench_or_exit(&lock, &cache_dir, &live, &cfg)
640        }
641    };
642
643    let (findings_path, regressions_path) = match findings::write(&report, &out_dir) {
644        Ok(paths) => paths,
645        Err(e) => {
646            eprintln!("eval testbench: {e:#}");
647            std::process::exit(1);
648        }
649    };
650
651    print!("{}", findings::render_findings(&report));
652    println!("\nFINDINGS:     {}", findings_path.display());
653    println!("regressions:  {}", regressions_path.display());
654
655    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
656        eprintln!("\ntestbench gate FAILED: {}", report.verdict.label());
657        std::process::exit(1);
658    }
659}
660
661fn run_testbench_or_exit(
662    lock: &TestbenchLock,
663    cache_dir: &Path,
664    runner: &dyn ModelRunner,
665    cfg: &TestbenchConfig,
666) -> TestbenchReport {
667    match testbench::run_testbench(lock, cache_dir, runner, cfg) {
668        Ok(r) => r,
669        Err(e) => {
670            eprintln!("eval testbench: run failed: {e:#}");
671            std::process::exit(1);
672        }
673    }
674}
675
676fn cmd_verify(args: &[String]) {
677    let Some(path) = args.first() else {
678        eprintln!("eval verify: <artifact.json> is required");
679        std::process::exit(2);
680    };
681    let artifact = match artifact::load_artifact(Path::new(path)) {
682        Ok(a) => a,
683        Err(e) => {
684            eprintln!("eval verify: {e}");
685            std::process::exit(1);
686        }
687    };
688    let result = artifact.verify();
689    println!("Artifact:           {path}");
690    println!("Verdict:            {}", artifact.verdict.label());
691    println!(
692        "Evidence tier:      {}",
693        artifact.report.evidence_tier.map_or_else(
694            || "UNSPECIFIED (v1 report)".to_string(),
695            |t| format!("{} ({})", t.code(), t.label())
696        )
697    );
698    println!(
699        "Quality claim:      {}",
700        if artifact.report.supports_quality_claim() {
701            "supported (powered, model-backed)"
702        } else {
703            "none"
704        }
705    );
706    println!("Determinism digest: {}", artifact.determinism_digest);
707    println!(
708        "Digest matches:     {}",
709        if result.digest_matches { "yes" } else { "NO" }
710    );
711    println!(
712        "Signature valid:    {}",
713        if result.signature_valid { "yes" } else { "NO" }
714    );
715    if let Some(pk) = &result.signer_public_key {
716        println!("Signer public key:  {pk}");
717    }
718    if let Some(err) = &result.error {
719        println!("Error:              {err}");
720    }
721    if result.ok() {
722        println!("\nOK — artifact is authentic and internally consistent.");
723    } else {
724        eprintln!("\nFAILED — artifact could not be verified.");
725        std::process::exit(1);
726    }
727}
728
729fn cmd_init(args: &[String]) {
730    let dir = PathBuf::from(args.first().map_or("eval-suite", |s| s.as_str()));
731    match write_starter_suite(&dir) {
732        Ok(suite) => {
733            println!("Starter suite written to {}", dir.display());
734            println!("Suite file: {}", suite.display());
735            println!("\nNext:");
736            println!("  # 1) record real model answers once (needs a live model in env)");
737            println!(
738                "  lean-ctx eval ab --suite {} --record {}/recording.json",
739                suite.display(),
740                dir.display()
741            );
742            println!("  # 2) replay deterministically anywhere (CI)");
743            println!(
744                "  lean-ctx eval ab --suite {} --replay {}/recording.json --gate",
745                suite.display(),
746                dir.display()
747            );
748        }
749        Err(e) => {
750            eprintln!("eval init: {e:#}");
751            std::process::exit(1);
752        }
753    }
754}
755
756/// Materializes a small, runnable starter suite: one RAG/QA task whose answer lives in the
757/// corpus, and one POSIX-shell code task with a failing stub + unit test.
758fn write_starter_suite(dir: &Path) -> anyhow::Result<PathBuf> {
759    use anyhow::Context;
760    let corpus = dir.join("corpus");
761    let code = dir.join("code");
762    std::fs::create_dir_all(&corpus).context("creating corpus dir")?;
763    std::fs::create_dir_all(&code).context("creating code dir")?;
764
765    std::fs::write(
766        corpus.join("architecture.md"),
767        "# Consolidation pipeline\n\n\
768Provider data flows through one consolidation pipeline. Artifacts are persisted to four \
769stores: the BM25 index, the Graph index, ProjectKnowledge, and the Session cache. This is \
770what lets semantic search, knowledge recall, and cross-source hints share one source of truth.\n",
771    )
772    .context("writing corpus/architecture.md")?;
773    std::fs::write(
774        corpus.join("overview.md"),
775        "# Overview\n\nlean-ctx is a context runtime for AI agents. This file is general \
776background and intentionally does not list the consolidation stores.\n",
777    )
778    .context("writing corpus/overview.md")?;
779
780    std::fs::write(
781        code.join("test.sh"),
782        "#!/bin/sh\n. ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ] || exit 1\n[ \"$(add 10 20)\" = \"30\" ] || exit 1\n",
783    )
784    .context("writing code/test.sh")?;
785    std::fs::write(
786        code.join("solution.sh"),
787        "# TODO: implement add() so that `add a b` prints a+b\nadd() { echo 0; }\n",
788    )
789    .context("writing code/solution.sh")?;
790
791    let suite = dir.join("suite.ndjson");
792    let lines = [
793        r#"{"id":"qa-consolidation-stores","domain":"qa","prompt":"Which four stores does the consolidation pipeline persist artifacts to?","workspace":"corpus","answers":["bm25 index, graph index, projectknowledge, session cache","bm25, graph, knowledge, session"]}"#,
794        r#"{"id":"code-add","domain":"code","prompt":"Implement the POSIX shell function add in solution.sh so that `add a b` prints the sum a+b. Output only the file contents.","workspace":"code","target_file":"solution.sh","test_cmd":"sh test.sh"}"#,
795    ];
796    std::fs::write(
797        &suite,
798        format!("# lean-ctx eval starter suite\n{}\n", lines.join("\n")),
799    )
800    .context("writing suite.ndjson")?;
801    Ok(suite)
802}
803
804#[cfg(test)]
805mod recording_guard_tests {
806    use super::*;
807
808    /// The committed recording (`rust/eval/recording.json`) is what flips the CI
809    /// quality-gate from "skipped" to "enforced" (#361 Phase 3). Guard it
810    /// **in-process** so a suite/corpus/prompt change that invalidates the
811    /// recording (a replay key miss) or a captured regression fails here in
812    /// `cargo test` — i.e. during `dev-install` — not only in CI.
813    #[test]
814    fn committed_recording_replays_and_passes_gate() {
815        let dir = tempfile::tempdir().unwrap();
816        let suite_path = write_starter_suite(dir.path()).expect("scaffold starter suite");
817        let suite = EvalSuite::load(&suite_path).expect("load starter suite");
818
819        let rec_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("eval/recording.json");
820        assert!(
821            rec_path.exists(),
822            "committed recording missing at {} — CI quality-gate would silently skip",
823            rec_path.display()
824        );
825        let runner = RecordedRunner::from_file(&rec_path).expect("load committed recording");
826
827        // Every (task × condition) request must hit a recorded key, else the
828        // recording drifted from the suite/corpus/prompt and must be re-captured.
829        let report = run_ab(&suite, "suite.ndjson", &runner, &AbRunConfig::default())
830            .expect("committed recording must cover every replay key");
831        assert!(
832            report.verdict.mechanism_gate_passes(),
833            "committed recording must not encode a regression, got: {}",
834            report.verdict.label()
835        );
836    }
837}