Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

75.6 KB
Raw Blame
//! `app record` and `app replay` on the same small CLI written in each of the six languages.
//!
//! Each test copies its fixture to a temp folder, records the original, replays the original
//! (everything matches), then replays a build whose division-by-zero message changed (only those
//! cases fail, with a diff in the report). A test is skipped when its runtime is missing.

mod common;

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

use rust_anything::app::{self, RecordOptions, ReplayOptions};
use rust_anything::drift::{self, DriftOptions};
use rust_anything::front_door::{self, FrontDoorOptions, WireOptions};
use rust_anything::lift::{self, LiftOptions};
use rust_anything::walk::Canonical;

fn copy_dir(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap().flatten() {
        let target = to.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_dir(&entry.path(), &target);
        } else {
            std::fs::copy(entry.path(), &target).unwrap();
        }
    }
}

fn fixture(lang: &str) -> PathBuf {
    static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let repo = std::env::temp_dir().join(format!(
        "rust-anything-app-test-{lang}-{}-{n}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&repo);
    copy_dir(
        &Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/cli")
            .join(lang),
        &repo,
    );
    repo
}

fn sh(repo: &Path, program: &str, args: &[&str]) {
    let out = Command::new(program)
        .args(args)
        .current_dir(repo)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{program} {args:?}: {}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

fn add_bug(repo: &Path, source: &str, copy_to: Option<&str>) {
    let text = std::fs::read_to_string(repo.join(source)).unwrap();
    assert!(text.contains("division by zero"));
    std::fs::write(
        repo.join(copy_to.unwrap_or(source)),
        text.replace("division by zero", "divide by zero"),
    )
    .unwrap();
}

fn words(line: &str) -> Vec<String> {
    line.split_whitespace().map(str::to_string).collect()
}

fn record_then_replay(repo: &Path, run: &str, buggy: &str) {
    let outcome = app::record(&RecordOptions {
        repo,
        run: &words(run),
        inputs: None,
        normalize: &[],
        name: None,
        traps: true,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    assert_eq!(outcome.examples, 7, "{outcome:?}");
    assert!(outcome.traps > 30, "{outcome:?}");
    assert!(outcome.unstable.is_empty(), "{outcome:?}");
    assert!(outcome.timed_out.is_empty(), "{outcome:?}");
    assert_eq!(outcome.noisy, ["example-006-now"], "{outcome:?}");

    let dir = app::cases_dir(repo);
    let read = |name: &str| std::fs::read_to_string(dir.join(name)).unwrap();
    assert_eq!(
        read("example-006-now.stdout").lines().collect::<Vec<_>>(),
        ["now: [..]"]
    );
    let div = read("example-003-div.toml");
    assert!(div.contains("args = [\"div\", \"7\", \"2\"]"), "{div}");
    assert!(div.contains("status.code = 0"), "{div}");
    assert_eq!(
        read("example-003-div.stdout").lines().collect::<Vec<_>>(),
        ["7 / 2 = 3 remainder 1"]
    );
    assert_eq!(read("example-004-words.stdin"), "one two three\n");
    assert_eq!(
        read("example-004-words.stdout").lines().collect::<Vec<_>>(),
        ["3"]
    );
    assert!(dir.join("example-005-copy.in/input.txt").is_file());
    assert!(
        read("example-005-copy.out/out.txt").starts_with("GR"),
        "the copy wrote its output file"
    );
    assert!(read("example-007-nope.toml").contains("status.code = 1"));
    assert!(read("example-007-nope.stderr").starts_with("usage: tcli"));

    let original = app::replay(&ReplayOptions {
        case: None,
        repo,
        build: None,
        timeout_secs: None,
        port: None,
    })
    .unwrap();
    assert_eq!(original.total, outcome.cases);
    assert_eq!(
        original.passed,
        original.total,
        "{}",
        std::fs::read_to_string(&original.report).unwrap()
    );
    assert!(original.fallback.is_none());

    let bug = app::replay(&ReplayOptions {
        case: None,
        repo,
        build: Some(buggy),
        timeout_secs: None,
        port: None,
    })
    .unwrap();
    assert!(!bug.failures.is_empty());
    assert_eq!(bug.passed + bug.failures.len(), bug.total);
    for f in &bug.failures {
        assert_eq!(f.args[0], "div", "{f:?}");
        assert!(f.problems.iter().all(|p| p.field == "stderr"), "{f:?}");
    }
    let report = std::fs::read_to_string(&bug.report).unwrap();
    assert!(report.contains("- error: division by zero"), "{report}");
    assert!(report.contains("+ error: divide by zero"), "{report}");

    let one = app::replay(&ReplayOptions {
        case: Some(&bug.failures[0].case),
        repo,
        build: Some(buggy),
        timeout_secs: None,
        port: None,
    })
    .unwrap();
    assert_eq!((one.total, one.failures.len()), (1, 1));
    let missing = app::replay(&ReplayOptions {
        case: Some("no-such-case"),
        repo,
        build: None,
        timeout_secs: None,
        port: None,
    });
    assert!(missing.unwrap_err().to_string().contains("no case named"));

    front_door_then_wire(repo);
    std::fs::remove_dir_all(repo).unwrap();
}

const WORDCOUNT_PORT: &str = "pub fn count_words(text: &[u8]) -> usize {
    text.split(|b| b.is_ascii_whitespace() || *b == 0x0b)
        .filter(|w| !w.is_empty())
        .count()
}
";

const WORDCOUNT_GLUE: &str = "use std::io::Read;
use std::process::ExitCode;

use clap::ArgMatches;

pub fn run(_command: &str, _matches: &ArgMatches) -> ExitCode {
    let mut input = Vec::new();
    if std::io::stdin().read_to_end(&mut input).is_err() {
        return ExitCode::from(1);
    }
    println!(\"{}\", wordcount_rs::port::count_words(&input));
    ExitCode::SUCCESS
}
";

const WORDCOUNT_DECLINING_GLUE: &str = "use std::io::Read;
use std::process::ExitCode;

use clap::ArgMatches;

pub fn run(_command: &str, _matches: &ArgMatches) -> ExitCode {
    let mut input = Vec::new();
    if std::io::stdin().read_to_end(&mut input).is_err() {
        return ExitCode::from(1);
    }
    if input.starts_with(b\"#original\") {
        let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
        return crate::original::run_with_stdin(&argv[1..], &input);
    }
    println!(\"{}\", wordcount_rs::port::count_words(&input));
    ExitCode::SUCCESS
}
";

/// The front door answers everything through the original; then a unit takes over `words`.
fn front_door_then_wire(repo: &Path) {
    let door = front_door::front_door(&FrontDoorOptions {
        repo,
        library: false,
        check: true,
        commands: &[],
    })
    .unwrap();
    assert_eq!(
        door.commands,
        ["copy", "div", "len", "now", "upper", "words"]
    );
    let replay = door.replay.unwrap();
    assert_eq!(replay.passed, replay.total, "{:?}", replay.failures);
    let fallback = replay.fallback.as_ref().unwrap();
    assert_eq!(fallback.cases, replay.total);
    let app_dir = repo.join(front_door::APP_DIR);
    if common::have("cargo") {
        sh(&app_dir, "cargo", &["fmt", "--check"]);
    }

    let unit = repo.join("rust/wordcount-rs");
    std::fs::create_dir_all(unit.join("src")).unwrap();
    std::fs::write(
        unit.join("Cargo.toml"),
        "[package]\nname = \"wordcount-rs\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n",
    )
    .unwrap();
    std::fs::write(unit.join("src/lib.rs"), "pub mod port;\n").unwrap();
    std::fs::write(unit.join("src/port.rs"), WORDCOUNT_PORT).unwrap();
    let wire = |commands: &[String]| {
        front_door::wire(&WireOptions {
            repo,
            unit: "wordcount-rs",
            commands,
            routes: &[],
            skip_gate: true,
            check: true,
        })
        .unwrap()
    };

    let stub = wire(&["words".to_string()]);
    assert!(stub.glue_pending);
    assert_eq!(stub.switch, "RUST_ANYTHING_UNIT_WORDCOUNT");
    let failing = stub.replay.unwrap();
    assert!(!failing.failures.is_empty());
    assert!(
        failing.failures.iter().all(|f| f.args[0] == "words"),
        "{:?}",
        failing.failures
    );

    std::fs::write(&stub.glue, WORDCOUNT_DECLINING_GLUE).unwrap();
    let wired = wire(&[]);
    assert!(!wired.glue_pending);
    assert_eq!(wired.commands, ["words"]);
    let replay = wired.replay.unwrap();
    assert_eq!(
        replay.passed,
        replay.total,
        "{}",
        std::fs::read_to_string(&replay.report).unwrap()
    );
    if common::have("cargo") {
        sh(&app_dir, "cargo", &["fmt", "--check"]);
        sh(
            &app_dir,
            "cargo",
            &["clippy", "--all-targets", "--", "-D", "warnings"],
        );
    }
    let fallback = replay.fallback.as_ref().unwrap();
    assert!(fallback.cases < fallback.total, "{fallback:?}");
    assert!(fallback.cases >= fallback.total - 5, "{fallback:?}");

    let exe = &replay.build[0];
    let log = repo.join("fallback.log");
    let run = |switch: Option<(&str, &str)>, input: &[u8]| {
        let _ = std::fs::remove_file(&log);
        let mut cmd = Command::new(exe);
        cmd.arg("words")
            .env(rust_anything::app::FALLBACK_ENV, &log)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped());
        if let Some((name, value)) = switch {
            cmd.env(name, value);
        }
        let mut child = cmd.spawn().unwrap();
        child.stdin.take().unwrap().write_all(input).unwrap();
        let out = child.wait_with_output().unwrap();
        assert!(out.status.success());
        assert_eq!(
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .collect::<Vec<_>>(),
            ["3"]
        );
        std::fs::read_to_string(&log).unwrap()
    };
    assert_eq!(run(None, b"one two  three\n"), "", "Rust answered");
    assert_eq!(
        run(
            Some(("RUST_ANYTHING_UNIT_WORDCOUNT", "original")),
            b"one two  three\n"
        ),
        "words\n",
        "the kill switch fell back"
    );
    assert_eq!(
        run(Some(("RUST_ANYTHING_MODE", "old")), b"one two  three\n"),
        "words\n",
        "RUST_ANYTHING_MODE=old ran the original"
    );
    assert_eq!(
        run(None, b"#original two three\n"),
        "words\n",
        "the glue declined and passed stdin on"
    );
}

#[test]
fn ts_cli_records_and_replays() {
    if !common::have("node") {
        return;
    }
    let repo = fixture("ts");
    add_bug(&repo, "tcli.js", Some("tcli-bug.js"));
    record_then_replay(&repo, "node tcli.js", "node tcli-bug.js");
}

#[test]
fn python_cli_records_and_replays() {
    if !common::have("python3") {
        return;
    }
    let repo = fixture("python");
    add_bug(&repo, "tcli.py", Some("tcli_bug.py"));
    record_then_replay(&repo, "python3 tcli.py", "python3 tcli_bug.py");
}

#[test]
fn c_cli_records_and_replays() {
    if !common::have("cc") {
        return;
    }
    let repo = fixture("c");
    sh(&repo, "cc", &["-O1", "-o", "tcli", "tcli.c"]);
    add_bug(&repo, "tcli.c", Some("tcli-bug.c"));
    sh(&repo, "cc", &["-O1", "-o", "tcli-bug", "tcli-bug.c"]);
    record_then_replay(&repo, "./tcli", "./tcli-bug");
}

#[test]
fn go_cli_records_and_replays() {
    if !common::have("go") {
        return;
    }
    let repo = fixture("go");
    sh(&repo, "go", &["build", "-o", "tcli", "."]);
    add_bug(&repo, "main.go", None);
    sh(&repo, "go", &["build", "-o", "tcli-bug", "."]);
    record_then_replay(&repo, "./tcli", "./tcli-bug");
}

#[test]
fn ruby_cli_records_and_replays() {
    if !common::have("ruby") {
        return;
    }
    let repo = fixture("ruby");
    add_bug(&repo, "tcli.rb", Some("tcli_bug.rb"));
    record_then_replay(&repo, "ruby tcli.rb", "ruby tcli_bug.rb");
}

#[test]
fn php_cli_records_and_replays() {
    if !common::have("php") {
        return;
    }
    let repo = fixture("php");
    add_bug(&repo, "tcli.php", Some("tcli_bug.php"));
    record_then_replay(&repo, "php tcli.php", "php tcli_bug.php");
}

#[test]
fn java_cli_records_and_replays() {
    if !common::have("javac") || !common::have("java") {
        return;
    }
    let repo = fixture("java");
    sh(&repo, "javac", &["-d", "classes", "Tcli.java"]);
    add_bug(&repo, "Tcli.java", None);
    sh(&repo, "javac", &["-d", "classes-bug", "Tcli.java"]);
    record_then_replay(
        &repo,
        "java -XX:-UsePerfData -cp ./classes Tcli",
        "java -XX:-UsePerfData -cp ./classes-bug Tcli",
    );
}

fn dotnet_build(repo: &Path, out: &str) {
    sh(
        repo,
        "dotnet",
        &["build", "-c", "Release", "--nologo", "-v", "q", "-o", out],
    );
}

#[test]
fn csharp_cli_records_and_replays() {
    if !common::have("dotnet") {
        return;
    }
    let repo = fixture("csharp");
    dotnet_build(&repo, "out");
    add_bug(&repo, "Program.cs", None);
    dotnet_build(&repo, "out-bug");
    record_then_replay(&repo, "dotnet out/tcli.dll", "dotnet out-bug/tcli.dll");
}

#[test]
fn the_command_exits_non_zero_on_a_mismatch() {
    if !common::have("python3") {
        return;
    }
    let repo = fixture("python");
    add_bug(&repo, "tcli.py", Some("tcli_bug.py"));
    std::fs::write(
        repo.join("inputs.jsonl"),
        "{\"name\": \"stamped\", \"args\": [\"upper\", \"at 2026-11-16T10:00:00Z\"]}\n\
         {\"args\": [\"copy\", \"a.txt\", \"b.txt\"], \"files\": {\"a.txt\": \"x\"}}\n\
         {\"args\": [\"div\", \"1\", \"0\"]}\n",
    )
    .unwrap();
    let record = common::cli()
        .args(["app", "record"])
        .arg(&repo)
        .args([
            "--no-traps",
            "--inputs",
            "inputs.jsonl",
            "--normalize",
            "timestamps",
            "--",
            "python3",
            "tcli.py",
        ])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(
        record.status.success(),
        "{}",
        String::from_utf8_lossy(&record.stderr)
    );
    let dir = app::cases_dir(&repo);
    assert_eq!(
        std::fs::read_to_string(dir.join("stamped.stdout"))
            .unwrap()
            .lines()
            .collect::<Vec<_>>(),
        ["AT [..]"]
    );
    assert_eq!(
        std::fs::read_to_string(dir.join("input-002-copy.out/b.txt")).unwrap(),
        "X"
    );
    let config = std::fs::read_to_string(dir.join(app::CONFIG_FILE)).unwrap();
    assert!(config.contains("\"timestamps\""), "{config}");

    let replay = |build: Option<&str>| {
        let mut cmd = common::cli();
        cmd.args(["app", "replay"]).arg(&repo);
        if let Some(b) = build {
            cmd.args(["--build", b]);
        }
        cmd.output().unwrap()
    };
    let good = replay(None);
    assert!(good.status.success());
    assert!(String::from_utf8_lossy(&good.stdout).starts_with("10/10 cases passed"));
    let bad = replay(Some("python3 tcli_bug.py"));
    assert_eq!(bad.status.code(), Some(1));
    let text = String::from_utf8_lossy(&bad.stdout);
    assert!(text.starts_with("9/10 cases passed"), "{text}");
    assert!(text.contains("- input-003-div: stderr"), "{text}");
    std::fs::remove_dir_all(&repo).unwrap();
}

fn write_unit(repo: &Path, name: &str, port: &str) {
    let unit = repo.join("rust").join(name);
    std::fs::create_dir_all(unit.join("src")).unwrap();
    std::fs::write(
        unit.join("Cargo.toml"),
        format!(
            "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n"
        ),
    )
    .unwrap();
    std::fs::write(unit.join("src/lib.rs"), "pub mod port;\n").unwrap();
    std::fs::write(unit.join("src/port.rs"), port).unwrap();
}

/// Issue #1477: a front door that answers commands in Rust before `units::dispatch` never reaches a
/// wired unit, and a helper cannot be wired on its own. `wire` and `lift` say so instead of
/// wiring a unit nothing calls.
#[test]
fn wire_requires_whole_command_routing_and_says_so() {
    let repo = fixture("python");
    app::record(&RecordOptions {
        repo: &repo,
        run: &words("python3 tcli.py"),
        inputs: None,
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    front_door::front_door(&FrontDoorOptions {
        repo: &repo,
        library: false,
        check: false,
        commands: &[],
    })
    .unwrap();
    write_unit(&repo, "helpers-rs", WORDCOUNT_PORT);

    let blocked = lift::lift(&LiftOptions { repo: &repo }).unwrap();
    let blocker = blocked
        .blockers
        .iter()
        .find(|b| b.contains("no unit is wired"))
        .unwrap_or_else(|| panic!("{:?}", blocked.blockers));
    assert!(
        blocker.contains("whole commands") && blocker.contains("glue"),
        "{blocker}"
    );

    let wire = |commands: &[&str]| {
        front_door::wire(&WireOptions {
            repo: &repo,
            unit: "helpers",
            commands: &commands.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
            routes: &[],
            skip_gate: true,
            check: false,
        })
    };
    let unnamed = format!("{:#}", wire(&[]).unwrap_err());
    assert!(
        unnamed.contains("--command") && unnamed.contains("hands whole commands"),
        "{unnamed}"
    );

    let main = repo.join("rust/app/src/main.rs");
    std::fs::write(
        &main,
        "mod cli;\nmod original;\nmod units;\n\nfn main() -> std::process::ExitCode {\n    \
         let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();\n    \
         original::run(&argv[1..])\n}\n",
    )
    .unwrap();
    let native = format!("{:#}", wire(&["words"]).unwrap_err());
    assert!(
        native.contains("never calls `units::dispatch`")
            && native.contains("move its Rust code into the glue"),
        "{native}"
    );
    std::fs::remove_dir_all(&repo).unwrap();
}

/// How the original counts and uppercases: a faithful port matches its own language.
struct Semantics {
    count: &'static str,
    upper: &'static str,
    unit: &'static str,
}

const CHARS: Semantics = Semantics {
    count: "Count::Chars",
    upper: "Upper::Full",
    unit: "characters",
};

fn textops_port(s: &Semantics) -> String {
    format!(
        "pub enum Count {{
    Chars,
    Bytes,
}}

pub enum Upper {{
    Full,
    Simple,
    Ascii,
}}

pub const COUNT: Count = {};
pub const UPPER: Upper = {};
pub const UNIT: &str = {:?};

pub fn upper(text: &str) -> String {{
    match UPPER {{
        Upper::Full => text.to_uppercase(),
        Upper::Simple => text
            .chars()
            .map(|c| {{
                let mut up = c.to_uppercase();
                match (up.next(), up.next()) {{
                    (Some(u), None) => u,
                    _ => c,
                }}
            }})
            .collect(),
        Upper::Ascii => text.to_ascii_uppercase(),
    }}
}}

pub fn count(text: &str) -> usize {{
    match COUNT {{
        Count::Chars => text.chars().count(),
        Count::Bytes => text.len(),
    }}
}}

pub fn div(a: i64, b: i64) -> Option<(i64, i64)> {{
    (b != 0).then(|| (a / b, a % b))
}}
",
        s.count, s.upper, s.unit
    )
}

const TEXTOPS_GLUE: &str = "use std::ffi::OsString;
use std::process::ExitCode;
use std::time::{SystemTime, UNIX_EPOCH};

use clap::ArgMatches;
use textops_rs::port;

pub fn run(command: &str, matches: &ArgMatches) -> ExitCode {
    let args: Vec<String> = matches
        .get_many::<OsString>(\"args\")
        .into_iter()
        .flatten()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    match (command, args.as_slice()) {
        (\"upper\", words) => {
            println!(\"{}\", port::upper(&words.join(\" \")));
            ExitCode::SUCCESS
        }
        (\"len\", [text]) => {
            println!(\"{}\", port::count(text));
            ExitCode::SUCCESS
        }
        (\"div\", [a, b]) => match (a.parse::<i64>(), b.parse::<i64>()) {
            (Ok(a), Ok(b)) => match port::div(a, b) {
                Some((q, r)) => {
                    println!(\"{a} / {b} = {q} remainder {r}\");
                    ExitCode::SUCCESS
                }
                None => {
                    eprintln!(\"error: division by zero\");
                    ExitCode::from(2)
                }
            },
            _ => {
                eprintln!(\"error: not a number\");
                ExitCode::from(2)
            }
        },
        (\"copy\", [from, to]) => {
            let Ok(text) = std::fs::read_to_string(from) else {
                eprintln!(\"error: cannot read {from}\");
                return ExitCode::from(1);
            };
            if std::fs::write(to, port::upper(&text)).is_err() {
                eprintln!(\"error: cannot write {to}\");
                return ExitCode::from(1);
            }
            println!(\"copied {} {}\", port::count(&text), port::UNIT);
            ExitCode::SUCCESS
        }
        (\"now\", _) => {
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos());
            println!(\"now: {nanos}\");
            ExitCode::SUCCESS
        }
        _ => {
            eprintln!(\"usage: tcli upper|len|div|words|copy|now\");
            ExitCode::from(1)
        }
    }
}
";

/// Record, front door, wire every command to Rust, lift, then replay the pure binary with the
/// original moved away: nothing may still need it.
fn lift_end_to_end(repo: &Path, run: &str, semantics: &Semantics, original: &str) {
    app::record(&RecordOptions {
        repo,
        run: &words(run),
        inputs: None,
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    let door = front_door::front_door(&FrontDoorOptions {
        repo,
        library: false,
        check: true,
        commands: &[],
    })
    .unwrap();
    let replay = door.replay.unwrap();
    assert_eq!(replay.passed, replay.total);
    assert_eq!(replay.fallback.unwrap().cases, replay.total);

    let blocked = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(!blocked.lifted);
    assert!(
        blocked
            .blockers
            .iter()
            .any(|b| b.contains("no unit is wired")),
        "{:?}",
        blocked.blockers
    );

    write_unit(repo, "wordcount-rs", WORDCOUNT_PORT);
    write_unit(repo, "textops-rs", &textops_port(semantics));
    let wire = |unit: &str, commands: &[&str], check: bool| {
        front_door::wire(&WireOptions {
            repo,
            unit,
            commands: &commands.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
            routes: &[],
            skip_gate: true,
            check,
        })
        .unwrap()
    };
    let words_glue = wire("wordcount", &["words"], false).glue;
    std::fs::write(&words_glue, WORDCOUNT_DECLINING_GLUE).unwrap();
    let partial = wire("textops", &["upper", "len"], true);
    let fallback = partial.replay.unwrap().fallback.unwrap();
    assert!(fallback.cases > 0);
    let blocked = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(!blocked.lifted);
    assert!(
        blocked
            .blockers
            .iter()
            .any(|b| b.contains("the glue in") && b.contains("textops")),
        "{:?}",
        blocked.blockers
    );
    assert!(
        blocked
            .blockers
            .iter()
            .any(|b| b.contains("wordcount") && b.contains("hands cases to the original")),
        "{:?}",
        blocked.blockers
    );
    std::fs::write(&words_glue, WORDCOUNT_GLUE).unwrap();
    std::fs::write(&partial.glue, TEXTOPS_GLUE).unwrap();
    let blocked = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(
        blocked
            .blockers
            .iter()
            .any(|b| b.contains("still fall back") && b.contains("example-003-div")),
        "{:?}",
        blocked.blockers
    );

    let all = wire(
        "textops",
        &["upper", "len", "div", "copy", "now", "tcli"],
        true,
    );
    let replay = all.replay.unwrap();
    assert_eq!(replay.passed, replay.total, "{:?}", replay.failures);
    assert_eq!(replay.fallback.unwrap().cases, 0);
    for dir in ["rust/app", "rust/wordcount-rs", "rust/textops-rs"] {
        sh(&repo.join(dir), "cargo", &["fmt"]);
    }

    // Everything is wired and replays, but what the original offers is still undecided: the lift
    // is refused for that alone, and each line says which command unblocks it.
    let undecided = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(!undecided.lifted);
    assert!(
        !undecided.blockers.is_empty()
            && undecided
                .blockers
                .iter()
                .all(|b| b.contains("rust-anything obligations")),
        "{:?}",
        undecided.blockers
    );
    // A decisions file that cannot be read is a blocker too, never a silent "nothing blocks".
    let decisions = repo.join("rust/obligations-decisions.toml");
    std::fs::write(&decisions, "this is [not toml\n").unwrap();
    let unreadable = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(!unreadable.lifted);
    assert!(
        unreadable.blockers.iter().any(|b| b.contains(
            "the obligations could not be checked: invalid rust/obligations-decisions.toml"
        )),
        "{:?}",
        unreadable.blockers
    );
    std::fs::remove_file(&decisions).unwrap();
    common::decide_obligations(repo);

    let lifted = lift::lift(&LiftOptions { repo }).unwrap();
    assert!(lifted.lifted, "{:?}", lifted.blockers);
    assert!(
        lifted.checklist.iter().all(|i| i.mark != lift::Mark::Fail),
        "{:?}",
        lifted.checklist
    );
    assert!(
        lifted
            .checklist
            .iter()
            .any(|i| i.name == "rust/app: cargo test" && i.mark == lift::Mark::Pass)
    );
    let replay = lifted.replay.as_ref().unwrap();
    assert_eq!(replay.passed, replay.total);

    let app_dir = repo.join(front_door::APP_DIR);
    assert!(!app_dir.join("src/original.rs").exists());
    let main = std::fs::read_to_string(app_dir.join("src/main.rs")).unwrap();
    assert!(!main.contains("original"), "{main}");
    let units = std::fs::read_to_string(app_dir.join("src/units/mod.rs")).unwrap();
    assert!(!units.contains("RUST_ANYTHING_UNIT"), "{units}");
    assert!(app_dir.join("tests/app_cases.rs").is_file());
    for unit in ["wordcount-rs", "textops-rs"] {
        let cargo =
            std::fs::read_to_string(repo.join("rust").join(unit).join("Cargo.toml")).unwrap();
        assert!(!cargo.contains("cdylib"), "{cargo}");
    }
    assert!(front_door::State::load(repo).unwrap().lifted);

    let hidden = repo.join(format!("{original}.hidden"));
    std::fs::rename(repo.join(original), &hidden).unwrap();
    let pure = app::replay(&ReplayOptions {
        case: None,
        repo,
        build: Some(&lifted.binary.as_ref().unwrap().to_string_lossy()),
        timeout_secs: None,
        port: None,
    })
    .unwrap();
    assert_eq!(
        pure.passed,
        pure.total,
        "{}",
        std::fs::read_to_string(&pure.report).unwrap()
    );
    assert!(
        pure.fallback.is_none(),
        "the pure binary has no fallback hook"
    );
    std::fs::rename(&hidden, repo.join(original)).unwrap();

    let again = lift::lift(&LiftOptions { repo });
    assert!(again.is_err());
    let rewire = front_door::wire(&WireOptions {
        repo,
        unit: "wordcount",
        commands: &[],
        routes: &[],
        skip_gate: true,
        check: false,
    });
    assert!(rewire.is_err());

    // Each wire and the one lift that happened are in the audit log; refused lifts and the
    // failed rewire changed nothing and are not.
    let log = rust_anything::audit::read(repo).unwrap();
    let changes: Vec<&str> = log.entries.iter().map(|e| e.change.as_str()).collect();
    assert_eq!(
        changes,
        ["wire", "wire", "wire", "lift"],
        "{:?}",
        log.entries
    );
    let wired = &log.entries[2];
    assert_eq!(wired.command, "app wire");
    assert_eq!(wired.crate_dir.as_deref(), Some("rust/textops-rs"));
    assert_eq!(wired.routes, ["upper", "len", "div", "copy", "now", "tcli"]);
    assert!(wired.skipped_gate);
    let lift = &log.entries[3];
    assert_eq!(lift.command, "app lift");
    assert_eq!(lift.units.len(), 2, "{lift:?}");
    let cases = lift.cases.unwrap();
    assert_eq!(cases.matched, cases.total);
    std::fs::remove_dir_all(repo).unwrap();
}

#[test]
fn ts_cli_lifts_to_pure_rust() {
    if !common::have("node") || !common::have("cargo") {
        return;
    }
    lift_end_to_end(&fixture("ts"), "node tcli.js", &CHARS, "tcli.js");
}

#[test]
fn python_cli_lifts_to_pure_rust() {
    if !common::have("python3") || !common::have("cargo") {
        return;
    }
    lift_end_to_end(&fixture("python"), "python3 tcli.py", &CHARS, "tcli.py");
}

#[test]
fn c_cli_lifts_to_pure_rust() {
    if !common::have("cc") || !common::have("cargo") {
        return;
    }
    let repo = fixture("c");
    sh(&repo, "cc", &["-O1", "-o", "tcli", "tcli.c"]);
    let bytes = Semantics {
        count: "Count::Bytes",
        upper: "Upper::Ascii",
        unit: "bytes",
    };
    lift_end_to_end(&repo, "./tcli", &bytes, "tcli");
}

#[test]
fn go_cli_lifts_to_pure_rust() {
    if !common::have("go") || !common::have("cargo") {
        return;
    }
    let repo = fixture("go");
    sh(&repo, "go", &["build", "-o", "tcli", "."]);
    let go = Semantics {
        count: "Count::Bytes",
        upper: "Upper::Simple",
        unit: "bytes",
    };
    lift_end_to_end(&repo, "./tcli", &go, "tcli");
}

#[test]
fn php_cli_lifts_to_pure_rust() {
    if !common::have("php") || !common::have("cargo") {
        return;
    }
    lift_end_to_end(&fixture("php"), "php tcli.php", &CHARS, "tcli.php");
}

#[test]
fn ruby_cli_lifts_to_pure_rust() {
    if !common::have("ruby") || !common::have("cargo") {
        return;
    }
    lift_end_to_end(&fixture("ruby"), "ruby tcli.rb", &CHARS, "tcli.rb");
}

#[test]
fn java_cli_lifts_to_pure_rust() {
    if !common::have("javac") || !common::have("java") || !common::have("cargo") {
        return;
    }
    let repo = fixture("java");
    sh(&repo, "javac", &["-d", "classes", "Tcli.java"]);
    lift_end_to_end(
        &repo,
        "java -XX:-UsePerfData -cp ./classes Tcli",
        &CHARS,
        "classes",
    );
}

#[test]
fn csharp_cli_lifts_to_pure_rust() {
    if !common::have("dotnet") || !common::have("cargo") {
        return;
    }
    let repo = fixture("csharp");
    dotnet_build(&repo, "out");
    let invariant = Semantics {
        count: "Count::Chars",
        upper: "Upper::Simple",
        unit: "characters",
    };
    lift_end_to_end(&repo, "dotnet out/tcli.dll", &invariant, "out");
}

/// A glue that answers every case by running the original's program: the shape of a cheat.
const SHELLING_OUT_GLUE: &str = "use std::process::{Command, ExitCode};

use clap::ArgMatches;

pub fn run(_command: &str, _matches: &ArgMatches) -> ExitCode {
    let status = Command::new(\"python3\")
        .arg(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../../tcli.py\"))
        .args(std::env::args().skip(1))
        .status();
    match status.ok().and_then(|s| s.code()) {
        Some(0) => ExitCode::SUCCESS,
        Some(code) => ExitCode::from(u8::try_from(code).unwrap_or(1)),
        None => ExitCode::from(127),
    }
}
";

/// Records the Python fixture, wires every command to one unit and puts `glue` in its place.
fn wired_with_glue(glue: &str, body: Option<&str>) -> PathBuf {
    let repo = fixture("python");
    app::record(&RecordOptions {
        repo: &repo,
        run: &words("python3 tcli.py"),
        inputs: None,
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    front_door::front_door(&FrontDoorOptions {
        repo: &repo,
        library: false,
        check: false,
        commands: &[],
    })
    .unwrap();
    write_unit(&repo, "cheat-rs", WORDCOUNT_PORT);
    let wired = front_door::wire(&WireOptions {
        repo: &repo,
        unit: "cheat",
        commands: &["upper", "len", "div", "copy", "now", "words", "tcli"].map(String::from),
        routes: &[],
        skip_gate: true,
        check: false,
    })
    .unwrap();
    if let Some(body) = body {
        std::fs::write(wired.glue.with_file_name("cheat_body.txt"), body).unwrap();
    }
    std::fs::write(&wired.glue, glue).unwrap();
    for dir in ["rust/app", "rust/cheat-rs"] {
        sh(&repo.join(dir), "cargo", &["fmt"]);
    }
    // These tests are about what `lift` refuses after the obligation registry (the sweep for
    // escape hatches, the replay without the original): the obligations are decided, as a person
    // would, so that the refusal observed is the one the test names.
    common::decide_obligations(&repo);
    repo
}

#[test]
fn lift_refuses_a_front_door_that_shells_out_to_the_original() {
    if !common::have("python3") || !common::have("cargo") {
        return;
    }
    let repo = wired_with_glue(SHELLING_OUT_GLUE, None);
    let outcome = lift::lift(&LiftOptions { repo: &repo }).unwrap();
    assert!(!outcome.lifted, "{:?}", outcome.checklist);
    let text = format!("{:?}", outcome.blockers);
    assert!(text.contains("starts `python3`"), "{text}");
    assert!(!front_door::State::load(&repo).unwrap().lifted);
    std::fs::remove_dir_all(&repo).unwrap();
}

/// The static scan cannot see code it does not read: the replay with the original moved away
/// still refuses it, and puts the original back.
#[test]
fn lift_replays_with_the_original_hidden() {
    if !common::have("python3") || !common::have("cargo") {
        return;
    }
    let hidden_glue = "include!(\"cheat_body.txt\");\n";
    let repo = wired_with_glue(hidden_glue, Some(SHELLING_OUT_GLUE));
    let outcome = lift::lift(&LiftOptions { repo: &repo }).unwrap();
    assert!(!outcome.lifted);
    let replay = outcome
        .checklist
        .iter()
        .find(|i| i.name == "replay")
        .unwrap_or_else(|| panic!("{:?} {:?}", outcome.blockers, outcome.checklist));
    assert_eq!(replay.mark, lift::Mark::Fail, "{replay:?}");
    assert!(replay.detail.contains("original hidden"), "{replay:?}");
    assert!(replay.detail.contains("tcli.py"), "{replay:?}");
    assert!(repo.join("tcli.py").is_file(), "the original is put back");
    assert!(!repo.join("tcli.py.rust-anything-hidden").exists());
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn lift_strips_bridge_bindings_in_every_language() {
    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
    let base = std::env::temp_dir().join(format!("rust-anything-strip-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    let units = [
        ("mini", "packages/a/src/util.ts", "ts"),
        ("python", "src/textkit/", "python"),
        ("c", "src/text.c", "c"),
        ("go", "strkit/", "go"),
        ("ruby", "lib/textkit/", "ruby"),
        ("java", "src/main/java/com/example/text/", "java"),
    ];
    for (fixture, unit, lang) in units {
        let dir = base.join(lang);
        rust_anything::bridge::bridge(&rust_anything::bridge::Options {
            root: &fixtures.join(fixture),
            unit,
            kind: None,
            out: Some(dir.clone()),
            name: None,
            force: false,
            keep: Vec::new(),
            lang: None,
            batch: Vec::new(),
            as_json: Vec::new(),
            allocator: Default::default(),
        })
        .unwrap();
        if lang == "ts" {
            let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
            std::fs::write(
                dir.join("src/port.rs"),
                format!("{port}\n#[allow(unused_imports)]\nuse crate::utf16;\n"),
            )
            .unwrap();
        }
        let removed = lift::strip_unit(&dir).unwrap();
        assert!(!removed.is_empty(), "{lang}");
        let cargo = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap();
        for binding in [
            "cdylib",
            "staticlib",
            "napi",
            "pyo3",
            "magnus",
            "jni",
            "build =",
        ] {
            assert!(!cargo.contains(binding), "{lang}: {cargo}");
        }
        let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
        let expected = if lang == "ts" {
            "pub mod port;\npub mod utf16;\n"
        } else {
            "pub mod port;\n"
        };
        assert_eq!(lib, expected, "{lang}");
        for generated in [
            "build.rs",
            "index.cjs",
            "python",
            "go",
            "ruby",
            "java",
            "include",
            "src/wire.rs",
            "src/js.rs",
            "src/pyconv.rs",
            "src/rbconv.rs",
        ] {
            assert!(!dir.join(generated).exists(), "{lang}: {generated}");
        }
        assert!(dir.join("src/port.rs").is_file());
        if common::have("cargo") {
            let out = Command::new("cargo")
                .args(["check", "--quiet", "--manifest-path"])
                .arg(dir.join("Cargo.toml"))
                .env("CARGO_TARGET_DIR", base.join("target"))
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "{lang}: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        }
    }
    std::fs::remove_dir_all(&base).unwrap();
}

fn one_off(name: &str, files: &[(&str, &str)]) -> PathBuf {
    let repo = std::env::temp_dir().join(format!(
        "rust-anything-app-test-{name}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).unwrap();
    for (path, text) in files {
        std::fs::write(repo.join(path), text).unwrap();
    }
    repo
}

/// Plants one difference at a time in a build of a small original and checks that `app replay`
/// fails on each: the newline and wildcard leniencies, an extra file, and a case edited,
/// skipped or removed after it was recorded.
#[test]
fn replay_fails_on_every_planted_difference() {
    if !common::have("python3") {
        return;
    }
    let body = |stdout: &str, stderr: &str, extra: &str| {
        format!(
            "import sys\nsys.stdout.buffer.write({stdout:?}.encode())\nsys.stderr.buffer.write({stderr:?}.encode())\n{extra}\n"
        )
    };
    // The original prints a lone `...` and a `[..]` as text, and a blank line on stderr.
    let text = "Loading\n...\nDone\npattern: src/[..]/x\n";
    let repo = one_off(
        "planted",
        &[
            ("orig.py", &body(text, "\n", "")),
            ("same.py", &body(text, "\n", "")),
            ("no_newline.py", &body(text.trim_end(), "\n", "")),
            ("crlf.py", &body(&text.replace('\n', "\r\n"), "\n", "")),
            ("no_blank.py", &body(text, "", "")),
            (
                "garbage.py",
                &body(
                    "Loading\nGARBAGE\nMORE GARBAGE\nDone\npattern: src/WHATEVER/x\n",
                    "\n",
                    "",
                ),
            ),
            (
                "extra_file.py",
                &body(text, "\n", "open('evil.txt', 'w').write('x')"),
            ),
        ],
    );
    let record = common::cli()
        .args([
            "app",
            "record",
            ".",
            "--no-traps",
            "--",
            "python3",
            "orig.py",
        ])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(record.status.success(), "{record:?}");
    let replay = |build: &str| -> String {
        let out = common::cli()
            .args(["app", "replay", ".", "--build", build])
            .current_dir(&repo)
            .output()
            .unwrap();
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        )
    };
    let passes = |build: &str| {
        let printed = replay(build);
        assert!(
            printed.starts_with("1/1 cases passed"),
            "{build}: {printed}"
        );
    };
    let fails = |build: &str| {
        let printed = replay(build);
        assert!(
            printed.starts_with("0/1 cases passed"),
            "{build} should fail: {printed}"
        );
        printed
    };
    passes("python3 same.py");
    fails("python3 no_newline.py");
    fails("python3 crlf.py");
    fails("python3 no_blank.py");
    fails("python3 garbage.py");
    let extra = fails("python3 extra_file.py");
    assert!(extra.contains("evil.txt"), "{extra}");

    // The cases are what `app record` wrote: an edit, a skip or a removal is a failure.
    let case = repo.join("rust/app-cases/no-args");
    let toml = std::fs::read_to_string(case.with_extension("toml")).unwrap();
    std::fs::write(
        case.with_extension("toml"),
        toml.replace("status.code = 0", "status = \"skipped\""),
    )
    .unwrap();
    let skipped = fails("python3 garbage.py");
    assert!(skipped.contains("recording (skipped)"), "{skipped}");
    let skipped_same = replay("python3 same.py");
    assert!(
        skipped_same.starts_with("0/1 cases passed"),
        "a skipped case is not a pass: {skipped_same}"
    );
    std::fs::write(case.with_extension("toml"), &toml).unwrap();
    passes("python3 same.py");
    let stdout = std::fs::read_to_string(case.with_extension("stdout")).unwrap();
    std::fs::write(
        case.with_extension("stdout"),
        stdout.replace("Done", "Gone"),
    )
    .unwrap();
    let edited = fails("python3 same.py");
    assert!(edited.contains("recording (edited)"), "{edited}");
    std::fs::write(case.with_extension("stdout"), &stdout).unwrap();
    std::fs::remove_file(case.with_extension("stdout")).unwrap();
    let missing = replay("python3 same.py");
    assert!(missing.contains("recording (edited)"), "{missing}");
    std::fs::write(case.with_extension("stdout"), &stdout).unwrap();
    passes("python3 same.py");

    // A case added by hand is not in the case list: the note counts it in the singular and names it.
    let hand = repo.join("rust/app-cases/handwritten");
    for ext in ["toml", "stderr"] {
        std::fs::copy(case.with_extension(ext), hand.with_extension(ext)).unwrap();
    }
    std::fs::write(
        hand.with_extension("stdout"),
        "Loading\n[..]\nDone\npattern: src/[..]/x\n",
    )
    .unwrap();
    let noted = replay("python3 same.py");
    assert!(noted.starts_with("2/2 cases passed"), "{noted}");
    assert!(
        noted.contains("note: 1 case is not in rust-anything.cases.json"),
        "{noted}"
    );
    assert!(noted.contains(": handwritten; its `[..]`"), "{noted}");
    for ext in ["toml", "stdout", "stderr"] {
        std::fs::remove_file(hand.with_extension(ext)).unwrap();
    }

    // A recording from before the case list is read as it always was, with a note.
    std::fs::remove_file(repo.join("rust/app-cases/rust-anything.cases.json")).unwrap();
    let legacy = replay("python3 garbage.py");
    assert!(legacy.starts_with("1/1 cases passed"), "{legacy}");
    assert!(legacy.contains("legacy recording"), "{legacy}");
    // Exact newlines are checked either way.
    let printed = replay("python3 no_newline.py");
    assert!(printed.starts_with("0/1 cases passed"), "{printed}");
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn app_record_refuses_to_write_a_secret_from_the_environment() {
    if !common::have("python3") {
        return;
    }
    let repo = one_off(
        "secret-env",
        &[(
            "cli.py",
            "import os\nprint(os.environ.get('API_TOKEN', 'unset'))\n",
        )],
    );
    let record = |token: Option<&str>| {
        let mut cmd = common::cli();
        cmd.args([
            "app",
            "record",
            ".",
            "--no-traps",
            "--",
            "python3",
            "cli.py",
        ])
        .env_remove("API_TOKEN")
        .current_dir(&repo);
        if let Some(token) = token {
            cmd.env("API_TOKEN", token);
        }
        cmd.output().unwrap()
    };
    let leaked = record(Some("sk-live-0123456789abcdef"));
    let written = std::fs::read_dir(repo.join("rust/app-cases")).is_ok_and(|d| d.count() > 0);
    let clean = record(None);
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(!leaked.status.success(), "{leaked:?}");
    let stderr = String::from_utf8_lossy(&leaked.stderr);
    assert!(stderr.contains("$API_TOKEN"), "{stderr}");
    assert!(
        !stderr.contains("sk-live-0123456789abcdef"),
        "the value is never printed: {stderr}"
    );
    assert!(!written, "nothing was written");
    assert!(clean.status.success(), "{clean:?}");
}

#[test]
fn app_record_prints_one_case_in_the_singular() {
    if !common::have("node") {
        return;
    }
    let repo = one_off(
        "one-case",
        &[
            ("up.mjs", "console.log(process.argv[2].toUpperCase())\n"),
            ("inputs.jsonl", "{\"args\": [\"hi\"]}\n"),
        ],
    );
    let out = common::cli()
        .args(["app", "record", "."])
        .args([
            "--no-traps",
            "--inputs",
            "inputs.jsonl",
            "--",
            "node",
            "up.mjs",
        ])
        .current_dir(&repo)
        .output()
        .unwrap();
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(out.status.success(), "{out:?}");
    let printed = String::from_utf8_lossy(&out.stdout);
    assert!(printed.starts_with("Recorded 1 case in "), "{printed}");
}

#[test]
fn app_record_without_examples_names_the_no_arguments_run() {
    if !common::have("python3") {
        return;
    }
    let repo = one_off(
        "no-examples",
        &[("cli.py", "import sys\nprint(\"args:\", sys.argv[1:])\n")],
    );
    let record = |args: &[&str]| {
        common::cli()
            .args(args)
            .current_dir(&repo)
            .output()
            .unwrap()
    };
    let out = record(&["app", "record", ".", "--", "python3", "cli.py"]);
    let printed = String::from_utf8_lossy(&out.stdout).into_owned();
    let wrote_no_args = repo.join("rust/app-cases/no-args.toml").is_file();
    let json = record(&["app", "record", ".", "--json", "--", "python3", "cli.py"]);
    let printed_json = String::from_utf8_lossy(&json.stdout).into_owned();
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(out.status.success(), "{out:?}");
    assert!(printed.starts_with("Recorded 1 case in "), "{printed}");
    assert!(
        printed.contains("(0 from examples, 0 from inputs, 1 run with no arguments, 0 traps)"),
        "{printed}"
    );
    assert!(wrote_no_args);
    assert!(json.status.success(), "{json:?}");
    assert!(printed_json.contains("\"no_args\": 1"), "{printed_json}");
    let parsed: serde_json::Value = serde_json::from_str(&printed_json).unwrap();
    assert_eq!(parsed["cases"], 1, "{printed_json}");
    assert_eq!(parsed["no_args"], 1, "{printed_json}");
}

#[test]
fn app_record_without_examples_and_a_timeout_fails_and_writes_no_case() {
    if !common::have("python3") {
        return;
    }
    let repo = one_off(
        "no-examples-timeout",
        &[("cli.py", "import time\ntime.sleep(30)\n")],
    );
    let record = |args: &[&str]| {
        common::cli()
            .args(args)
            .current_dir(&repo)
            .output()
            .unwrap()
    };
    let out = record(&[
        "app",
        "record",
        ".",
        "--timeout",
        "1",
        "--",
        "python3",
        "cli.py",
    ]);
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    let wrote_no_args = repo.join("rust/app-cases/no-args.toml").is_file();
    std::fs::remove_dir_all(&repo).unwrap();
    // Nothing answered, so there is no recording: the command fails and says which case.
    assert!(!out.status.success(), "{out:?} {stderr}");
    assert!(stderr.contains("recorded 0 cases"), "{stderr}");
    assert!(stderr.contains("no-args"), "{stderr}");
    assert!(!wrote_no_args);
}

#[cfg(unix)]
#[test]
fn app_replay_counts_a_case_with_two_differences_once() {
    if !common::have("python3") {
        return;
    }
    let repo = one_off(
        "two-differences-one-case",
        &[("cli.py", "import sys\nprint(\"args:\", sys.argv[1:])\n")],
    );
    let recorded = common::cli()
        .args(["app", "record", ".", "--", "python3", "cli.py"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(recorded.status.success(), "{recorded:?}");
    // `false` exits 1 with no output, so the one case differs in its status and its stdout.
    let replayed = common::cli()
        .args(["app", "replay", ".", "--build", "false"])
        .current_dir(&repo)
        .output()
        .unwrap();
    let printed = String::from_utf8_lossy(&replayed.stdout).into_owned();
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(!replayed.status.success(), "{replayed:?}");
    assert!(printed.starts_with("0/1 cases passed"), "{printed}");
    assert!(
        printed.contains("2 distinct differences in 1 case:"),
        "{printed}"
    );
    assert!(!printed.contains("in 2 cases"), "{printed}");
    assert!(printed.contains("- no-args: status"), "{printed}");
    assert!(printed.contains("stdout"), "{printed}");
}

#[test]
fn a_written_file_named_by_a_normalized_value_replays() {
    if !common::have("node") {
        return;
    }
    // Every run names its file differently; `run=run-\d+` says that part of the name is noise.
    let write = |text: &str| {
        format!(
            "require('fs').writeFileSync(`run-${{process.hrtime.bigint()}}.log`, '{text}\\n')\n"
        )
    };
    let repo = one_off(
        "named-by-time",
        &[
            ("save.cjs", &write("saved")),
            ("other.cjs", &write("other")),
            ("nothing.cjs", "\n"),
            ("inputs.jsonl", "{\"name\": \"save\", \"args\": []}\n"),
        ],
    );
    let record = common::cli()
        .args([
            "app",
            "record",
            ".",
            "--no-traps",
            "--inputs",
            "inputs.jsonl",
        ])
        .args(["--normalize", r"run=run-\d+", "--", "node", "save.cjs"])
        .current_dir(&repo)
        .output()
        .unwrap();
    let printed = String::from_utf8_lossy(&record.stdout).into_owned();
    let replay = |build: Option<&str>| {
        let mut cmd = common::cli();
        cmd.args(["app", "replay", "."]).current_dir(&repo);
        if let Some(build) = build {
            cmd.args(["--build", build]);
        }
        let out = cmd.output().unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned()
    };
    let (same, other, nothing) = (
        replay(None),
        replay(Some("node other.cjs")),
        replay(Some("node nothing.cjs")),
    );
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(record.status.success(), "{record:?}");
    assert!(!printed.contains("Unstable"), "{printed}");
    assert!(same.starts_with("1/1 cases passed"), "{same}");
    assert!(other.starts_with("0/1 cases passed"), "{other}");
    assert!(other.contains("- save: file run-"), "{other}");
    assert!(nothing.contains("(not written)"), "{nothing}");
}

#[test]
fn a_library_front_door_names_the_folder_when_no_exports_are_read() {
    let repo = one_off(
        "script with spaces",
        &[("main.py", "import sys\nprint(sys.argv)\n")],
    );
    let out = common::cli()
        .args(["app", "front-door"])
        .arg(&repo)
        .output()
        .unwrap();
    let repo_name = repo.file_name().unwrap().to_str().unwrap().to_owned();
    let cli_repo = app::cli_path(repo.canonical().unwrap());
    let suggested_command = format!("rust-anything app record {cli_repo} -- <command>");
    // Issue #1458: `--http` is a switch, so the server form must not give it a value.
    let suggested_server = format!("rust-anything app record {cli_repo} --http -- <command>");
    std::fs::remove_dir_all(&repo).unwrap();

    assert!(!out.status.success(), "{out:?}");
    let error = String::from_utf8_lossy(&out.stderr);
    assert!(error.contains(&repo_name), "{error}");
    assert!(error.contains("as a library"), "{error}");
    assert!(error.contains(&suggested_command), "{error}");
    assert!(error.contains(&suggested_server), "{error}");
    assert!(
        error.contains("add `--inputs <requests.jsonl>` before `--`"),
        "{error}"
    );
    assert!(!error.contains("--http <"), "{error}");
    assert!(
        error.contains("check that this folder is its root"),
        "{error}"
    );
}

#[test]
fn a_library_front_door_prints_one_export_in_the_singular() {
    let repo = one_off(
        "one-export",
        &[
            (
                "package.json",
                "{\"name\": \"one\", \"type\": \"module\"}\n",
            ),
            ("one.ts", "export function one(): number {\n  return 1\n}\n"),
        ],
    );
    let out = common::cli()
        .args(["app", "front-door", ".", "--library", "--no-check"])
        .current_dir(&repo)
        .output()
        .unwrap();
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(out.status.success(), "{out:?}");
    let printed = String::from_utf8_lossy(&out.stdout);
    assert!(
        printed.contains("public API: one.ts (1 export)\n"),
        "{printed}"
    );
}

#[test]
fn a_front_door_with_no_commands_names_the_root_command() {
    let Some(python) = common::python() else {
        return;
    };
    let repo = one_off(
        "root-only",
        &[("cli.py", "import sys\nprint('hello', *sys.argv[1:])\n")],
    );
    let record = common::cli()
        .args(["app", "record", ".", "--no-traps", "--"])
        .args([python, "cli.py"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(
        record.status.success(),
        "{}",
        String::from_utf8_lossy(&record.stderr)
    );
    let out = common::cli()
        .args(["app", "front-door", ".", "--no-check"])
        .current_dir(&repo)
        .output()
        .unwrap();
    let state: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(repo.join("rust/app/rust-anything.json")).unwrap_or_default(),
    )
    .unwrap_or_default();
    std::fs::remove_dir_all(&repo).unwrap();
    assert!(out.status.success(), "{out:?}");
    let printed = String::from_utf8_lossy(&out.stdout);
    let root = state["name"].as_str().unwrap_or_default();
    assert!(!root.is_empty(), "{state}");
    assert!(
        printed.contains(&format!("commands: none (the root command is `{root}`)")),
        "{printed}"
    );
    assert!(
        printed.contains(&format!("<unit> --command {}\n", app::cli_path(root))),
        "{printed}"
    );
    assert!(!printed.contains("<name>"), "{printed}");
}

#[test]
fn app_record_keeps_a_saved_timeout_when_none_is_passed() {
    let Some(python) = common::python() else {
        return;
    };
    let repo = one_off(
        "keeps-timeout",
        &[("cli.py", "import sys\nprint('hello', *sys.argv[1:])\n")],
    );
    let record = |extra: &[&str], run: &[&str]| {
        let out = common::cli()
            .args(["app", "record", ".", "--no-traps"])
            .args(extra)
            .args(run)
            .current_dir(&repo)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
    };
    let saved = || -> serde_json::Value {
        serde_json::from_str(
            &std::fs::read_to_string(app::cases_dir(&repo).join("rust-anything.json")).unwrap(),
        )
        .unwrap()
    };
    record(&["--timeout", "5"], &["--", python, "cli.py"]);
    assert_eq!(saved()["timeout_secs"], 5);
    // Without `--timeout` (and without the command, which is saved too), the saved one stays.
    record(&[], &[]);
    assert_eq!(saved()["timeout_secs"], 5, "{}", saved());
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn app_record_and_replay_cli_reject_zero_timeout_without_touching_cases() {
    let repo = one_off("zero-timeout-cli", &[("cli.py", "print('hi')\n")]);
    let cases_dir = repo.join("rust/app-cases");
    std::fs::create_dir_all(&cases_dir).unwrap();
    let cfg_path = cases_dir.join("rust-anything.json");
    let case_path = cases_dir.join("no-args.toml");
    let original_cfg = "{\"schema\":\"rust-anything/app@1\",\"name\":\"app\",\"run\":[\"python3\",\"cli.py\"],\"timeout_secs\":30,\"recorded\":[\"no-args\"]}\n";
    let original_case = "stdout = \"hi\\n\"\n";
    std::fs::write(&cfg_path, original_cfg).unwrap();
    std::fs::write(&case_path, original_case).unwrap();

    let rec = common::cli()
        .args([
            "app",
            "record",
            ".",
            "--timeout",
            "0",
            "--",
            "missing-command",
        ])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(!rec.status.success(), "{rec:?}");
    let rec_err = String::from_utf8_lossy(&rec.stderr);
    assert!(
        rec_err.contains("--timeout") && rec_err.contains("1 second"),
        "{rec_err}"
    );

    let rep = common::cli()
        .args(["app", "replay", ".", "--timeout", "0"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(!rep.status.success(), "{rep:?}");
    let rep_err = String::from_utf8_lossy(&rep.stderr);
    assert!(
        rep_err.contains("--timeout") && rep_err.contains("1 second"),
        "{rep_err}"
    );

    assert_eq!(std::fs::read_to_string(&cfg_path).unwrap(), original_cfg);
    assert_eq!(std::fs::read_to_string(&case_path).unwrap(), original_case);
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn app_replay_with_a_port_on_a_cli_recording_fails_before_running() {
    let repo = one_off("port-on-cli", &[("cli.py", "print('hi')\n")]);
    let cases_dir = repo.join("rust/app-cases");
    std::fs::create_dir_all(&cases_dir).unwrap();
    let cfg_path = cases_dir.join("rust-anything.json");
    let case_path = cases_dir.join("no-args.toml");
    let original_cfg = "{\"schema\":\"rust-anything/app@1\",\"name\":\"app\",\"run\":[\"python3\",\"cli.py\"],\"timeout_secs\":30,\"recorded\":[\"no-args\"]}\n";
    let original_case = "stdout = \"hi\\n\"\n";
    std::fs::write(&cfg_path, original_cfg).unwrap();
    std::fs::write(&case_path, original_case).unwrap();

    let rep = common::cli()
        .args(["app", "replay", ".", "--port", "9"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert!(!rep.status.success(), "{rep:?}");
    let rep_err = String::from_utf8_lossy(&rep.stderr);
    assert!(
        rep_err.contains("--port") && rep_err.contains("server recordings (`app record --http`)"),
        "{rep_err}"
    );

    // It failed before running: no report was written and the cases are untouched.
    assert!(!cases_dir.join("replay-report.md").exists());
    assert_eq!(std::fs::read_to_string(&cfg_path).unwrap(), original_cfg);
    assert_eq!(std::fs::read_to_string(&case_path).unwrap(), original_case);
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn drift_lists_an_edited_or_removed_recording_apart_from_upstream_changes() {
    let Some(python) = common::python() else {
        return;
    };
    let repo = one_off(
        "drift-recording",
        &[
            ("cli.py", "import sys\nprint(sys.argv[1].upper())\n"),
            (
                "inputs.jsonl",
                "{\"name\":\"hi\",\"args\":[\"hi\"]}\n{\"name\":\"bye\",\"args\":[\"bye\"]}\n",
            ),
        ],
    );
    let inputs = repo.join("inputs.jsonl");
    app::record(&RecordOptions {
        repo: &repo,
        run: &[python.to_string(), "cli.py".to_string()],
        inputs: Some(&inputs),
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    let dir = app::cases_dir(&repo);
    std::fs::write(dir.join("hi.stdout"), "HELLO\n").unwrap();
    for entry in std::fs::read_dir(&dir).unwrap() {
        let path = entry.unwrap().path();
        if path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("bye."))
        {
            std::fs::remove_file(path).unwrap();
        }
    }
    let out = drift::drift(&DriftOptions {
        repo: &repo,
        build: None,
        timeout_secs: None,
    })
    .unwrap();
    let report = std::fs::read_to_string(&out.report).unwrap();
    std::fs::remove_dir_all(&repo).unwrap();

    assert!(out.drifted, "{out:?}");
    assert!(
        out.changed.is_empty(),
        "the original did not change: {out:?}"
    );
    let verdicts: Vec<(&str, &str)> = out
        .recording
        .iter()
        .map(|d| (d.case.as_str(), d.verdict.as_str()))
        .collect();
    assert!(
        verdicts.contains(&("hi", "recording edited")),
        "{verdicts:?}"
    );
    assert!(
        verdicts.contains(&("bye", "recording removed")),
        "{verdicts:?}"
    );
    assert!(report.contains("## Recording changed"), "{report}");
    assert!(!report.contains("## Changed upstream"), "{report}");
    assert!(!report.contains("original changed"), "{report}");
}

#[test]
fn drift_finds_upstream_changes_and_new_examples() {
    if !common::have("node") {
        return;
    }
    let repo = fixture("ts");
    std::fs::copy(repo.join("tcli.js"), repo.join("tcli_copy.js")).unwrap();
    std::fs::write(
        repo.join("inputs.jsonl"),
        "{\"args\": [\"div\", \"1\", \"0\"]}\n",
    )
    .unwrap();
    let inputs = repo.join("inputs.jsonl");
    app::record(&RecordOptions {
        repo: &repo,
        run: &words("node tcli.js"),
        inputs: Some(&inputs),
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    let replay_report = app::cases_dir(&repo).join(app::REPORT_FILE);
    std::fs::write(&replay_report, "kept\n").unwrap();
    let run = || {
        drift::drift(&DriftOptions {
            repo: &repo,
            build: Some("node tcli_copy.js"),
            timeout_secs: None,
        })
        .unwrap()
    };

    let clean = run();
    assert!(!clean.drifted, "{clean:?}");
    assert!(clean.changed.is_empty() && clean.failing.is_empty() && clean.new.is_empty());
    assert_eq!(std::fs::read_to_string(&replay_report).unwrap(), "kept\n");
    let report = std::fs::read_to_string(&clean.report).unwrap();
    assert!(report.contains("No drift"), "{report}");
    assert!(
        !report.contains(&*std::env::temp_dir().to_string_lossy()),
        "{report}"
    );

    add_bug(&repo, "tcli.js", None);
    let changed = run();
    assert!(changed.drifted);
    assert_eq!(
        changed
            .changed
            .iter()
            .map(|c| c.case.as_str())
            .collect::<Vec<_>>(),
        ["input-001-div"],
        "{changed:?}"
    );
    assert_eq!(
        changed.changed[0].verdict,
        "original changed, port still old"
    );
    assert!(changed.failing.is_empty(), "{changed:?}");
    assert_eq!(std::fs::read_to_string(&replay_report).unwrap(), "kept\n");
    let report = std::fs::read_to_string(&changed.report).unwrap();
    assert!(
        report.contains("input-001-div") && report.contains("divide by zero"),
        "{report}"
    );

    let readme = std::fs::read_to_string(repo.join("README.md"))
        .unwrap()
        .replace("\r\n", "\n");
    std::fs::write(
        repo.join("README.md"),
        readme.replace("$ tcli nope\n", "$ tcli nope\n$ tcli upper again\n"),
    )
    .unwrap();
    let out = common::cli()
        .args(["app", "drift", ".", "--build", "node tcli_copy.js"])
        .current_dir(&repo)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let printed = String::from_utf8_lossy(&out.stdout);
    assert!(
        printed.contains("8 cases; build: node tcli_copy.js"),
        "{printed}"
    );
    assert!(printed.contains("tcli upper again"), "{printed}");
    let fresh = run();
    assert_eq!(fresh.new, ["tcli upper again"], "{fresh:?}");
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn drift_prints_singular_case_for_one_case_recording() {
    if !common::have("node") {
        return;
    }
    let repo = fixture("ts");
    std::fs::copy(repo.join("tcli.js"), repo.join("tcli_copy.js")).unwrap();
    std::fs::write(repo.join("README.md"), "").unwrap();
    std::fs::write(
        repo.join("inputs.jsonl"),
        "{\"args\": [\"div\", \"1\", \"0\"]}\n",
    )
    .unwrap();
    let inputs = repo.join("inputs.jsonl");
    app::record(&RecordOptions {
        repo: &repo,
        run: &words("node tcli.js"),
        inputs: Some(&inputs),
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();

    let out = common::cli()
        .args(["app", "drift", ".", "--build", "node tcli_copy.js"])
        .current_dir(&repo)
        .output()
        .unwrap();
    let printed = String::from_utf8_lossy(&out.stdout);
    assert!(
        printed.contains("1 case; build: node tcli_copy.js"),
        "{printed}"
    );
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn record_names_input_lines_that_repeat_an_earlier_case() {
    // jmespath.py's compliance suite repeats 17 of its cases: a repeated line is not run again,
    // and the outcome says which line it was and which case it repeats.
    if !common::have("python3") {
        return;
    }
    let repo = std::env::temp_dir().join(format!("ra-dup-inputs-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join("echo.py"),
        "import sys\nprint(' '.join(sys.argv[1:]))\n",
    )
    .unwrap();
    let inputs = repo.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"name\": \"first\", \"args\": [\"a\"]}\n\
         {\"name\": \"other\", \"args\": [\"b\"]}\n\
         {\"name\": \"again\", \"args\": [\"a\"]}\n",
    )
    .unwrap();
    let outcome = app::record(&RecordOptions {
        repo: &repo,
        run: &words("python3 echo.py"),
        inputs: Some(&inputs),
        normalize: &[],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    std::fs::remove_dir_all(&repo).unwrap();
    assert_eq!(outcome.inputs, 2);
    assert_eq!(outcome.duplicate_inputs, ["again (first)"]);
}

#[test]
fn record_warns_when_every_case_fails_the_same_way() {
    // A command that never gets to the app (here a module it cannot import) records a failure
    // per case and nothing else; the recording says so instead of reading as complete.
    if !common::have("python3") {
        return;
    }
    let repo = std::env::temp_dir().join(format!("ra-same-failure-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join("broken.py"),
        "import no_such_module_ra_test\nprint('never')\n",
    )
    .unwrap();
    std::fs::write(
        repo.join("picky.py"),
        "import sys\nsys.exit('bad input: ' + sys.argv[1]) if sys.argv[1] != 'ok' else print('fine')\n",
    )
    .unwrap();
    let inputs = repo.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"name\": \"one\", \"args\": [\"a\"]}\n{\"name\": \"two\", \"args\": [\"b\"]}\n\
         {\"name\": \"three\", \"args\": [\"ok\"]}\n",
    )
    .unwrap();
    let record = |run: &str| {
        app::record(&RecordOptions {
            repo: &repo,
            run: &words(run),
            inputs: Some(&inputs),
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        })
        .unwrap()
    };
    let broken = record("python3 broken.py");
    // Cases that fail in different ways, or succeed, are the app answering: no warning.
    let picky = record("python3 picky.py");
    std::fs::remove_dir_all(&repo).unwrap();
    assert_eq!(
        broken.same_failure.as_deref(),
        Some("ModuleNotFoundError: No module named 'no_such_module_ra_test'")
    );
    assert_eq!(picky.same_failure, None);
}

#[test]
fn app_record_takes_a_float_tolerance_above_one_in_a_million_only_when_asked() {
    if !common::have("python3") {
        return;
    }
    let repo = one_off(
        "large-tolerance",
        &[
            ("cli.py", "import sys\nprint(float(sys.argv[1]) * 3)\n"),
            ("in.jsonl", "{\"name\": \"x\", \"args\": [\"2\"]}\n"),
        ],
    );
    let config = repo.join("rust/app-cases/rust-anything.json");
    let record = |tolerance: &[&str]| {
        common::cli()
            .args(["app", "record", ".", "--inputs", "in.jsonl", "--no-traps"])
            .args(tolerance)
            .args(["--", "python3", "cli.py"])
            .current_dir(&repo)
            .output()
            .unwrap()
    };
    let saved = || {
        std::fs::read_to_string(&config)
            .ok()
            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
            .map(|v| v["float_tolerance"].clone())
    };
    let call = |arguments: serde_json::Value| {
        rust_anything::mcp::handle(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": { "name": "app_record", "arguments": arguments },
        }))
        .unwrap()
    };

    let refused = record(&["--float-tolerance", "0.5"]);
    let refused_saved = saved();
    let mcp_refused = call(serde_json::json!({
        "repo": repo, "run": ["python3", "cli.py"], "inputs": repo.join("in.jsonl"),
        "traps": false, "float_tolerance": 0.5,
    }));
    let mcp_refused_saved = saved();
    let allowed = record(&["--float-tolerance", "0.5", "--allow-large-tolerance"]);
    let allowed_saved = saved();
    let small = record(&["--float-tolerance", "1e-9"]);
    let small_saved = saved();
    let mcp_allowed = call(serde_json::json!({
        "repo": repo, "run": ["python3", "cli.py"], "inputs": repo.join("in.jsonl"),
        "traps": false, "float_tolerance": 0.5, "allow_large_tolerance": true,
    }));
    let mcp_allowed_saved = saved();
    std::fs::remove_dir_all(&repo).unwrap();

    assert!(!refused.status.success(), "{refused:?}");
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(stderr.contains("--allow-large-tolerance"), "{stderr}");
    assert_eq!(refused_saved, None);
    assert_eq!(mcp_refused["result"]["isError"], true, "{mcp_refused}");
    assert!(
        mcp_refused.to_string().contains("allow-large-tolerance"),
        "{mcp_refused}"
    );
    assert_eq!(mcp_refused_saved, None);
    assert!(allowed.status.success(), "{allowed:?}");
    assert_eq!(allowed_saved, Some(serde_json::json!(0.5)));
    assert!(small.status.success(), "{small:?}");
    assert_eq!(small_saved, Some(serde_json::json!(1e-9)));
    assert_ne!(mcp_allowed["result"]["isError"], true, "{mcp_allowed}");
    assert_eq!(mcp_allowed_saved, Some(serde_json::json!(0.5)));
}

#[test]
fn a_line_spanning_normalizer_skips_only_the_cases_it_folded_across_lines() {
    if !common::have("python3") {
        return;
    }
    let cli = "import os, sys\n\
        case = sys.argv[1]\n\
        if case == 'inline':\n    print('id=abc done')\n\
        elif case == 'noise':\n    print('took', os.getpid(), 'ms')\n\
        else:\n    print('id=abc\\nsecond line')\n";
    let repo = one_off(
        "across-lines",
        &[
            ("cli.py", cli),
            (
                "inputs.jsonl",
                "{\"name\": \"inline\", \"args\": [\"inline\"]}\n\
                 {\"name\": \"noise\", \"args\": [\"noise\"]}\n\
                 {\"name\": \"multi\", \"args\": [\"multi\"]}\n",
            ),
        ],
    );
    // A lifted app whose `app_cases.rs` was edited by hand: `app record` leaves it alone and
    // names the skips it needs.
    let lifted = repo.join("rust/app");
    std::fs::create_dir_all(lifted.join("tests")).unwrap();
    std::fs::write(lifted.join("Cargo.toml"), "[package]\nname = \"cli-app\"\n").unwrap();
    std::fs::write(
        lifted.join("rust-anything.json"),
        r#"{"schema":"rust-anything/front-door@1","name":"cli","commands":[],"units":[],"lifted":true,"kind":"cli"}"#,
    )
    .unwrap();
    std::fs::write(lifted.join("tests/app_cases.rs"), "#[test]\nfn mine() {}\n").unwrap();
    let run = words("python3 cli.py");
    let recorded = app::record(&RecordOptions {
        repo: &repo,
        run: &run,
        inputs: Some(&repo.join("inputs.jsonl")),
        normalize: &["ident=id=[^ ]+".to_string()],
        name: None,
        traps: false,
        timeout_secs: None,
        http: None,
        server_args: None,
        fresh: None,
        pace_ms: None,
        port: None,
        float_tolerance: None,
        float_files: &[],
        effects: None,
        ready_secs: None,
        ready_request: None,
        sandbox: false,
    })
    .unwrap();
    let cases = app::cases_dir(&repo);
    let stdout = |name: &str| {
        std::fs::read_to_string(cases.join(format!("{name}.stdout")))
            .unwrap()
            .replace("\r\n", "\n")
    };
    let saved = std::fs::read_to_string(cases.join(app::CONFIG_FILE)).unwrap();
    let saved: serde_json::Value = serde_json::from_str(&saved).unwrap();
    let (inline, noise, multi) = (stdout("inline"), stdout("noise"), stdout("multi"));
    std::fs::remove_dir_all(&repo).unwrap();

    assert_eq!(inline, "[..] done\n");
    assert_eq!(noise, "took [..] ms\n");
    assert_eq!(multi, "[..] line\n");
    assert_eq!(
        saved["across_lines"],
        serde_json::json!({"multi": ["stdout"]})
    );
    let note = recorded.trycmd_test.unwrap();
    assert!(
        note.ends_with("required trycmd skips: multi.toml"),
        "{note}"
    );
}