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::arm_study::{self, Arm, ProviderCondition};
11use crate::core::eval_ab::artifact::{self, SignedAbReportV1};
12use crate::core::eval_ab::conditions::Condition;
13use crate::core::eval_ab::footprint::{
14    Footprint, FootprintConfig, FootprintReport, run_footprint_ab,
15};
16use crate::core::eval_ab::frontier::{self, FrontierReport};
17use crate::core::eval_ab::model::{ModelRunner, OpenAiRunner, RecordedRunner, RecordingRunner};
18use crate::core::eval_ab::report::ReportConfig;
19use crate::core::eval_ab::suite::EvalSuite;
20use crate::core::eval_ab::testbench::lockfile::TestbenchLock;
21use crate::core::eval_ab::testbench::{self, TestbenchConfig, TestbenchReport, findings};
22use crate::core::eval_ab::{AbRunConfig, run_ab};
23
24/// Entry point dispatched from `cli::dispatch`.
25pub fn cmd_eval(args: &[String]) {
26    // `eval --delta [opts]` is sugar for the footprint subcommand.
27    if args.iter().any(|a| a == "--delta") {
28        let rest: Vec<String> = args.iter().filter(|a| *a != "--delta").cloned().collect();
29        return cmd_footprint(&rest);
30    }
31    match args.first().map(String::as_str) {
32        Some("ab") => cmd_ab(&args[1..]),
33        Some("frontier") => cmd_frontier(&args[1..]),
34        Some("footprint" | "delta") => cmd_footprint(&args[1..]),
35        Some("testbench") => cmd_testbench(&args[1..]),
36        Some("verify") => cmd_verify(&args[1..]),
37        Some("arm-study") => cmd_arm_study(&args[1..]),
38        Some("init") => cmd_init(&args[1..]),
39        Some("-h" | "--help") | None => print_help(),
40        Some(other) => {
41            eprintln!("eval: unknown subcommand '{other}'\n");
42            print_help();
43            std::process::exit(2);
44        }
45    }
46}
47
48fn print_help() {
49    println!(
50        "lean-ctx eval — deterministic with/without output-quality proof\n\n\
51USAGE:\n\
52  lean-ctx eval init <dir>                 Scaffold a runnable starter suite\n\
53  lean-ctx eval ab --suite <file> [opts]   Run the A/B quality comparison\n\
54  lean-ctx eval footprint --suite <f> [o]  Ablate lean-ctx's OWN injected context (#959)\n\
55  lean-ctx eval testbench --lock <f> [o]   Off-vs-on across pinned real repos (#611)\n\
56  lean-ctx eval verify <artifact.json>     Verify signature + determinism digest\n\n\
57ab OPTIONS:\n\
58  --suite <file>     NDJSON suite (required)\n\
59  --budget <n>       Token budget per condition (default 4000)\n\
60  --margin <f>       Non-inferiority margin for the gate (default 0.0)\n\
61  --out <file>       Artifact path (default: data dir)\n\
62  --replay <file>    Replay a recording instead of calling a live model (deterministic CI)\n\
63  --record <file>    Call the live model and save responses to a recording\n\
64  --gate             Exit non-zero if the verdict is a regression\n\n\
65footprint OPTIONS (also: `eval --delta`):\n\
66  --suite <file>     Footprint-sensitive NDJSON suite (required)\n\
67  --margin <f>       Non-inferiority margin for the per-element gate (default 0.0)\n\
68  --floor <n>        Min marginal tokens before flagging an element to prune (default 50)\n\
69  --replay <file>    Replay a recording (deterministic); --record to capture live\n\
70  --json             Emit the full JSON report instead of the side-by-side table\n\
71  --gate             Exit non-zero if any injected element is actively harmful\n\
72  --export <file>    Write this build's footprint (rules, tool schemas, wakeup) as JSON\n\
73  --compare <file>   Paired run: exported baseline footprint vs. this build's footprint\n\n\
74testbench OPTIONS:\n\
75  --lock <file>      Pinned-repo lockfile (default eval/testbench/testbench.lock.json)\n\
76  --out <dir>        Output dir for FINDINGS.md + regressions.json (default testbench-out)\n\
77  --cache <dir>      Clone cache for remote repos (default <out>/cache)\n\
78  --budget <n>       Token budget per condition (default 4000)\n\
79  --margin <f>       Non-inferiority margin for the per-repo gate (default 0.0)\n\
80  --replay <file>    Replay a recording (deterministic CI); --record to capture live\n\
81  --gate             Exit non-zero if any repo regressed\n\n\
82GATES: --gate fails on REGRESSED and on UNDERPOWERED (too few pairs to show quality).\n\
83  --mechanism        With --gate: wiring check for tiny fixture suites; only REGRESSED fails\n\n\
84LIVE MODEL (when not replaying) is read from the environment:\n\
85  LEAN_CTX_EVAL_MODEL_URL   OpenAI-compatible base URL (e.g. https://api.openai.com/v1)\n\
86  LEAN_CTX_EVAL_MODEL       Model id (e.g. gpt-4o-mini)\n\
87  LEAN_CTX_EVAL_MODEL_KEY   API key (optional for local servers)\n\
88  LEAN_CTX_EVAL_SEED        Decoding seed (default 7)"
89    );
90    println!(
91        "  lean-ctx eval frontier --suite <file> --strategies <csv> [opts]\n\
92frontier strategies: lean_ctx, json_crush, tabular_crush, yaml_crush, read_full, read_map, read_signatures\n\
93frontier options: --limit <n>, --budget <n>, --replay <file>, --record <file>, --json, --gate, --save-evidence"
94    );
95    println!(
96        "Model revision provenance: LEAN_CTX_EVAL_MODEL_VERSION (defaults to a colon-tagged model revision when available)."
97    );
98    println!(
99        "  lean-ctx eval arm-study --protocol <file> --observations <file> [--json]\n\
100arm-study: medians, 95% intervals and p95 latency over SUPPLIED four-arm observations of a\n\
101registered task list. It runs nothing and measures nothing, and what it prints is no proof\n\
102that the observations are authentic, blind or preregistered in time."
103    );
104    println!(
105        "Optional provider metadata: --provider-report <file> --provider-arm <unchanged_agent|community|team|company> --provider-condition <baseline|lean_ctx>"
106    );
107}
108
109/// A regular file that is not a link, read up to `limit` bytes; one byte more
110/// is a refusal, never a truncation.
111///
112/// The open itself decides: it does not follow a link in the last component
113/// and does not wait on a FIFO, so nothing swapped in after an earlier look can
114/// be read or block. What was opened must be a regular file, and the path must
115/// still name that very file. Where the platform has no such open here, the
116/// read is refused instead of done the unsafe way.
117#[cfg(unix)]
118fn bounded_regular_file(path: &Path, limit: usize) -> Result<Vec<u8>, &'static str> {
119    use std::io::Read;
120    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
121    let file = std::fs::OpenOptions::new()
122        .read(true)
123        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
124        .open(path)
125        .map_err(|_| "cannot be opened as a file that is not a link")?;
126    let opened = file.metadata().map_err(|_| "cannot be read")?;
127    if !opened.is_file() {
128        return Err("is not a regular file");
129    }
130    let named = std::fs::symlink_metadata(path).map_err(|_| "cannot be read")?;
131    if !named.file_type().is_file() || (named.dev(), named.ino()) != (opened.dev(), opened.ino()) {
132        return Err("was replaced while it was opened");
133    }
134    let mut bytes = Vec::new();
135    file.take(limit as u64 + 1)
136        .read_to_end(&mut bytes)
137        .map_err(|_| "cannot be read")?;
138    if bytes.len() > limit {
139        return Err("exceeds its size bound");
140    }
141    Ok(bytes)
142}
143
144/// Windows: the parent directory is opened and held as the object it is (a
145/// reparse point is refused, not followed), and the file is opened by its one
146/// name RELATIVE to that held handle with the shared opener
147/// (`leanctx_native_storage::windows_file::open_relative`: `RootDirectory` +
148/// `OBJ_DONT_REPARSE`), read-only, as a non-directory, without following a final
149/// reparse point — the flags `agent_identity::read_key_file` opens a key with.
150/// The admitted length is checked before a byte is read; after the read the
151/// same name is opened once more against the same held directory and must be
152/// the same file (volume serial and file index) of the same length.
153///
154/// The protection is of the parent and the final component. A reparse point in
155/// an EARLIER component of the path is not looked for, and the handles share
156/// write and delete like the opener's other callers: a change is detected by
157/// the checks above, it is not prevented.
158#[cfg(windows)]
159fn bounded_regular_file(path: &Path, limit: usize) -> Result<Vec<u8>, &'static str> {
160    use leanctx_native_storage::windows_file::open_relative;
161    use std::fs::File;
162    use std::io::Read;
163    use std::os::windows::ffi::OsStrExt;
164    use std::os::windows::fs::MetadataExt;
165    use std::os::windows::io::{AsRawHandle, FromRawHandle};
166    use windows_sys::Wdk::Storage::FileSystem::{
167        FILE_NON_DIRECTORY_FILE, FILE_OPEN, FILE_OPEN_REPARSE_POINT, FILE_SYNCHRONOUS_IO_NONALERT,
168    };
169    use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
170    use windows_sys::Win32::Storage::FileSystem::{
171        BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT,
172        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_LIST_DIRECTORY,
173        FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
174        GetFileInformationByHandle, OPEN_EXISTING, SYNCHRONIZE,
175    };
176
177    const NOT_OPENED: &str = "cannot be opened as a file that is not a link";
178    const NOT_READ: &str = "cannot be read";
179    const NOT_REGULAR: &str = "is not a regular file";
180    const TOO_LARGE: &str = "exceeds its size bound";
181
182    // A relative path is taken against the working directory as it is now,
183    // lexically: nothing is canonicalized and then opened the ordinary way.
184    let absolute = if path.is_absolute() {
185        path.to_path_buf()
186    } else {
187        std::env::current_dir().map_err(|_| NOT_READ)?.join(path)
188    };
189    let parent = absolute.parent().ok_or(NOT_OPENED)?;
190    let name: Vec<u16> = absolute
191        .file_name()
192        .ok_or(NOT_OPENED)?
193        .encode_wide()
194        .collect();
195    // The parent as it is named, first WITHOUT a terminator: a NUL inside it would
196    // make the call open a shorter path than the one that was checked. Refused;
197    // then exactly one terminator is appended.
198    let mut wide_parent: Vec<u16> = parent.as_os_str().encode_wide().collect();
199    if wide_parent.contains(&0) {
200        return Err(NOT_OPENED);
201    }
202    wide_parent.push(0);
203    // SAFETY: `wide_parent` is NUL-terminated and lives through the call;
204    // security attributes and template handle are null.
205    let handle = unsafe {
206        CreateFileW(
207            wide_parent.as_ptr(),
208            FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
209            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
210            std::ptr::null(),
211            OPEN_EXISTING,
212            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
213            std::ptr::null_mut(),
214        )
215    };
216    if handle == INVALID_HANDLE_VALUE || handle.is_null() {
217        return Err(NOT_OPENED);
218    }
219    // SAFETY: a successful `CreateFileW` returned this owned handle.
220    let directory = unsafe { File::from_raw_handle(handle) };
221    let held = directory.metadata().map_err(|_| NOT_READ)?;
222    if held.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 || !held.is_dir() {
223        return Err(NOT_OPENED);
224    }
225
226    let open = || {
227        open_relative(
228            &directory,
229            &name,
230            FILE_READ_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
231            FILE_OPEN,
232            FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
233        )
234        .map_err(|_| NOT_OPENED)
235    };
236    // The length of what was opened, if it is a regular file and no reparse point.
237    let regular_length = |file: &File| -> Result<u64, &'static str> {
238        let about = file.metadata().map_err(|_| NOT_READ)?;
239        if about.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 || !about.is_file() {
240            return Err(NOT_REGULAR);
241        }
242        Ok(about.len())
243    };
244    let identity = |file: &File| -> Result<(u32, u32, u32), &'static str> {
245        let mut info = BY_HANDLE_FILE_INFORMATION::default();
246        // SAFETY: a live handle and exactly the writable storage the call fills.
247        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &raw mut info) } == 0 {
248            return Err(NOT_READ);
249        }
250        Ok((
251            info.dwVolumeSerialNumber,
252            info.nFileIndexHigh,
253            info.nFileIndexLow,
254        ))
255    };
256
257    let file = open()?;
258    if regular_length(&file)? > limit as u64 {
259        return Err(TOO_LARGE);
260    }
261    let opened = identity(&file)?;
262    let mut bytes = Vec::new();
263    (&file)
264        .take(limit as u64 + 1)
265        .read_to_end(&mut bytes)
266        .map_err(|_| NOT_READ)?;
267    if bytes.len() > limit {
268        return Err(TOO_LARGE);
269    }
270    let again = open()?;
271    if regular_length(&again)? != bytes.len() as u64
272        || regular_length(&file)? != bytes.len() as u64
273        || identity(&again)? != opened
274    {
275        return Err("was replaced while it was opened");
276    }
277    Ok(bytes)
278}
279
280#[cfg(not(any(unix, windows)))]
281fn bounded_regular_file(path: &Path, limit: usize) -> Result<Vec<u8>, &'static str> {
282    let _ = (path, limit);
283    Err("cannot be read: this command has no link-safe file open on this platform")
284}
285
286/// The optional provider source is one explicit all-or-none tuple. Admission of
287/// these arguments precedes every file read, including the unchanged old inputs.
288fn arm_study_provider_args(
289    args: &[String],
290) -> Result<Option<(&str, Arm, ProviderCondition)>, &'static str> {
291    let mut values = [None; 3];
292    for (index, arg) in args.iter().enumerate() {
293        let slot = match arg.as_str() {
294            "--provider-report" => 0,
295            "--provider-arm" => 1,
296            "--provider-condition" => 2,
297            _ if arg.split_once('=').is_some_and(|(flag, _)| {
298                matches!(
299                    flag,
300                    "--provider-report" | "--provider-arm" | "--provider-condition"
301                )
302            }) =>
303            {
304                return Err("provider flags require separate values");
305            }
306            _ => continue,
307        };
308        if values[slot].is_some() {
309            return Err("provider flags must occur exactly once");
310        }
311        values[slot] = Some(
312            args.get(index + 1)
313                .map(String::as_str)
314                .filter(|value| !value.is_empty() && !value.starts_with('-'))
315                .ok_or("provider flags require a value")?,
316        );
317    }
318    match values {
319        [None, None, None] => Ok(None),
320        [Some(path), Some(arm), Some(condition)] => {
321            let arm = match arm {
322                "unchanged_agent" => Arm::UnchangedAgent,
323                "community" => Arm::Community,
324                "team" => Arm::Team,
325                "company" => Arm::Company,
326                _ => {
327                    return Err("provider arm must be unchanged_agent, community, team or company");
328                }
329            };
330            let condition = match condition {
331                "baseline" => ProviderCondition::Baseline,
332                "lean_ctx" => ProviderCondition::LeanCtx,
333                _ => return Err("provider condition must be baseline or lean_ctx"),
334            };
335            Ok(Some((path, arm, condition)))
336        }
337        _ => Err("provider-report, provider-arm and provider-condition are required together"),
338    }
339}
340
341/// `eval arm-study`: inputs are admitted by size before they are
342/// parsed, the protocol's own work bounds before anything is analysed
343/// (`arm_study::parse_protocol`), and a refusal exits 1 with the rule it broke.
344fn cmd_arm_study(args: &[String]) {
345    let provider = arm_study_provider_args(args).unwrap_or_else(|error| {
346        eprintln!("eval arm-study: {error}");
347        std::process::exit(2);
348    });
349    let (Some(protocol_path), Some(observations_path)) = (
350        flag_value(args, "--protocol"),
351        flag_value(args, "--observations"),
352    ) else {
353        eprintln!("eval arm-study: --protocol <file> and --observations <file> are required");
354        std::process::exit(2);
355    };
356    let read = |path: &str, limit: usize| {
357        bounded_regular_file(Path::new(path), limit).unwrap_or_else(|error| {
358            eprintln!("eval arm-study: {path} {error}");
359            std::process::exit(1);
360        })
361    };
362    let protocol_bytes = read(protocol_path, arm_study::MAX_PROTOCOL_BYTES);
363    let observation_bytes = read(observations_path, arm_study::MAX_OBSERVATIONS_BYTES);
364    let provider_bytes = provider.map(|(path, arm, condition)| {
365        (
366            read(path, arm_study::MAX_PROVIDER_REPORT_BYTES),
367            arm,
368            condition,
369        )
370    });
371    let report = arm_study::parse_protocol(&protocol_bytes).and_then(|(protocol, digest)| {
372        let mut observations = arm_study::parse_observations(&observation_bytes)?;
373        if let Some((bytes, arm, condition)) = &provider_bytes {
374            let provider_report = arm_study::parse_provider_report(bytes)?;
375            arm_study::attach_provider_observations(
376                &mut observations,
377                &provider_report,
378                *arm,
379                *condition,
380            )?;
381        }
382        arm_study::analyze(&protocol, &digest, &observations)
383    });
384    match report {
385        Ok(report) if has_flag(args, "--json") => println!("{}", report.to_json()),
386        Ok(report) => print!("{}", report.render()),
387        Err(refusal) => {
388            eprintln!("eval arm-study: refused: {refusal}");
389            std::process::exit(1);
390        }
391    }
392}
393
394/// Returns the value following `flag` in `args`, if present.
395fn flag_value<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
396    args.iter()
397        .position(|a| a == flag)
398        .and_then(|i| args.get(i + 1))
399        .map(String::as_str)
400}
401
402fn has_flag(args: &[String], flag: &str) -> bool {
403    args.iter().any(|a| a == flag)
404}
405
406fn cmd_ab(args: &[String]) {
407    let Some(suite_path) = flag_value(args, "--suite") else {
408        eprintln!("eval ab: --suite <file> is required");
409        std::process::exit(2);
410    };
411    let suite_path = PathBuf::from(suite_path);
412    let suite = match EvalSuite::load(&suite_path) {
413        Ok(s) => s,
414        Err(e) => {
415            eprintln!("eval ab: {e:#}");
416            std::process::exit(1);
417        }
418    };
419    let suite_name = suite_path
420        .file_name()
421        .map_or_else(|| "suite".to_string(), |s| s.to_string_lossy().into_owned());
422
423    let mut cfg = AbRunConfig::default();
424    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
425        cfg.budget_tokens = b;
426    }
427    cfg.report = ReportConfig {
428        noninferiority_margin: flag_value(args, "--margin")
429            .and_then(|v| v.parse().ok())
430            .unwrap_or(0.0),
431        ..ReportConfig::default()
432    };
433
434    // Runner selection: replay (deterministic) > live + record > live.
435    let report = if let Some(replay) = flag_value(args, "--replay") {
436        let runner = match RecordedRunner::from_file(Path::new(replay)) {
437            Ok(r) => r,
438            Err(e) => {
439                eprintln!("eval ab: {e:#}");
440                std::process::exit(1);
441            }
442        };
443        run_or_exit(&suite, &suite_name, &runner, &cfg)
444    } else {
445        let live = match OpenAiRunner::from_env() {
446            Ok(r) => r,
447            Err(e) => {
448                eprintln!(
449                    "eval ab: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
450                );
451                std::process::exit(1);
452            }
453        };
454        cfg.report.live_model = true;
455        if let Some(record_path) = flag_value(args, "--record") {
456            let recorder = RecordingRunner::new(live);
457            let report = run_or_exit(&suite, &suite_name, &recorder, &cfg);
458            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
459                eprintln!("eval ab: failed to save recording: {e:#}");
460                std::process::exit(1);
461            }
462            println!("Recording saved → {record_path}");
463            report
464        } else {
465            run_or_exit(&suite, &suite_name, &live, &cfg)
466        }
467    };
468
469    // Sign + persist the artifact.
470    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
471    let mut signed = SignedAbReportV1::from_report(report, &agent_id);
472    if let Err(e) = signed.sign(&agent_id) {
473        eprintln!("eval ab: signing failed: {e}");
474        std::process::exit(1);
475    }
476    let out = match flag_value(args, "--out") {
477        Some(p) => PathBuf::from(p),
478        None => match artifact::default_artifact_path() {
479            Ok(p) => p,
480            Err(e) => {
481                eprintln!("eval ab: {e}");
482                std::process::exit(1);
483            }
484        },
485    };
486    if let Err(e) = artifact::write_artifact(&signed, &out) {
487        eprintln!("eval ab: {e}");
488        std::process::exit(1);
489    }
490
491    println!("{}", signed.report.render());
492    println!("determinism digest: {}", signed.determinism_digest);
493    println!("artifact:           {}", out.display());
494
495    if has_flag(args, "--gate") && !signed.verdict.passes_gate(has_flag(args, "--mechanism")) {
496        eprintln!("\nquality gate FAILED: {}", signed.verdict.label());
497        std::process::exit(1);
498    }
499}
500
501fn cmd_frontier(args: &[String]) {
502    let Some(suite_path) = flag_value(args, "--suite") else {
503        eprintln!("eval frontier: --suite <file> is required");
504        std::process::exit(2);
505    };
506    let Some(strategy_names) = flag_value(args, "--strategies") else {
507        eprintln!("eval frontier: --strategies <csv> is required");
508        std::process::exit(2);
509    };
510    let strategies = match frontier::parse_strategies(strategy_names) {
511        Ok(strategies) => strategies,
512        Err(error) => {
513            eprintln!("eval frontier: {error:#}");
514            std::process::exit(2);
515        }
516    };
517
518    let suite_path = PathBuf::from(suite_path);
519    let mut suite = match EvalSuite::load(&suite_path) {
520        Ok(suite) => suite,
521        Err(error) => {
522            eprintln!("eval frontier: {error:#}");
523            std::process::exit(1);
524        }
525    };
526    if let Some(limit) = flag_value(args, "--limit") {
527        let Ok(limit) = limit.parse::<usize>() else {
528            eprintln!("eval frontier: --limit must be a positive integer");
529            std::process::exit(2);
530        };
531        if limit == 0 {
532            eprintln!("eval frontier: --limit must be a positive integer");
533            std::process::exit(2);
534        }
535        suite.tasks.truncate(limit);
536    }
537    let suite_name = suite_path.file_name().map_or_else(
538        || "suite".to_string(),
539        |name| name.to_string_lossy().into_owned(),
540    );
541
542    let mut cfg = AbRunConfig::default();
543    if let Some(budget) = flag_value(args, "--budget").and_then(|value| value.parse().ok()) {
544        cfg.budget_tokens = budget;
545    }
546    cfg.report = ReportConfig {
547        noninferiority_margin: flag_value(args, "--margin")
548            .and_then(|value| value.parse().ok())
549            .unwrap_or(0.0),
550        ..ReportConfig::default()
551    };
552
553    let report = if let Some(replay) = flag_value(args, "--replay") {
554        let runner = match RecordedRunner::from_file(Path::new(replay)) {
555            Ok(runner) => runner,
556            Err(error) => {
557                eprintln!("eval frontier: {error:#}");
558                std::process::exit(1);
559            }
560        };
561        run_frontier_or_exit(&suite, &suite_name, &runner, &cfg, &strategies)
562    } else {
563        let live = match OpenAiRunner::from_env() {
564            Ok(runner) => runner,
565            Err(error) => {
566                eprintln!(
567                    "eval frontier: no live model configured: {error:#}\n(use --replay <file> for an offline run)"
568                );
569                std::process::exit(1);
570            }
571        };
572        cfg.report.live_model = true;
573        if let Some(record_path) = flag_value(args, "--record") {
574            let recorder = RecordingRunner::new(live);
575            let report = run_frontier_or_exit(&suite, &suite_name, &recorder, &cfg, &strategies);
576            if let Err(error) = recorder.into_recording().save(Path::new(record_path)) {
577                eprintln!("eval frontier: failed to save recording: {error:#}");
578                std::process::exit(1);
579            }
580            eprintln!("Recording saved → {record_path}");
581            report
582        } else {
583            run_frontier_or_exit(&suite, &suite_name, &live, &cfg, &strategies)
584        }
585    };
586
587    if has_flag(args, "--json") {
588        println!("{}", report.to_json());
589    } else {
590        print!("{}", report.render_table());
591    }
592    if has_flag(args, "--save-evidence") {
593        match crate::core::eval_ab::strategy_evaluations::save(&report) {
594            Ok(0) => eprintln!(
595                "No read-strategy evaluation to save (use read_full, read_map, read_signatures)."
596            ),
597            Ok(saved) => {
598                eprintln!("Saved {saved} read-strategy evaluation(s) as context-policy evidence.");
599            }
600            Err(error) => {
601                eprintln!("eval frontier: failed to save evidence: {error}");
602                std::process::exit(1);
603            }
604        }
605    }
606    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
607        eprintln!("\nquality gate FAILED: one or more frontier strategies regressed");
608        std::process::exit(1);
609    }
610}
611
612fn run_frontier_or_exit(
613    suite: &EvalSuite,
614    suite_name: &str,
615    runner: &dyn ModelRunner,
616    cfg: &AbRunConfig,
617    strategies: &[Condition],
618) -> FrontierReport {
619    match frontier::run_frontier(suite, suite_name, runner, cfg, strategies) {
620        Ok(report) => report,
621        Err(error) => {
622            eprintln!("eval frontier: run failed: {error:#}");
623            std::process::exit(1);
624        }
625    }
626}
627
628fn run_or_exit(
629    suite: &EvalSuite,
630    suite_name: &str,
631    runner: &dyn crate::core::eval_ab::model::ModelRunner,
632    cfg: &AbRunConfig,
633) -> crate::core::eval_ab::report::AbReport {
634    match run_ab(suite, suite_name, runner, cfg) {
635        Ok(r) => r,
636        Err(e) => {
637            eprintln!("eval ab: run failed: {e:#}");
638            std::process::exit(1);
639        }
640    }
641}
642
643/// `eval footprint` (alias `eval --delta`): ablate each element of lean-ctx's own
644/// injected context (rules / tool schemas / wakeup) and report per-element
645/// pass-rate Δ + token Δ with a prune recommendation (#959).
646/// `eval footprint --compare <baseline.json>`: the exported footprint of another
647/// build against this build's live footprint, paired on the same tasks.
648fn cmd_footprint_compare(
649    args: &[String],
650    suite: &EvalSuite,
651    suite_name: &str,
652    baseline_path: &str,
653    candidate: &Footprint,
654    mut report_cfg: ReportConfig,
655) {
656    let baseline: Footprint = match std::fs::read_to_string(baseline_path)
657        .map_err(|e| e.to_string())
658        .and_then(|raw| serde_json::from_str(&raw).map_err(|e| e.to_string()))
659    {
660        Ok(fp) => fp,
661        Err(e) => {
662            eprintln!("eval footprint: cannot load baseline footprint {baseline_path}: {e}");
663            std::process::exit(1);
664        }
665    };
666    let run = |runner: &dyn crate::core::eval_ab::model::ModelRunner, cfg: ReportConfig| {
667        match crate::core::eval_ab::footprint::run_footprint_compare(
668            suite, suite_name, &baseline, candidate, runner, cfg,
669        ) {
670            Ok(report) => report,
671            Err(e) => {
672                eprintln!("eval footprint: {e:#}");
673                std::process::exit(1);
674            }
675        }
676    };
677    let report = if let Some(replay) = flag_value(args, "--replay") {
678        match RecordedRunner::from_file(Path::new(replay)) {
679            Ok(runner) => run(&runner, report_cfg),
680            Err(e) => {
681                eprintln!("eval footprint: {e:#}");
682                std::process::exit(1);
683            }
684        }
685    } else {
686        let live = match OpenAiRunner::from_env() {
687            Ok(r) => r,
688            Err(e) => {
689                eprintln!(
690                    "eval footprint: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
691                );
692                std::process::exit(1);
693            }
694        };
695        report_cfg.live_model = true;
696        if let Some(record_path) = flag_value(args, "--record") {
697            let recorder = RecordingRunner::new(live);
698            let report = run(&recorder, report_cfg);
699            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
700                eprintln!("eval footprint: failed to save recording: {e:#}");
701                std::process::exit(1);
702            }
703            println!("Recording saved → {record_path}");
704            report
705        } else {
706            run(&live, report_cfg)
707        }
708    };
709    let saved = report
710        .records
711        .first()
712        .map_or(0, |r| r.baseline_tokens as i64 - r.lean_ctx_tokens as i64);
713    println!("Footprint compare: baseline {baseline_path} vs. this build");
714    println!(
715        "Fixed footprint delta: {saved:+} tokens per request (positive = candidate smaller)\n"
716    );
717    println!("{}", report.render());
718    if has_flag(args, "--gate") && !report.verdict.passes_gate(has_flag(args, "--mechanism")) {
719        eprintln!(
720            "\nfootprint compare gate FAILED: {}",
721            report.verdict.label()
722        );
723        std::process::exit(1);
724    }
725}
726
727fn cmd_footprint(args: &[String]) {
728    let Some(suite_path) = flag_value(args, "--suite") else {
729        eprintln!("eval footprint: --suite <file> is required");
730        std::process::exit(2);
731    };
732    let suite_path = PathBuf::from(suite_path);
733    let suite = match EvalSuite::load(&suite_path) {
734        Ok(s) => s,
735        Err(e) => {
736            eprintln!("eval footprint: {e:#}");
737            std::process::exit(1);
738        }
739    };
740    let suite_name = suite_path.file_name().map_or_else(
741        || "footprint".to_string(),
742        |s| s.to_string_lossy().into_owned(),
743    );
744
745    let margin = flag_value(args, "--margin")
746        .and_then(|v| v.parse().ok())
747        .unwrap_or(0.0);
748    let token_floor = flag_value(args, "--floor")
749        .and_then(|v| v.parse().ok())
750        .unwrap_or_else(|| FootprintConfig::default().token_floor);
751    let mut cfg = FootprintConfig {
752        report: ReportConfig {
753            noninferiority_margin: margin,
754            ..ReportConfig::default()
755        },
756        token_floor,
757    };
758
759    // The footprint under test is what this install actually injects.
760    let project_root = std::env::current_dir()
761        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().into_owned());
762    let footprint = Footprint::live(&project_root);
763
764    if let Some(path) = flag_value(args, "--export") {
765        let json = serde_json::to_string_pretty(&footprint).unwrap_or_default();
766        if let Err(e) = std::fs::write(path, json) {
767            eprintln!("eval footprint: cannot write {path}: {e}");
768            std::process::exit(1);
769        }
770        println!("Footprint exported → {path}");
771        return;
772    }
773    if let Some(path) = flag_value(args, "--compare") {
774        cmd_footprint_compare(args, &suite, &suite_name, path, &footprint, cfg.report);
775        return;
776    }
777
778    let mut report = if let Some(replay) = flag_value(args, "--replay") {
779        let runner = match RecordedRunner::from_file(Path::new(replay)) {
780            Ok(r) => r,
781            Err(e) => {
782                eprintln!("eval footprint: {e:#}");
783                std::process::exit(1);
784            }
785        };
786        run_footprint_or_exit(&suite, &suite_name, &footprint, &runner, &cfg)
787    } else {
788        let live = match OpenAiRunner::from_env() {
789            Ok(r) => r,
790            Err(e) => {
791                eprintln!(
792                    "eval footprint: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
793                );
794                std::process::exit(1);
795            }
796        };
797        cfg.report.live_model = true;
798        if let Some(record_path) = flag_value(args, "--record") {
799            let recorder = RecordingRunner::new(live);
800            let report = run_footprint_or_exit(&suite, &suite_name, &footprint, &recorder, &cfg);
801            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
802                eprintln!("eval footprint: failed to save recording: {e:#}");
803                std::process::exit(1);
804            }
805            println!("Recording saved → {record_path}");
806            report
807        } else {
808            run_footprint_or_exit(&suite, &suite_name, &footprint, &live, &cfg)
809        }
810    };
811
812    let agent_id = crate::core::agent_identity::current_agent_id().to_string();
813    if let Err(e) = report.sign(&agent_id) {
814        eprintln!("eval footprint: signing failed: {e}");
815        std::process::exit(1);
816    }
817
818    let out = match flag_value(args, "--out") {
819        Some(p) => PathBuf::from(p),
820        None => match default_footprint_path() {
821            Ok(p) => p,
822            Err(e) => {
823                eprintln!("eval footprint: {e}");
824                std::process::exit(1);
825            }
826        },
827    };
828    if let Some(parent) = out.parent() {
829        let _ = std::fs::create_dir_all(parent);
830    }
831    if let Err(e) = std::fs::write(&out, report.to_json()) {
832        eprintln!("eval footprint: write {}: {e}", out.display());
833        std::process::exit(1);
834    }
835
836    if has_flag(args, "--json") {
837        println!("{}", report.to_json());
838    } else {
839        println!("{}", report.render());
840        println!("artifact:           {}", out.display());
841    }
842
843    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
844        eprintln!("\nfootprint gate FAILED: a harmful injected element is present");
845        std::process::exit(1);
846    }
847}
848
849fn run_footprint_or_exit(
850    suite: &EvalSuite,
851    suite_name: &str,
852    footprint: &Footprint,
853    runner: &dyn ModelRunner,
854    cfg: &FootprintConfig,
855) -> FootprintReport {
856    match run_footprint_ab(suite, suite_name, footprint, runner, cfg) {
857        Ok(r) => r,
858        Err(e) => {
859            eprintln!("eval footprint: run failed: {e:#}");
860            std::process::exit(1);
861        }
862    }
863}
864
865/// Default footprint artifact location: `<data_dir>/eval/footprint-report-v1_<utc>.json`.
866fn default_footprint_path() -> Result<PathBuf, String> {
867    let dir = crate::core::data_dir::lean_ctx_data_dir()?.join("eval");
868    std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir eval: {e}"))?;
869    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
870    Ok(dir.join(format!("footprint-report-v1_{stamp}.json")))
871}
872
873/// `eval testbench`: run the off-vs-on answer-quality benchmark across every pinned
874/// repo in a lockfile, write `FINDINGS.md` + `regressions.json`, and (with `--gate`)
875/// fail the build if any repo regressed (#611).
876fn cmd_testbench(args: &[String]) {
877    let lock_path = flag_value(args, "--lock").map_or_else(
878        || PathBuf::from("eval/testbench/testbench.lock.json"),
879        PathBuf::from,
880    );
881    let lock = match TestbenchLock::load(&lock_path) {
882        Ok(l) => l,
883        Err(e) => {
884            eprintln!("eval testbench: {e:#}\n(use --lock <file> to point at a lockfile)");
885            std::process::exit(1);
886        }
887    };
888
889    let out_dir =
890        flag_value(args, "--out").map_or_else(|| PathBuf::from("testbench-out"), PathBuf::from);
891    let cache_dir =
892        flag_value(args, "--cache").map_or_else(|| out_dir.join("cache"), PathBuf::from);
893
894    let mut cfg = TestbenchConfig::default();
895    if let Some(b) = flag_value(args, "--budget").and_then(|v| v.parse().ok()) {
896        cfg.run.budget_tokens = b;
897    }
898    cfg.run.report = ReportConfig {
899        noninferiority_margin: flag_value(args, "--margin")
900            .and_then(|v| v.parse().ok())
901            .unwrap_or(0.0),
902        ..ReportConfig::default()
903    };
904
905    let report = if let Some(replay) = flag_value(args, "--replay") {
906        let runner = match RecordedRunner::from_file(Path::new(replay)) {
907            Ok(r) => r,
908            Err(e) => {
909                eprintln!("eval testbench: {e:#}");
910                std::process::exit(1);
911            }
912        };
913        run_testbench_or_exit(&lock, &cache_dir, &runner, &cfg)
914    } else {
915        let live = match OpenAiRunner::from_env() {
916            Ok(r) => r,
917            Err(e) => {
918                eprintln!(
919                    "eval testbench: no live model configured: {e:#}\n(use --replay <file> for an offline run)"
920                );
921                std::process::exit(1);
922            }
923        };
924        cfg.run.report.live_model = true;
925        if let Some(record_path) = flag_value(args, "--record") {
926            let recorder = RecordingRunner::new(live);
927            let report = run_testbench_or_exit(&lock, &cache_dir, &recorder, &cfg);
928            if let Err(e) = recorder.into_recording().save(Path::new(record_path)) {
929                eprintln!("eval testbench: failed to save recording: {e:#}");
930                std::process::exit(1);
931            }
932            println!("Recording saved → {record_path}");
933            report
934        } else {
935            run_testbench_or_exit(&lock, &cache_dir, &live, &cfg)
936        }
937    };
938
939    let (findings_path, regressions_path) = match findings::write(&report, &out_dir) {
940        Ok(paths) => paths,
941        Err(e) => {
942            eprintln!("eval testbench: {e:#}");
943            std::process::exit(1);
944        }
945    };
946
947    print!("{}", findings::render_findings(&report));
948    println!("\nFINDINGS:     {}", findings_path.display());
949    println!("regressions:  {}", regressions_path.display());
950
951    if has_flag(args, "--gate") && !report.gate_passes(has_flag(args, "--mechanism")) {
952        eprintln!("\ntestbench gate FAILED: {}", report.verdict.label());
953        std::process::exit(1);
954    }
955}
956
957fn run_testbench_or_exit(
958    lock: &TestbenchLock,
959    cache_dir: &Path,
960    runner: &dyn ModelRunner,
961    cfg: &TestbenchConfig,
962) -> TestbenchReport {
963    match testbench::run_testbench(lock, cache_dir, runner, cfg) {
964        Ok(r) => r,
965        Err(e) => {
966            eprintln!("eval testbench: run failed: {e:#}");
967            std::process::exit(1);
968        }
969    }
970}
971
972fn cmd_verify(args: &[String]) {
973    let Some(path) = args.first() else {
974        eprintln!("eval verify: <artifact.json> is required");
975        std::process::exit(2);
976    };
977    let artifact = match artifact::load_artifact(Path::new(path)) {
978        Ok(a) => a,
979        Err(e) => {
980            eprintln!("eval verify: {e}");
981            std::process::exit(1);
982        }
983    };
984    let result = artifact.verify();
985    println!("Artifact:           {path}");
986    println!("Verdict:            {}", artifact.verdict.label());
987    println!(
988        "Evidence tier:      {}",
989        artifact.report.evidence_tier.map_or_else(
990            || "UNSPECIFIED (v1 report)".to_string(),
991            |t| format!("{} ({})", t.code(), t.label())
992        )
993    );
994    println!(
995        "Quality claim:      {}",
996        if artifact.report.supports_quality_claim() {
997            "supported (powered, model-backed)"
998        } else {
999            "none"
1000        }
1001    );
1002    println!("Determinism digest: {}", artifact.determinism_digest);
1003    println!(
1004        "Digest matches:     {}",
1005        if result.digest_matches { "yes" } else { "NO" }
1006    );
1007    println!(
1008        "Signature valid:    {}",
1009        if result.signature_valid { "yes" } else { "NO" }
1010    );
1011    if let Some(pk) = &result.signer_public_key {
1012        println!("Signer public key:  {pk}");
1013    }
1014    if let Some(err) = &result.error {
1015        println!("Error:              {err}");
1016    }
1017    if result.ok() {
1018        println!("\nOK — artifact is authentic and internally consistent.");
1019    } else {
1020        eprintln!("\nFAILED — artifact could not be verified.");
1021        std::process::exit(1);
1022    }
1023}
1024
1025fn cmd_init(args: &[String]) {
1026    let dir = PathBuf::from(args.first().map_or("eval-suite", |s| s.as_str()));
1027    match write_starter_suite(&dir) {
1028        Ok(suite) => {
1029            println!("Starter suite written to {}", dir.display());
1030            println!("Suite file: {}", suite.display());
1031            println!("\nNext:");
1032            println!("  # 1) record real model answers once (needs a live model in env)");
1033            println!(
1034                "  lean-ctx eval ab --suite {} --record {}/recording.json",
1035                suite.display(),
1036                dir.display()
1037            );
1038            println!("  # 2) replay deterministically anywhere (CI)");
1039            println!(
1040                "  lean-ctx eval ab --suite {} --replay {}/recording.json --gate",
1041                suite.display(),
1042                dir.display()
1043            );
1044        }
1045        Err(e) => {
1046            eprintln!("eval init: {e:#}");
1047            std::process::exit(1);
1048        }
1049    }
1050}
1051
1052/// Materializes a small, runnable starter suite: one RAG/QA task whose answer lives in the
1053/// corpus, and one POSIX-shell code task with a failing stub + unit test.
1054fn write_starter_suite(dir: &Path) -> anyhow::Result<PathBuf> {
1055    use anyhow::Context;
1056    let corpus = dir.join("corpus");
1057    let code = dir.join("code");
1058    std::fs::create_dir_all(&corpus).context("creating corpus dir")?;
1059    std::fs::create_dir_all(&code).context("creating code dir")?;
1060
1061    std::fs::write(
1062        corpus.join("architecture.md"),
1063        "# Consolidation pipeline\n\n\
1064Provider data flows through one consolidation pipeline. Artifacts are persisted to four \
1065stores: the BM25 index, the Graph index, ProjectKnowledge, and the Session cache. This is \
1066what lets semantic search, knowledge recall, and cross-source hints share one source of truth.\n",
1067    )
1068    .context("writing corpus/architecture.md")?;
1069    std::fs::write(
1070        corpus.join("overview.md"),
1071        "# Overview\n\nlean-ctx is a context runtime for AI agents. This file is general \
1072background and intentionally does not list the consolidation stores.\n",
1073    )
1074    .context("writing corpus/overview.md")?;
1075
1076    std::fs::write(
1077        code.join("test.sh"),
1078        "#!/bin/sh\n. ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ] || exit 1\n[ \"$(add 10 20)\" = \"30\" ] || exit 1\n",
1079    )
1080    .context("writing code/test.sh")?;
1081    std::fs::write(
1082        code.join("solution.sh"),
1083        "# TODO: implement add() so that `add a b` prints a+b\nadd() { echo 0; }\n",
1084    )
1085    .context("writing code/solution.sh")?;
1086
1087    let suite = dir.join("suite.ndjson");
1088    let lines = [
1089        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"]}"#,
1090        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"}"#,
1091    ];
1092    std::fs::write(
1093        &suite,
1094        format!("# lean-ctx eval starter suite\n{}\n", lines.join("\n")),
1095    )
1096    .context("writing suite.ndjson")?;
1097    Ok(suite)
1098}
1099
1100#[cfg(test)]
1101mod recording_guard_tests {
1102    use super::*;
1103
1104    #[test]
1105    fn arm_study_provider_flags_are_explicit_complete_and_unique() {
1106        let strings = |values: &[&str]| values.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
1107        assert_eq!(
1108            arm_study_provider_args(&strings(&["--protocol", "p", "--observations", "o"])),
1109            Ok(None)
1110        );
1111        let pairs = [
1112            ["--provider-report", "report.json"],
1113            ["--provider-arm", "team"],
1114            ["--provider-condition", "lean_ctx"],
1115        ];
1116        let valid = pairs
1117            .iter()
1118            .flatten()
1119            .map(|s| (*s).to_owned())
1120            .collect::<Vec<_>>();
1121        assert_eq!(
1122            arm_study_provider_args(&valid),
1123            Ok(Some(("report.json", Arm::Team, ProviderCondition::LeanCtx)))
1124        );
1125        for mask in 1..7 {
1126            let mut args = Vec::new();
1127            for (index, pair) in pairs.iter().enumerate() {
1128                if mask & (1 << index) != 0 {
1129                    args.extend(pair.iter().map(|s| (*s).to_owned()));
1130                }
1131            }
1132            assert!(arm_study_provider_args(&args).is_err());
1133        }
1134        for pair in pairs {
1135            let mut duplicated = valid.clone();
1136            duplicated.extend(pair.map(str::to_owned));
1137            assert!(arm_study_provider_args(&duplicated).is_err());
1138        }
1139        for bad in [
1140            vec!["--provider-report"],
1141            vec!["--provider-report", "--provider-arm", "team"],
1142            vec!["--provider-report", ""],
1143            vec!["--provider-arm=team"],
1144            vec![
1145                "--provider-report",
1146                "r",
1147                "--provider-arm",
1148                "baseline",
1149                "--provider-condition",
1150                "lean_ctx",
1151            ],
1152            vec![
1153                "--provider-report",
1154                "r",
1155                "--provider-arm",
1156                "team",
1157                "--provider-condition",
1158                "company",
1159            ],
1160        ] {
1161            assert!(arm_study_provider_args(&strings(&bad)).is_err());
1162        }
1163        for (name, arm) in [
1164            ("unchanged_agent", Arm::UnchangedAgent),
1165            ("community", Arm::Community),
1166            ("team", Arm::Team),
1167            ("company", Arm::Company),
1168        ] {
1169            assert_eq!(
1170                arm_study_provider_args(&strings(&[
1171                    "--provider-report",
1172                    "r",
1173                    "--provider-arm",
1174                    name,
1175                    "--provider-condition",
1176                    "baseline",
1177                ])),
1178                Ok(Some(("r", arm, ProviderCondition::Baseline)))
1179            );
1180        }
1181    }
1182
1183    /// The arm-study inputs: the exact bytes of a regular file at its bound, and
1184    /// a refusal — never a truncation, a followed link or a wait — for anything else.
1185    #[cfg(unix)]
1186    #[test]
1187    fn arm_study_input_is_a_bounded_regular_file_and_nothing_else() {
1188        use std::ffi::CString;
1189        use std::os::unix::ffi::OsStrExt;
1190        let dir = tempfile::tempdir().unwrap();
1191        let regular = dir.path().join("exact");
1192        std::fs::write(&regular, b"12345678").unwrap();
1193        assert_eq!(bounded_regular_file(&regular, 8).unwrap(), b"12345678");
1194        assert_eq!(
1195            bounded_regular_file(&regular, 7),
1196            Err("exceeds its size bound")
1197        );
1198        let link = dir.path().join("link");
1199        std::os::unix::fs::symlink(&regular, &link).unwrap();
1200        let fifo = dir.path().join("fifo");
1201        let name = CString::new(fifo.as_os_str().as_bytes()).unwrap();
1202        // SAFETY: a NUL-terminated path inside this test's own directory.
1203        assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);
1204        let not_opened = "cannot be opened as a file that is not a link";
1205        for (path, refusal) in [
1206            (link, not_opened),
1207            // Opened without waiting for a writer, then refused for what it is.
1208            (fifo, "is not a regular file"),
1209            (dir.path().to_path_buf(), "is not a regular file"),
1210            (dir.path().join("absent"), not_opened),
1211        ] {
1212            assert_eq!(
1213                bounded_regular_file(&path, 8),
1214                Err(refusal),
1215                "{}",
1216                path.display()
1217            );
1218        }
1219    }
1220
1221    /// The committed recording (`rust/eval/recording.json`) is what flips the CI
1222    /// quality-gate from "skipped" to "enforced" (#361 Phase 3). Guard it
1223    /// **in-process** so a suite/corpus/prompt change that invalidates the
1224    /// recording (a replay key miss) or a captured regression fails here in
1225    /// `cargo test` — i.e. during `dev-install` — not only in CI.
1226    #[test]
1227    fn committed_recording_replays_and_passes_gate() {
1228        let dir = tempfile::tempdir().unwrap();
1229        let suite_path = write_starter_suite(dir.path()).expect("scaffold starter suite");
1230        let suite = EvalSuite::load(&suite_path).expect("load starter suite");
1231
1232        let rec_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("eval/recording.json");
1233        assert!(
1234            rec_path.exists(),
1235            "committed recording missing at {} — CI quality-gate would silently skip",
1236            rec_path.display()
1237        );
1238        let runner = RecordedRunner::from_file(&rec_path).expect("load committed recording");
1239
1240        // Every (task × condition) request must hit a recorded key, else the
1241        // recording drifted from the suite/corpus/prompt and must be re-captured.
1242        let report = run_ab(&suite, "suite.ndjson", &runner, &AbRunConfig::default())
1243            .expect("committed recording must cover every replay key");
1244        assert!(
1245            report.verdict.mechanism_gate_passes(),
1246            "committed recording must not encode a regression, got: {}",
1247            report.verdict.label()
1248        );
1249    }
1250}