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::footprint::{
12    Footprint, FootprintConfig, FootprintReport, run_footprint_ab,
13};
14use crate::core::eval_ab::model::{ModelRunner, OpenAiRunner, RecordedRunner, RecordingRunner};
15use crate::core::eval_ab::report::ReportConfig;
16use crate::core::eval_ab::suite::EvalSuite;
17use crate::core::eval_ab::testbench::lockfile::TestbenchLock;
18use crate::core::eval_ab::testbench::{self, TestbenchConfig, TestbenchReport, findings};
19use crate::core::eval_ab::{AbRunConfig, run_ab};
20use crate::core::ocla::registry::OclaRegistry;
21use crate::core::ocla::types::{ExperimentRequest, OclaRequestContext};
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("footprint" | "delta") => cmd_footprint(&args[1..]),
33        Some("routing") => cmd_routing(&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 routing --suite <f> [o]    Router off-vs-on rate-card savings proof\n\
54  lean-ctx eval testbench --lock <f> [o]   Off-vs-on across pinned real repos (#611)\n\
55  lean-ctx eval verify <artifact.json>     Verify signature + determinism digest\n\n\
56ab OPTIONS:\n\
57  --suite <file>     NDJSON suite (required)\n\
58  --budget <n>       Token budget per condition (default 4000)\n\
59  --margin <f>       Non-inferiority margin for the gate (default 0.0)\n\
60  --out <file>       Artifact path (default: data dir)\n\
61  --replay <file>    Replay a recording instead of calling a live model (deterministic CI)\n\
62  --record <file>    Call the live model and save responses to a recording\n\
63  --gate             Exit non-zero if the verdict is a regression\n\n\
64footprint OPTIONS (also: `eval --delta`):\n\
65  --suite <file>     Footprint-sensitive NDJSON suite (required)\n\
66  --margin <f>       Non-inferiority margin for the per-element gate (default 0.0)\n\
67  --floor <n>        Min marginal tokens before flagging an element to prune (default 50)\n\
68  --replay <file>    Replay a recording (deterministic); --record to capture live\n\
69  --json             Emit the full JSON report instead of the side-by-side table\n\
70  --gate             Exit non-zero if any injected element is actively harmful\n\n\
71routing OPTIONS:\n\
72  --suite <file>     NDJSON suite of real task prompts (required)\n\
73  --requested <m>    Model the off-arm assumes (default: [proxy.baseline].reference_model)\n\
74  --json             Emit the full JSON report instead of the table\n\
75  --gate             Exit non-zero if routing downgraded premium work\n\
76  Rules come from [proxy.routing] in config.toml — the deployment's live rule set.\n\n\
77testbench OPTIONS:\n\
78  --lock <file>      Pinned-repo lockfile (default eval/testbench/testbench.lock.json)\n\
79  --out <dir>        Output dir for FINDINGS.md + regressions.json (default testbench-out)\n\
80  --cache <dir>      Clone cache for remote repos (default <out>/cache)\n\
81  --budget <n>       Token budget per condition (default 4000)\n\
82  --margin <f>       Non-inferiority margin for the per-repo gate (default 0.0)\n\
83  --replay <file>    Replay a recording (deterministic CI); --record to capture live\n\
84  --gate             Exit non-zero if any repo regressed\n\n\
85LIVE MODEL (when not replaying) is read from the environment:\n\
86  LEAN_CTX_EVAL_MODEL_URL   OpenAI-compatible base URL (e.g. https://api.openai.com/v1)\n\
87  LEAN_CTX_EVAL_MODEL       Model id (e.g. gpt-4o-mini)\n\
88  LEAN_CTX_EVAL_MODEL_KEY   API key (optional for local servers)\n\
89  LEAN_CTX_EVAL_SEED        Decoding seed (default 7)"
90    );
91}
92
93/// Returns the value following `flag` in `args`, if present.
94fn flag_value<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
95    args.iter()
96        .position(|a| a == flag)
97        .and_then(|i| args.get(i + 1))
98        .map(String::as_str)
99}
100
101fn has_flag(args: &[String], flag: &str) -> bool {
102    args.iter().any(|a| a == flag)
103}
104
105fn cmd_ab(args: &[String]) {
106    let Some(suite_path) = flag_value(args, "--suite") else {
107        eprintln!("eval ab: --suite <file> is required");
108        std::process::exit(2);
109    };
110    let suite_path = PathBuf::from(suite_path);
111    let suite = match EvalSuite::load(&suite_path) {
112        Ok(s) => s,
113        Err(e) => {
114            eprintln!("eval ab: {e:#}");
115            std::process::exit(1);
116        }
117    };
118    let suite_name = suite_path
119        .file_name()
120        .map_or_else(|| "suite".to_string(), |s| s.to_string_lossy().into_owned());
121
122    let mut cfg = AbRunConfig::default();
123    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
124        cfg.budget_tokens = b;
125    }
126    cfg.report = ReportConfig {
127        noninferiority_margin: flag_value(args, "--margin")
128            .and_then(|v| v.parse().ok())
129            .unwrap_or(0.0),
130        ..ReportConfig::default()
131    };
132
133    // Runner selection: replay (deterministic) > live + record > live.
134    let report = if let Some(replay) = flag_value(args, "--replay") {
135        let runner = match RecordedRunner::from_file(Path::new(replay)) {
136            Ok(r) => r,
137            Err(e) => {
138                eprintln!("eval ab: {e:#}");
139                std::process::exit(1);
140            }
141        };
142        run_or_exit(&suite, &suite_name, &runner, &cfg)
143    } else {
144        let live = match OpenAiRunner::from_env() {
145            Ok(r) => r,
146            Err(e) => {
147                eprintln!(
148                    "eval ab: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
149                );
150                std::process::exit(1);
151            }
152        };
153        if let Some(record_path) = flag_value(args, "--record") {
154            let recorder = RecordingRunner::new(live);
155            let report = run_or_exit(&suite, &suite_name, &recorder, &cfg);
156            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
157                eprintln!("eval ab: failed to save recording: {e:#}");
158                std::process::exit(1);
159            }
160            println!("Recording saved → {record_path}");
161            report
162        } else {
163            run_or_exit(&suite, &suite_name, &live, &cfg)
164        }
165    };
166
167    // Sign + persist the artifact.
168    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
169    let mut signed = SignedAbReportV1::from_report(report, &agent_id);
170    if let Err(e) = signed.sign(&agent_id) {
171        eprintln!("eval ab: signing failed: {e}");
172        std::process::exit(1);
173    }
174    let out = match flag_value(args, "--out") {
175        Some(p) => PathBuf::from(p),
176        None => match artifact::default_artifact_path() {
177            Ok(p) => p,
178            Err(e) => {
179                eprintln!("eval ab: {e}");
180                std::process::exit(1);
181            }
182        },
183    };
184    if let Err(e) = artifact::write_artifact(&signed, &out) {
185        eprintln!("eval ab: {e}");
186        std::process::exit(1);
187    }
188
189    println!("{}", signed.report.render());
190    println!("determinism digest: {}", signed.determinism_digest);
191    println!("artifact:           {}", out.display());
192
193    if has_flag(args, "--gate") && !signed.verdict.gate_passes() {
194        eprintln!("\nquality gate FAILED: {}", signed.verdict.label());
195        std::process::exit(1);
196    }
197}
198
199fn run_or_exit(
200    suite: &EvalSuite,
201    suite_name: &str,
202    runner: &dyn crate::core::eval_ab::model::ModelRunner,
203    cfg: &AbRunConfig,
204) -> crate::core::eval_ab::report::AbReport {
205    match run_ab(suite, suite_name, runner, cfg) {
206        Ok(r) => r,
207        Err(e) => {
208            eprintln!("eval ab: run failed: {e:#}");
209            std::process::exit(1);
210        }
211    }
212}
213
214/// `eval routing`: off-vs-on rate-card savings proof for the active router
215/// (enterprise#13/#21). Runs the deployment's `[proxy.routing]` rules and the
216/// production intent classifier over a suite's real prompts, priced from the
217/// shared pricing table; gates on "premium is never downgraded".
218fn cmd_routing(args: &[String]) {
219    let Some(suite_path) = flag_value(args, "--suite") else {
220        eprintln!("eval routing: --suite <file> is required");
221        std::process::exit(2);
222    };
223    let suite_path = PathBuf::from(suite_path);
224    if let Err(e) = EvalSuite::load(&suite_path) {
225        eprintln!("eval routing: {e:#}");
226        std::process::exit(1);
227    }
228    let suite_name = suite_path
229        .file_name()
230        .map_or_else(|| "suite".to_string(), |s| s.to_string_lossy().into_owned());
231
232    let request = ExperimentRequest {
233        context: OclaRequestContext {
234            request_id: format!("eval-routing:{suite_name}"),
235            session_id: "cli:eval-routing".into(),
236            agent_id: crate::core::agent_identity::current_agent_id().to_string(),
237            content_ref: suite_path.to_string_lossy().into_owned(),
238            tenant_id: None,
239            trace_id: "tr-unit".into(),
240            task_id: None,
241            parent_task_id: None,
242        },
243        experiment_ref: suite_path.to_string_lossy().into_owned(),
244        cohort_ref: "cohort:routing-eval".into(),
245        holdout: None,
246        stop_conditions: None,
247    };
248    let result = match OclaRegistry::global()
249        .experiment_runner
250        .run_experiment(request)
251    {
252        Ok(result) => result,
253        Err(e) => {
254            eprintln!("eval routing: {e:#}");
255            std::process::exit(1);
256        }
257    };
258
259    if has_flag(args, "--json") {
260        println!(
261            "{}",
262            serde_json::to_string_pretty(&result).expect("experiment result serializes")
263        );
264    } else {
265        println!("routing experiment: {}", result.experiment_ref);
266        println!("outcome ref:         {}", result.outcome_ref);
267        if let Some(rollback_ref) = result.rollback_ref {
268            println!("rollback ref:        {rollback_ref}");
269        }
270    }
271}
272
273/// `eval footprint` (alias `eval --delta`): ablate each element of lean-ctx's own
274/// injected context (rules / tool schemas / wakeup) and report per-element
275/// pass-rate Δ + token Δ with a prune recommendation (#959).
276fn cmd_footprint(args: &[String]) {
277    let Some(suite_path) = flag_value(args, "--suite") else {
278        eprintln!("eval footprint: --suite <file> is required");
279        std::process::exit(2);
280    };
281    let suite_path = PathBuf::from(suite_path);
282    let suite = match EvalSuite::load(&suite_path) {
283        Ok(s) => s,
284        Err(e) => {
285            eprintln!("eval footprint: {e:#}");
286            std::process::exit(1);
287        }
288    };
289    let suite_name = suite_path.file_name().map_or_else(
290        || "footprint".to_string(),
291        |s| s.to_string_lossy().into_owned(),
292    );
293
294    let margin = flag_value(args, "--margin")
295        .and_then(|v| v.parse().ok())
296        .unwrap_or(0.0);
297    let token_floor = flag_value(args, "--floor")
298        .and_then(|v| v.parse().ok())
299        .unwrap_or_else(|| FootprintConfig::default().token_floor);
300    let cfg = FootprintConfig {
301        report: ReportConfig {
302            noninferiority_margin: margin,
303            ..ReportConfig::default()
304        },
305        token_floor,
306    };
307
308    // The footprint under test is what this install actually injects.
309    let project_root = std::env::current_dir()
310        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().into_owned());
311    let footprint = Footprint::live(&project_root);
312
313    let mut report = if let Some(replay) = flag_value(args, "--replay") {
314        let runner = match RecordedRunner::from_file(Path::new(replay)) {
315            Ok(r) => r,
316            Err(e) => {
317                eprintln!("eval footprint: {e:#}");
318                std::process::exit(1);
319            }
320        };
321        run_footprint_or_exit(&suite, &suite_name, &footprint, &runner, &cfg)
322    } else {
323        let live = match OpenAiRunner::from_env() {
324            Ok(r) => r,
325            Err(e) => {
326                eprintln!(
327                    "eval footprint: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
328                );
329                std::process::exit(1);
330            }
331        };
332        if let Some(record_path) = flag_value(args, "--record") {
333            let recorder = RecordingRunner::new(live);
334            let report = run_footprint_or_exit(&suite, &suite_name, &footprint, &recorder, &cfg);
335            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
336                eprintln!("eval footprint: failed to save recording: {e:#}");
337                std::process::exit(1);
338            }
339            println!("Recording saved → {record_path}");
340            report
341        } else {
342            run_footprint_or_exit(&suite, &suite_name, &footprint, &live, &cfg)
343        }
344    };
345
346    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
347    if let Err(e) = report.sign(&agent_id) {
348        eprintln!("eval footprint: signing failed: {e}");
349        std::process::exit(1);
350    }
351
352    let out = match flag_value(args, "--out") {
353        Some(p) => PathBuf::from(p),
354        None => match default_footprint_path() {
355            Ok(p) => p,
356            Err(e) => {
357                eprintln!("eval footprint: {e}");
358                std::process::exit(1);
359            }
360        },
361    };
362    if let Some(parent) = out.parent() {
363        let _ = std::fs::create_dir_all(parent);
364    }
365    if let Err(e) = std::fs::write(&out, report.to_json()) {
366        eprintln!("eval footprint: write {}: {e}", out.display());
367        std::process::exit(1);
368    }
369
370    if has_flag(args, "--json") {
371        println!("{}", report.to_json());
372    } else {
373        println!("{}", report.render());
374        println!("artifact:           {}", out.display());
375    }
376
377    if has_flag(args, "--gate") && !report.gate_passes() {
378        eprintln!("\nfootprint gate FAILED: a harmful injected element is present");
379        std::process::exit(1);
380    }
381}
382
383fn run_footprint_or_exit(
384    suite: &EvalSuite,
385    suite_name: &str,
386    footprint: &Footprint,
387    runner: &dyn ModelRunner,
388    cfg: &FootprintConfig,
389) -> FootprintReport {
390    match run_footprint_ab(suite, suite_name, footprint, runner, cfg) {
391        Ok(r) => r,
392        Err(e) => {
393            eprintln!("eval footprint: run failed: {e:#}");
394            std::process::exit(1);
395        }
396    }
397}
398
399/// Default footprint artifact location: `<data_dir>/eval/footprint-report-v1_<utc>.json`.
400fn default_footprint_path() -> Result<PathBuf, String> {
401    let dir = crate::core::data_dir::lean_ctx_data_dir()?.join("eval");
402    std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir eval: {e}"))?;
403    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
404    Ok(dir.join(format!("footprint-report-v1_{stamp}.json")))
405}
406
407/// `eval testbench`: run the off-vs-on answer-quality benchmark across every pinned
408/// repo in a lockfile, write `FINDINGS.md` + `regressions.json`, and (with `--gate`)
409/// fail the build if any repo regressed (#611).
410fn cmd_testbench(args: &[String]) {
411    let lock_path = flag_value(args, "--lock").map_or_else(
412        || PathBuf::from("eval/testbench/testbench.lock.json"),
413        PathBuf::from,
414    );
415    let lock = match TestbenchLock::load(&lock_path) {
416        Ok(l) => l,
417        Err(e) => {
418            eprintln!("eval testbench: {e:#}\n(use --lock <file> to point at a lockfile)");
419            std::process::exit(1);
420        }
421    };
422
423    let out_dir =
424        flag_value(args, "--out").map_or_else(|| PathBuf::from("testbench-out"), PathBuf::from);
425    let cache_dir =
426        flag_value(args, "--cache").map_or_else(|| out_dir.join("cache"), PathBuf::from);
427
428    let mut cfg = TestbenchConfig::default();
429    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
430        cfg.run.budget_tokens = b;
431    }
432    cfg.run.report = ReportConfig {
433        noninferiority_margin: flag_value(args, "--margin")
434            .and_then(|v| v.parse().ok())
435            .unwrap_or(0.0),
436        ..ReportConfig::default()
437    };
438
439    let report = if let Some(replay) = flag_value(args, "--replay") {
440        let runner = match RecordedRunner::from_file(Path::new(replay)) {
441            Ok(r) => r,
442            Err(e) => {
443                eprintln!("eval testbench: {e:#}");
444                std::process::exit(1);
445            }
446        };
447        run_testbench_or_exit(&lock, &cache_dir, &runner, &cfg)
448    } else {
449        let live = match OpenAiRunner::from_env() {
450            Ok(r) => r,
451            Err(e) => {
452                eprintln!(
453                    "eval testbench: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
454                );
455                std::process::exit(1);
456            }
457        };
458        if let Some(record_path) = flag_value(args, "--record") {
459            let recorder = RecordingRunner::new(live);
460            let report = run_testbench_or_exit(&lock, &cache_dir, &recorder, &cfg);
461            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
462                eprintln!("eval testbench: failed to save recording: {e:#}");
463                std::process::exit(1);
464            }
465            println!("Recording saved → {record_path}");
466            report
467        } else {
468            run_testbench_or_exit(&lock, &cache_dir, &live, &cfg)
469        }
470    };
471
472    let (findings_path, regressions_path) = match findings::write(&report, &out_dir) {
473        Ok(paths) => paths,
474        Err(e) => {
475            eprintln!("eval testbench: {e:#}");
476            std::process::exit(1);
477        }
478    };
479
480    print!("{}", findings::render_findings(&report));
481    println!("\nFINDINGS:     {}", findings_path.display());
482    println!("regressions:  {}", regressions_path.display());
483
484    if has_flag(args, "--gate") && !report.gate_passes() {
485        eprintln!("\ntestbench gate FAILED: {}", report.verdict.label());
486        std::process::exit(1);
487    }
488}
489
490fn run_testbench_or_exit(
491    lock: &TestbenchLock,
492    cache_dir: &Path,
493    runner: &dyn ModelRunner,
494    cfg: &TestbenchConfig,
495) -> TestbenchReport {
496    match testbench::run_testbench(lock, cache_dir, runner, cfg) {
497        Ok(r) => r,
498        Err(e) => {
499            eprintln!("eval testbench: run failed: {e:#}");
500            std::process::exit(1);
501        }
502    }
503}
504
505fn cmd_verify(args: &[String]) {
506    let Some(path) = args.first() else {
507        eprintln!("eval verify: <artifact.json> is required");
508        std::process::exit(2);
509    };
510    let artifact = match artifact::load_artifact(Path::new(path)) {
511        Ok(a) => a,
512        Err(e) => {
513            eprintln!("eval verify: {e}");
514            std::process::exit(1);
515        }
516    };
517    let result = artifact.verify();
518    println!("Artifact:           {path}");
519    println!("Verdict:            {}", artifact.verdict.label());
520    println!("Determinism digest: {}", artifact.determinism_digest);
521    println!(
522        "Digest matches:     {}",
523        if result.digest_matches { "yes" } else { "NO" }
524    );
525    println!(
526        "Signature valid:    {}",
527        if result.signature_valid { "yes" } else { "NO" }
528    );
529    if let Some(pk) = &result.signer_public_key {
530        println!("Signer public key:  {pk}");
531    }
532    if let Some(err) = &result.error {
533        println!("Error:              {err}");
534    }
535    if result.ok() {
536        println!("\nOK — artifact is authentic and internally consistent.");
537    } else {
538        eprintln!("\nFAILED — artifact could not be verified.");
539        std::process::exit(1);
540    }
541}
542
543fn cmd_init(args: &[String]) {
544    let dir = PathBuf::from(args.first().map_or("eval-suite", |s| s.as_str()));
545    match write_starter_suite(&dir) {
546        Ok(suite) => {
547            println!("Starter suite written to {}", dir.display());
548            println!("Suite file: {}", suite.display());
549            println!("\nNext:");
550            println!("  # 1) record real model answers once (needs a live model in env)");
551            println!(
552                "  lean-ctx eval ab --suite {} --record {}/recording.json",
553                suite.display(),
554                dir.display()
555            );
556            println!("  # 2) replay deterministically anywhere (CI)");
557            println!(
558                "  lean-ctx eval ab --suite {} --replay {}/recording.json --gate",
559                suite.display(),
560                dir.display()
561            );
562        }
563        Err(e) => {
564            eprintln!("eval init: {e:#}");
565            std::process::exit(1);
566        }
567    }
568}
569
570/// Materializes a small, runnable starter suite: one RAG/QA task whose answer lives in the
571/// corpus, and one POSIX-shell code task with a failing stub + unit test.
572fn write_starter_suite(dir: &Path) -> anyhow::Result<PathBuf> {
573    use anyhow::Context;
574    let corpus = dir.join("corpus");
575    let code = dir.join("code");
576    std::fs::create_dir_all(&corpus).context("creating corpus dir")?;
577    std::fs::create_dir_all(&code).context("creating code dir")?;
578
579    std::fs::write(
580        corpus.join("architecture.md"),
581        "# Consolidation pipeline\n\n\
582Provider data flows through one consolidation pipeline. Artifacts are persisted to four \
583stores: the BM25 index, the Graph index, ProjectKnowledge, and the Session cache. This is \
584what lets semantic search, knowledge recall, and cross-source hints share one source of truth.\n",
585    )
586    .context("writing corpus/architecture.md")?;
587    std::fs::write(
588        corpus.join("overview.md"),
589        "# Overview\n\nlean-ctx is a context runtime for AI agents. This file is general \
590background and intentionally does not list the consolidation stores.\n",
591    )
592    .context("writing corpus/overview.md")?;
593
594    std::fs::write(
595        code.join("test.sh"),
596        "#!/bin/sh\n. ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ] || exit 1\n[ \"$(add 10 20)\" = \"30\" ] || exit 1\n",
597    )
598    .context("writing code/test.sh")?;
599    std::fs::write(
600        code.join("solution.sh"),
601        "# TODO: implement add() so that `add a b` prints a+b\nadd() { echo 0; }\n",
602    )
603    .context("writing code/solution.sh")?;
604
605    let suite = dir.join("suite.ndjson");
606    let lines = [
607        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"]}"#,
608        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"}"#,
609    ];
610    std::fs::write(
611        &suite,
612        format!("# lean-ctx eval starter suite\n{}\n", lines.join("\n")),
613    )
614    .context("writing suite.ndjson")?;
615    Ok(suite)
616}
617
618#[cfg(test)]
619mod recording_guard_tests {
620    use super::*;
621
622    /// The committed recording (`rust/eval/recording.json`) is what flips the CI
623    /// quality-gate from "skipped" to "enforced" (#361 Phase 3). Guard it
624    /// **in-process** so a suite/corpus/prompt change that invalidates the
625    /// recording (a replay key miss) or a captured regression fails here in
626    /// `cargo test` — i.e. during `dev-install` — not only in CI.
627    #[test]
628    fn committed_recording_replays_and_passes_gate() {
629        let dir = tempfile::tempdir().unwrap();
630        let suite_path = write_starter_suite(dir.path()).expect("scaffold starter suite");
631        let suite = EvalSuite::load(&suite_path).expect("load starter suite");
632
633        let rec_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("eval/recording.json");
634        assert!(
635            rec_path.exists(),
636            "committed recording missing at {} — CI quality-gate would silently skip",
637            rec_path.display()
638        );
639        let runner = RecordedRunner::from_file(&rec_path).expect("load committed recording");
640
641        // Every (task × condition) request must hit a recorded key, else the
642        // recording drifted from the suite/corpus/prompt and must be re-captured.
643        let report = run_ab(&suite, "suite.ndjson", &runner, &AbRunConfig::default())
644            .expect("committed recording must cover every replay key");
645        assert!(
646            report.verdict.gate_passes(),
647            "committed recording must not encode a regression, got: {}",
648            report.verdict.label()
649        );
650    }
651}