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.

168 KB
Raw Blame
//! The bridge -> record -> diff -> shadow loop on the fixture repo.
//!
//! A hand-written JS module stands in for the built Rust module, so these tests check the
//! harness itself without compiling a native crate. They need `node` on PATH.

mod common;

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

use rust_anything::bridge::{self, Kind, Manifest};
use rust_anything::codegen_php;
use rust_anything::harness::{self, DiffOptions, RecordOptions};
use rust_anything::shadow;
use rust_anything::walk::Canonical;

fn fixture() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini")
}

/// A fresh crate for `util.ts` in a temp folder.
fn bridged(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("rust-anything-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/util.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    // The tests replace the compiled module with a JS stand-in, so no `.node` file is ever built;
    // an empty one marks the crate as built, which `diff` and `bench` check before starting node.
    let lib = bridge::Manifest::load(&dir).unwrap().lib_name();
    std::fs::write(dir.join(format!("{lib}.node")), "").unwrap();
    dir
}

/// JS stand-in for the Rust module; `buggy` miscounts tabs as spaces.
fn stand_in(dir: &Path, buggy: bool) {
    let space = if buggy { "/[ \\t]/" } else { "/ /" };
    std::fs::write(
        dir.join("index.cjs"),
        format!(
            "const after = /(?<=\\$)\\w+/g\n\
             exports.rangeOf = (text, word) => {{ const start = text.indexOf(word); return {{ start, end: start + word.length, rest: text.slice(start) }} }}\n\
             exports.words = text => [...text.matchAll(after)].map(m => m[0])\n\
             exports.count = text => [...text].filter(c => {space}.test(c)).length\n"
        ),
    )
    .unwrap();
}

#[test]
fn refresh_keeps_the_original_name_for_raw_rust_identifiers() {
    let dir = bridged("raw-identifiers");
    let mut manifest = Manifest::load(&dir).unwrap();
    manifest.exports.truncate(1);
    manifest.exports[0].name = "Type".into();
    manifest.save(&dir).unwrap();
    std::fs::write(dir.join("src/port.rs"), "pub fn r#type() -> f64 { 1.0 }\n").unwrap();

    let refreshed = bridge::refresh(&dir).unwrap();
    assert_eq!(refreshed.functions, ["Type"]);
    let bindings = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(bindings.contains(r#"js_name = "Type""#), "{bindings}");
    std::fs::remove_dir_all(dir).unwrap();
}

/// A crate for one source file, bridged in a scratch repository named `name`.
fn bridged_file(name: &str, file: &str, source: &str) -> (common::Scratch, PathBuf) {
    let root = common::Scratch::new(
        std::env::temp_dir().join(format!("rust-anything-{name}-{}", std::process::id())),
    );
    std::fs::write(root.join(file), source).unwrap();
    let dir = root.join("rust/mathx-rs");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: file,
        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();
    (root, dir)
}

/// Adds a `pub fn` that matches no export of the original to the crate's `port.rs`.
fn add_helper(dir: &Path) {
    let port = dir.join("src/port.rs");
    let source = std::fs::read_to_string(&port).unwrap();
    std::fs::write(
        &port,
        source + "\npub fn helper_extra(x: i64) -> Result<i64, String> {\n    Ok(x)\n}\n",
    )
    .unwrap();
}

/// The MCP `refresh` tool's result for a crate.
fn refresh_tool(dir: &Path) -> serde_json::Value {
    let response = rust_anything::mcp::handle(&serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": { "name": "refresh", "arguments": { "crate": dir } },
    }))
    .unwrap();
    assert_ne!(response["result"]["isError"], true, "{response}");
    response["result"]["structuredContent"].clone()
}

#[test]
fn refresh_keeps_the_rust_name_of_a_python_function_that_is_not_an_export_and_says_so() {
    let (_root, dir) = bridged_file(
        "not-an-export-py",
        "mathx.py",
        "def scale(x: float, k: float) -> float:\n    return x * k\n",
    );
    add_helper(&dir);

    let out = common::cli().arg("refresh").arg(&dir).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout.contains(" for scale, helper_extra\n"), "{stdout}");
    assert!(
        stdout.contains(
            "`helper_extra` is not an export of `mathx.py` and is now part of the bridged API; \
             make it private (`fn`) if it is a helper\n"
        ),
        "{stdout}"
    );
    let init = std::fs::read_to_string(dir.join("python/mathx_rs/__init__.py")).unwrap();
    assert!(
        init.contains("helper_extra = _native.helper_extra\n"),
        "{init}"
    );
    assert!(!init.contains("helperExtra"), "{init}");
    let refreshed = refresh_tool(&dir);
    assert_eq!(
        refreshed["not_exports"],
        serde_json::json!(["helper_extra"]),
        "{refreshed}"
    );
}

#[test]
fn refresh_keeps_the_doc_name_of_a_python_function_that_is_not_an_export() {
    let (_root, dir) = bridged_file(
        "doc-named-py",
        "mathx.py",
        "def scale(x: float, k: float) -> float:\n    return x * k\n",
    );
    let port = dir.join("src/port.rs");
    let source = std::fs::read_to_string(&port).unwrap();
    std::fs::write(
        &port,
        source
            + "\n/// Port of `rescale`\npub fn rescale_it(x: i64) -> Result<i64, String> {\n    Ok(x)\n}\n\
               \n/// Port of `widenIt`\npub fn widen_it(x: i64) -> Result<i64, String> {\n    Ok(x)\n}\n",
    )
    .unwrap();
    let refreshed = refresh_tool(&dir);
    assert_eq!(
        refreshed["functions"],
        serde_json::json!(["scale", "rescale", "widenIt"])
    );
    assert_eq!(
        refreshed["not_exports"],
        serde_json::json!(["rescale_it", "widen_it"])
    );
}

#[test]
fn refresh_does_not_let_a_python_helper_replace_a_name_the_loader_uses() {
    let (_root, dir) = bridged_file(
        "underscore-py",
        "mathx.py",
        "def scale(x: float, k: float) -> float:\n    return x * k\n",
    );
    let port = dir.join("src/port.rs");
    let source = std::fs::read_to_string(&port).unwrap();
    std::fs::write(
        &port,
        source
            + "\npub fn _native(x: i64) -> Result<i64, String> {\n    Ok(x)\n}\n\
               \npub fn helper_extra(x: i64) -> Result<i64, String> {\n    Ok(x)\n}\n",
    )
    .unwrap();
    assert_eq!(
        refresh_tool(&dir)["functions"],
        serde_json::json!(["scale", "Native", "helper_extra"])
    );
}

#[test]
fn refresh_names_a_function_that_is_not_an_export_in_snake_case_for_ruby_and_camel_case_for_ts() {
    let (_root, dir) = bridged_file(
        "not-an-export-rb",
        "mathx.rb",
        "module Mathx\n  # @param x [Integer]\n  # @return [Integer]\n  def self.scale(x)\n    x * 2\n  end\nend\n",
    );
    add_helper(&dir);
    let refreshed = refresh_tool(&dir);
    assert_eq!(
        refreshed["functions"],
        serde_json::json!(["scale", "helper_extra"])
    );
    assert_eq!(
        refreshed["not_exports"],
        serde_json::json!(["helper_extra"])
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains(r#"define_module_function("helper_extra", "#),
        "{lib}"
    );

    let dir = bridged("not-an-export-ts");
    add_helper(&dir);
    let refreshed = refresh_tool(&dir);
    std::fs::remove_dir_all(&dir).unwrap();
    assert_eq!(
        refreshed["functions"],
        serde_json::json!(["rangeOf", "words", "count", "helperExtra"])
    );
    assert_eq!(
        refreshed["not_exports"],
        serde_json::json!(["helper_extra"])
    );
}

#[test]
fn bridge_writes_a_crate_and_never_overwrites_it() {
    let dir = bridged("bridge");
    let manifest = Manifest::load(&dir).unwrap();
    let names: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, ["rangeOf", "words", "count"]);
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    // Structured results cross as JSON text; string lists cross natively.
    assert!(lib.contains("pub fn range_of(text: String, word: String) -> napi::Result<String>"));
    assert!(lib.contains("pub fn words(text: String) -> napi::Result<Vec<String>>"));
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(port.contains(
        "pub fn range_of(text: String, word: String) -> Result<serde_json::Value, String>"
    ));
    assert!(
        dir.join("src/utf16.rs").exists(),
        "util.ts uses string offsets"
    );
    let again = bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/util.ts",
        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(),
    });
    let again = again.unwrap_err().to_string();
    assert!(again.contains("never overwrites"), "{again}");
    assert!(
        again.contains(&format!(
            "Run `rust-anything refresh {}` to regenerate the bindings, pass --out or --name for a \
             new crate, or remove the folder to start over",
            dir.display()
        )),
        "{again}"
    );
    let blocked = bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/svelte.ts",
        kind: None,
        out: Some(dir.join("nope")),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    });
    assert!(blocked.unwrap_err().to_string().contains("blocked"));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn bridge_refuses_a_js_kind_for_a_unit_in_another_language() {
    let root = std::env::temp_dir().join(format!("rust-anything-kind-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("mathy.py"),
        "def add(a: int, b: int) -> int:\n    return a + b\n",
    )
    .unwrap();
    for (kind, name) in [(Kind::Napi, "napi"), (Kind::Wasm, "wasm")] {
        let err = bridge::bridge(&bridge::Options {
            root: &root,
            unit: "mathy.py",
            kind: Some(kind),
            out: None,
            name: None,
            force: false,
            keep: Vec::new(),
            lang: None,
            batch: Vec::new(),
            as_json: Vec::new(),
            allocator: Default::default(),
        })
        .unwrap_err()
        .to_string();
        assert_eq!(
            err,
            format!(
                "--kind {name} is for TS/JS units; mathy.py is Python and is bridged with PyO3"
            )
        );
        assert!(!root.join("rust").exists(), "nothing is written");
    }
    std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn diff_rejects_an_empty_recording() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("empty-recording");
    std::fs::write(dir.join(harness::CASES), "").unwrap();
    stand_in(&dir, false);
    let err = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap_err();
    std::fs::remove_dir_all(&dir).unwrap();
    assert!(
        err.to_string().contains("no recorded cases to compare"),
        "{err:#}"
    );
}

#[test]
fn record_rejects_a_device_on_host_before_saving_settings() {
    let dir = bridged("record-host-device");
    let manifest = dir.join(bridge::MANIFEST);
    let before = std::fs::read(&manifest).unwrap();
    let out = common::cli()
        .arg("record")
        .arg(&dir)
        .args(["--ignore-key-order", "--device", "x"])
        .output()
        .unwrap();
    let after = std::fs::read(&manifest).unwrap();
    std::fs::remove_dir_all(dir).unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.contains("`--device` needs `--profile android`"),
        "{stderr}"
    );
    assert_eq!(before, after, "record changed the manifest");
}

/// #1050: after its summary, `record` points functions that decode a parameter at real inputs.
#[test]
fn record_points_a_decoded_parameter_at_inputs() {
    if !common::have("node") {
        return;
    }
    let repo = std::env::temp_dir().join(format!("rust-anything-decoded-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("package.json"),
        r#"{ "name": "decoded", "private": true, "type": "module" }"#,
    )
    .unwrap();
    std::fs::write(
        repo.join("src/payload.ts"),
        "export function payloadDate(raw: string): string | null {\n  \
         try {\n    \
         const at = JSON.parse(Buffer.from(raw, \"base64url\").toString(\"utf8\")).at;\n    \
         const ms = Date.parse(at);\n    \
         return Number.isFinite(ms) ? new Date(ms).toISOString() : null;\n  \
         } catch { return null; }\n}\n\
         export function build(at: string): string {\n  return JSON.stringify({ at })\n}\n",
    )
    .unwrap();
    let dir = repo.join("rust/unit");
    bridge::bridge(&bridge::Options {
        root: &repo,
        unit: "src/payload.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: Some("decoded-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_rust-anything"))
        .arg("record")
        .arg(&dir)
        .args(["--count", "5"])
        .output()
        .unwrap();
    std::fs::remove_dir_all(&repo).unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        out.status.success(),
        "{stdout}{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let lines: Vec<&str> = stdout
        .lines()
        .filter(|l| l.contains("Decoded inside"))
        .collect();
    assert_eq!(
        lines,
        [
            "Decoded inside: payloadDate (`raw`): generated strings may miss cases that depend \
             on the decoded content. Record real payloads with `--inputs`."
        ],
        "{stdout}"
    );
    let summary = stdout.find("Recorded ").unwrap();
    assert!(stdout.find(lines[0]).unwrap() > summary, "{stdout}");
}

#[test]
fn record_and_diff_catch_a_behavior_change() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("diff");
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 120,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases - recorded.traps, 360);
    assert!(recorded.traps > 0);

    let diff = |dir: &Path| {
        harness::diff(&DiffOptions {
            crate_dir: dir,
            module: None,
            ignore_key_order: false,
            float_tolerance: None,
            node_args: &[],
        })
        .unwrap()
    };
    stand_in(&dir, true);
    let buggy = diff(&dir);
    assert!(buggy.failed > 0, "the tab bug must show up");
    assert!(buggy.mismatches.iter().all(|m| m["fn"] == "count"));
    for m in &buggy.mismatches {
        assert_eq!(m["at"]["channel"], "return", "{m}");
        assert_eq!(m["at"]["kind"], "value", "{m}");
        assert_eq!(m["at"]["path"], "$", "{m}");
    }
    assert_eq!(buggy.groups.len(), 1, "{:?}", buggy.groups);
    assert_eq!(buggy.groups[0].cases, buggy.failed);
    assert_eq!(buggy.groups[0].label(), "count: return $ (value)");

    let mut redacted = diff(&dir);
    rust_anything::mismatch::redact_diff(&mut redacted);
    let text = serde_json::to_string(&redacted).unwrap();
    for m in &buggy.mismatches {
        for arg in m["args"].as_array().unwrap() {
            assert!(!text.contains(&arg.to_string()), "{arg} in {text}");
        }
    }
    assert!(
        !text.contains("\"expected\"") && !text.contains("\"args\""),
        "{text}"
    );
    assert!(redacted.mismatches.iter().all(|m| m["at"]["path"] == "$"));
    assert_eq!(redacted.groups.len(), 1);

    std::fs::write(
        dir.join("index.cjs"),
        "exports.rangeOf = (text, word) => { const start = text.indexOf(word) + 1; return { start, end: start - 1 + word.length, rest: text.slice(start - 1) } }\n\
         exports.words = text => [...text.matchAll(/(?<=\\$)\\w+/g)].map(m => m[0])\n\
         exports.count = text => [...text].filter(c => / /.test(c)).length\n",
    )
    .unwrap();
    let shifted = diff(&dir);
    assert!(shifted.failed > 0);
    for m in &shifted.mismatches {
        assert_eq!(m["fn"], "rangeOf", "{m}");
        assert_eq!(m["at"]["path"], "$.start", "{m}");
    }
    assert_eq!(shifted.groups.len(), 1, "{:?}", shifted.groups);

    stand_in(&dir, false);
    let fixed = diff(&dir);
    assert_eq!((fixed.passed, fixed.failed), (recorded.cases, 0));
    assert!(fixed.groups.is_empty());
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn diff_replays_large_strings_with_lone_surrogates() {
    if !common::have("node") {
        return;
    }
    let unsplit = 0xd800;
    let mut units = vec![u16::from(b'a'); 200_000];
    units.push(unsplit);
    let dir = bridged("long-utf16");
    let input = serde_json::json!({
        "fn": "inspect",
        "args": [{ "$utf16": units }],
        "ok": [200_001, unsplit]
    });
    std::fs::write(dir.join(harness::CASES), input.to_string()).unwrap();
    std::fs::write(
        dir.join("index.cjs"),
        "exports.inspect = s => [s.length, s.charCodeAt(s.length - 1)]",
    )
    .unwrap();
    let result = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    });
    std::fs::remove_dir_all(&dir).unwrap();
    let outcome = result.unwrap();
    assert_eq!(
        outcome.passed,
        1,
        "{:?}",
        outcome
            .mismatches
            .iter()
            .map(|m| &m["actual"])
            .collect::<Vec<_>>()
    );
}

#[test]
fn float_tolerance_preserves_object_key_order_unless_requested() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("tolerance-order");
    std::fs::write(
        dir.join(harness::CASES),
        r#"{"fn":"f","args":[],"ok":{"nested":{"first":0.3,"second":1}}}"#,
    )
    .unwrap();
    std::fs::write(
        dir.join("index.cjs"),
        "exports.f = () => ({ nested: { second: 1, first: 0.30000000000000004 } })",
    )
    .unwrap();
    let mut opts = DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: Some(1e-9),
        node_args: &[],
    };
    let strict = harness::diff(&opts).unwrap();
    opts.ignore_key_order = true;
    let unordered = harness::diff(&opts).unwrap();
    std::fs::remove_dir_all(dir).unwrap();
    assert_eq!(strict.failed, 1);
    assert_eq!(unordered.passed, 1);
}

#[test]
fn shadow_returns_the_original_and_reports_mismatches() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("shadow");
    stand_in(&dir, true);
    let out = shadow::shadow(&dir, None).unwrap();
    let script = dir.join("use.ts");
    // Relative, with `/`: a Windows path pasted into the string turns its `\` into escapes.
    let module = out
        .path
        .canonical()
        .unwrap()
        .strip_prefix(dir.canonical().unwrap())
        .unwrap()
        .to_string_lossy()
        .replace('\\', "/");
    std::fs::write(
        &script,
        format!(
            "import {{ count, shadowStats, onMismatch }} from './{module}'\n\
             const seen: string[] = []\n\
             onMismatch(m => seen.push(m.fn))\n\
             console.log(JSON.stringify([count('a b'), count('a\\tb'), shadowStats.calls, seen]))\n"
        ),
    )
    .unwrap();
    let run = |mode: &str| {
        let o = Command::new("node")
            .arg(&script)
            .env("RUST_ANYTHING_MODE", mode)
            .output()
            .unwrap();
        assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
        String::from_utf8_lossy(&o.stdout).trim().to_string()
    };
    // Shadow: callers get the original's answers; the tab case is reported.
    assert_eq!(run("shadow"), r#"[1,0,2,["count"]]"#);
    assert_eq!(run("old"), r#"[1,0,0,[]]"#);
    // New: the stand-in answers, bug included.
    assert_eq!(run("new"), r#"[1,1,0,[]]"#);
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn mcp_app_record_refuses_a_string_argument_that_is_not_a_string() {
    // Issue #671: `as_str()` dropped a wrong-typed `ready`, `name`, `db_reset` or `db_dump` without a
    // word, so the recording went ahead with the setting silently missing.
    for (key, value) in [
        ("ready", serde_json::json!(42)),
        ("name", serde_json::json!(7)),
        ("db_reset", serde_json::json!(["sqlite3", "app.db"])),
        ("db_dump", serde_json::json!(true)),
    ] {
        let response = rust_anything::mcp::handle(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": 11,
            "method": "tools/call",
            "params": {
                "name": "app_record",
                "arguments": { "repo": fixture(), "run": ["python3", "server.py"], key: value },
            },
        }))
        .unwrap();
        assert_eq!(response["result"]["isError"], true, "{key}: {response}");
        let text = response["result"]["content"][0]["text"]
            .as_str()
            .unwrap_or_default();
        assert!(
            text.contains(&format!("`{key}` must be a string")),
            "{key} is named: {text}"
        );
    }
}

#[test]
fn mcp_app_record_with_no_http_names_ready_in_its_refusal() {
    // Issue #666: the check covers `--ready`, but the message left it out, and the CLI never shows
    // this one (clap refuses the pair first), so the MCP tool is where a caller sees it.
    let response = rust_anything::mcp::handle(&serde_json::json!({
        "jsonrpc": "2.0",
        "id": 9,
        "method": "tools/call",
        "params": {
            "name": "app_record",
            "arguments": {
                "repo": fixture(),
                "run": ["python3", "server.py"],
                "http": false,
                "ready": "GET /health",
            },
        },
    }))
    .unwrap();
    assert_eq!(response["result"]["isError"], true, "{response}");
    let text = response["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    // `--ready` is a prefix of `--ready-timeout`, so `contains` passes on the old message either
    // way: the list has to end with the flag.
    assert!(
        text.trim_end().ends_with("--ready"),
        "the refusal names every setting it checks: {text}"
    );
}

#[test]
fn mcp_runs_analyze() {
    let response = rust_anything::mcp::handle(&serde_json::json!({
        "jsonrpc": "2.0",
        "id": 7,
        "method": "tools/call",
        "params": { "name": "analyze", "arguments": { "root": fixture() } },
    }))
    .unwrap();
    assert_eq!(response["result"]["isError"], false);
    assert_eq!(
        response["result"]["structuredContent"]["schema"],
        "rust-anything/analyze@1"
    );
}

#[test]
fn record_follows_bundler_style_imports() {
    if !common::have("node") {
        return;
    }
    // `fs.ts` imports `./util.js`, a file that only exists as `util.ts`.
    let dir = std::env::temp_dir().join(format!("rust-anything-resolve-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/fs.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 5,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    // The paths do not exist: every call throws, but the module loaded and ran.
    assert_eq!(recorded.cases - recorded.traps, 5);
    assert_eq!(recorded.errors, recorded.cases);
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn record_registers_its_resolver_from_a_path_with_url_delimiters() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("record #1 % café");
    let result = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 2,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    });
    std::fs::remove_dir_all(&dir).unwrap();
    let recorded = result.unwrap();
    assert!(recorded.cases > 0);
    assert_eq!(recorded.errors, 0);
}

#[test]
fn async_functions_get_async_bindings() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/async");
    for kind in [Kind::Napi, Kind::Wasm] {
        let dir = std::env::temp_dir().join(format!(
            "rust-anything-async-{kind:?}-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        bridge::bridge(&bridge::Options {
            root: &root,
            unit: "src/pipeline.ts",
            kind: Some(kind),
            out: Some(dir.clone()),
            name: None,
            force: false,
            keep: Vec::new(),
            lang: None,
            batch: Vec::new(),
            as_json: Vec::new(),
            allocator: Default::default(),
        })
        .unwrap();
        let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
        assert!(port.contains("pub async fn count_words(text: String) -> Result<f64, String>"));
        assert!(port.contains("pub fn upper(text: String) -> Result<String, String>"));
        let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
        assert!(
            lib.contains("pub async fn count_words(text: String)"),
            "{lib}"
        );
        let cargo = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap();
        match kind {
            Kind::Napi => {
                assert!(cargo.contains("features = [\"async\"]") && cargo.contains("futures"))
            }
            Kind::Wasm => assert!(cargo.contains("wasm-bindgen-futures")),
            Kind::Pyo3 | Kind::CAbi | Kind::Ffi => {}
        }
        let index = std::fs::read_to_string(dir.join("index.cjs")).unwrap();
        assert!(
            index.contains("normalize: [[1, 0], 'json', true]"),
            "{index}"
        );
        assert!(index.contains("  countWords: [true, [0]],"), "{index}");
        std::fs::remove_dir_all(&dir).unwrap();
    }
}

#[test]
fn benchmark_awaits_async_typescript_calls_and_counts_rejections() {
    if !common::have("node") {
        return;
    }
    let root = std::env::temp_dir().join(format!(
        "rust-anything-ts-async-bench-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("main.mts"),
        "export async function delayed(): Promise<number> { await new Promise(r => setTimeout(r, 15)); throw new Error('intentional'); }",
    )
    .unwrap();
    let dir = root.join("bridge");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "main.mts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    std::fs::write(
        dir.join(harness::CASES),
        r#"{"fn":"delayed","args":[],"error":"intentional"}"#,
    )
    .unwrap();
    std::fs::write(
        dir.join("index.cjs"),
        "exports.delayed = async () => { await new Promise(r => setTimeout(r, 15)); throw new Error('intentional') }",
    )
    .unwrap();
    common::mark_built(&dir);
    let result = harness::bench(&harness::BenchOptions {
        crate_dir: &dir,
        min_ms: 1,
        resolve_from: None,
        node_args: &[],
    });
    std::fs::remove_dir_all(root).unwrap();
    let rows = result.unwrap();
    assert_eq!(rows.len(), 1);
    assert!(rows[0].original_ns > 5_000_000.0, "{rows:?}");
    assert!(rows[0].rust_ns > 5_000_000.0, "{rows:?}");
}

#[test]
fn benchmark_marks_functions_whose_cases_do_not_match() {
    // #341: a function the port does not match (here: wrong, as `unimplemented!` would panic) was
    // timed with the rest, and the cost of its failure set the overall verdict.
    if !common::have("node") {
        return;
    }
    let root = std::env::temp_dir().join(format!(
        "rust-anything-ts-bench-failing-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("main.mts"),
        "export function double(n: number): number { return n * 2; }\n\
         export function triple(n: number): number { return n * 3; }\n",
    )
    .unwrap();
    let dir = root.join("bridge");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "main.mts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    std::fs::write(
        dir.join(harness::CASES),
        "{\"fn\":\"double\",\"args\":[2],\"ok\":4}\n{\"fn\":\"triple\",\"args\":[2],\"ok\":6}\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("index.cjs"),
        "exports.double = (n) => n * 2\nexports.triple = (n) => { throw new Error('not implemented') }\n",
    )
    .unwrap();
    common::mark_built(&dir);
    let result = harness::bench(&harness::BenchOptions {
        crate_dir: &dir,
        min_ms: 1,
        resolve_from: None,
        node_args: &[],
    });
    std::fs::remove_dir_all(root).unwrap();
    let rows = result.unwrap();
    let failing: Vec<(&str, bool)> = rows.iter().map(|r| (r.name.as_str(), r.failing)).collect();
    assert_eq!(failing, [("double", false), ("triple", true)], "{rows:?}");
    let verdict = harness::verdict(&rows, rust_anything::lang::Lang::Ts, &dir);
    assert_eq!(verdict.left_out, ["triple"]);
    assert!(
        (verdict.speedup - rows[0].speedup).abs() < 1e-9,
        "{verdict:?}"
    );
}

#[test]
fn classes_are_bridged_recorded_and_replayed() {
    if !common::have("node") {
        return;
    }
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/classes");
    let dir = std::env::temp_dir().join(format!("rust-anything-classes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/stats.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(outcome.exports, ["class TextStats", "class LruCache"]);
    let manifest = Manifest::load(&dir).unwrap();
    assert!(
        manifest
            .js_only
            .iter()
            .any(|j| j.name == "Blocked" && j.reason.contains("extends"))
    );
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(port.contains("pub fn new(capacity: f64) -> Result<Self, String>"));
    assert!(port.contains("pub fn get(&mut self, key: String) -> Result<Option<String>, String>"));
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("#[napi(constructor)]") && lib.contains("inner: port::LruCache"));

    // Record scenarios (the TS uses parameter properties: Node needs to transform it).
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 150,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases, 300);
    // A JS stand-in with an LRU bug: `get` does not refresh recency.
    std::fs::write(
        dir.join("index.cjs"),
        "class TextStats { constructor(s = '\\n') { this.s = s; this.w = 0; this.l = 0; this.long = '' }\n\
         add(t) { const p = t.split(this.s); this.l += p.length; for (const x of p) for (const w of x.split(/\\s+/).filter(Boolean)) { this.w++; if (w.length > this.long.length) this.long = w } return this.w }\n\
         stats() { return { words: this.w, lines: this.l } } longestWord() { return this.long } reset() { this.w = 0; this.l = 0; this.long = '' } }\n\
         class LruCache { constructor(c) { if (!(c >= 1)) throw new RangeError('x'); this.c = c; this.m = new Map() }\n\
         get(k) { return this.m.get(k) }\n\
         set(k, v) { this.m.delete(k); this.m.set(k, v); const e = []; while (this.m.size > this.c) { const o = this.m.keys().next().value; this.m.delete(o); e.push(o) } return e }\n\
         keys() { return [...this.m.keys()] } }\n\
         module.exports = { TextStats, LruCache }\n",
    )
    .unwrap();
    common::mark_built(&dir);
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert!(diff.failed > 0, "the recency bug must show up");
    assert!(diff.mismatches.iter().all(|m| m["fn"] == "LruCache"));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn recording_substitutes_typescript_extensions_from_emitted_module_imports() {
    if !common::have("node") {
        return;
    }
    let root = std::env::temp_dir().join(format!(
        "rust-anything-ts-extensions-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(root.join("esm.mts"), "export const value: number = 2;").unwrap();
    std::fs::write(
        root.join("common.cts"),
        "module.exports = 40 satisfies number;",
    )
    .unwrap();
    std::fs::write(
        root.join("main.mts"),
        "import { value } from './esm.mjs'; import common from './common.cjs'; export function answer(): number { return value + common; }",
    )
    .unwrap();
    let dir = root.join("bridge");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "main.mts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let result = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 1,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    });
    let evidence = std::fs::read_to_string(dir.join(harness::CASES));
    std::fs::remove_dir_all(root).unwrap();
    result.unwrap();
    assert!(evidence.unwrap().contains(r#""ok":42"#));
}

#[test]
fn tsconfig_aliases_are_followed() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/aliases");
    let report = rust_anything::analyze::analyze(&root).unwrap();
    let greet = report
        .units
        .iter()
        .find(|u| u.id == "src/greet.ts")
        .unwrap();
    assert_eq!(greet.internal_deps, ["src/lib/", "src/util/"]);
    if !common::have("node") {
        return;
    }
    let dir = std::env::temp_dir().join(format!("rust-anything-alias-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/greet.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 5,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!((recorded.cases - recorded.traps, recorded.errors), (5, 0));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn record_prefers_an_exact_tsconfig_alias_to_a_matching_wildcard() {
    if !common::have("node") {
        return;
    }
    let root =
        std::env::temp_dir().join(format!("rust-anything-exact-alias-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(root.join("package.json"), r#"{"type":"module"}"#).unwrap();
    std::fs::write(
        root.join("tsconfig.json"),
        r#"{"compilerOptions":{"paths":{"@demo*":["./src/wild*"],"@demo":["./src/exact.ts"]}}}"#,
    )
    .unwrap();
    std::fs::write(root.join("src/wild.ts"), "export const value = 'wild';").unwrap();
    std::fs::write(root.join("src/exact.ts"), "export const value = 'exact';").unwrap();
    std::fs::write(
        root.join("src/main.ts"),
        "import { value } from '@demo'; export function selected(): string { return value; }",
    )
    .unwrap();
    let dir = root.join("bridge");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/main.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let result = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 1,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    });
    let evidence = std::fs::read_to_string(dir.join(harness::CASES));
    std::fs::remove_dir_all(root).unwrap();
    result.unwrap();
    assert!(evidence.unwrap().contains(r#""ok":"exact""#));
}

#[test]
fn record_resolves_workspace_packages_to_source() {
    if !common::have("node") {
        return;
    }
    // `@m/b` imports `@m/a` by name; `@m/a` has no build output (`dist/` does not exist).
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/monorepo");
    let dir = std::env::temp_dir().join(format!("rust-anything-monorepo-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "packages/b/src/titles.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 10,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!((recorded.cases - recorded.traps, recorded.errors), (10, 0));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn python_required_optional_port_local_type_compiles() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/python");
    let dir =
        std::env::temp_dir().join(format!("rust-anything-python-local-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let _gone = common::Scratch(dir.clone());
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/textkit/",
        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();
    let mut manifest = Manifest::load(&dir).unwrap();
    let clipped = manifest
        .exports
        .iter_mut()
        .find(|f| f.name == "clipped")
        .unwrap();
    clipped.params[1].optional = false;
    clipped.params[1].default = None;
    manifest.save(&dir).unwrap();
    std::fs::write(
        dir.join("src/port.rs"),
        "pub type Settings = serde_json::Value;\n\
         pub fn clipped(text: String, limits: Option<Settings>) -> String { let _ = limits; text }\n",
    )
    .unwrap();
    bridge::refresh(&dir).unwrap();
    let output = Command::new("cargo")
        .arg("check")
        .current_dir(&dir)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    std::fs::remove_dir_all(&dir).unwrap();
}

fn error_checks(dir: &Path, fails: &str) -> Vec<rust_anything::gate::Check> {
    let checks = rust_anything::error_paths::checks(dir, &Manifest::load(dir).unwrap());
    let errors = &checks[0];
    assert_eq!(errors.name, "error cases");
    assert!(errors.passed, "{errors:?}");
    assert!(
        errors.detail.starts_with("the 1 function that fails")
            || errors.detail.starts_with("each of the"),
        "{fails} fails in the original: {errors:?}"
    );
    checks
}

#[test]
fn python_modules_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/python");
    let dir = std::env::temp_dir().join(format!("rust-anything-python-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/textkit/",
        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();
    assert_eq!(outcome.kind, Kind::Pyo3);
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<&str> = manifest.js_only.iter().map(|j| j.name.as_str()).collect();
    assert_eq!(kept, ["walk", "apply", "configure", "Limits"]);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    // A literal default stays a plain value; `None` as default is an Option.
    assert!(
        port.contains("pub fn slugify(text: String, sep: String, max_length: Option<i64>)"),
        "{port}"
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains(r#"signature = (text, sep=String::from("-"), *, max_length=None)"#),
        "{lib}"
    );
    // An optional object parameter binds as `Option<Bound>` so `None` is accepted.
    assert!(lib.contains("limits: Option<Bound<'_, PyAny>>"), "{lib}");
    assert!(lib.contains(r#"signature = (text, limits=None)"#), "{lib}");
    assert!(lib.contains("#[pyclass(name = \"Stack\")]"));
    let build_rs = std::fs::read_to_string(dir.join("build.rs")).unwrap();
    assert!(build_rs.contains("dynamic_lookup"), "{build_rs}");
    if !common::have("python3") {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 60,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 200);
    error_checks(&dir, "chunk");
    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    let start = port.find("pub fn chunk(").unwrap();
    let body = start + port[start..].find('{').unwrap() + 1;
    let mut panicky = port.clone();
    panicky.insert_str(body, "\n    let _ = \"1\".parse::<i64>().unwrap();");
    std::fs::write(&port_path, &panicky).unwrap();
    let checks = error_checks(&dir, "chunk");
    assert!(
        !checks[1].passed && checks[1].detail.contains("in chunk"),
        "{checks:?}"
    );
    std::fs::write(&port_path, &port).unwrap();
    // A pure-Python stand-in for the built package: `page_count` truncates instead of flooring.
    let package = dir.join("python/textkit_rs");
    std::fs::create_dir_all(&package).unwrap();
    let original = std::fs::read_to_string(root.join("src/textkit/words.py")).unwrap();
    let stack = std::fs::read_to_string(root.join("src/textkit/stack.py")).unwrap();
    let buggy = original.replace(
        "return -(-total // per_page)",
        "return int(-(-total / per_page))",
    );
    std::fs::write(package.join("__init__.py"), format!("{buggy}\n{stack}")).unwrap();
    common::mark_built(&dir);
    let diff = |dir: &Path| {
        harness::diff(&DiffOptions {
            crate_dir: dir,
            module: None,
            ignore_key_order: false,
            float_tolerance: None,
            node_args: &[],
        })
        .unwrap()
    };
    let buggy = diff(&dir);
    assert!(
        buggy.failed > 0 && buggy.mismatches.iter().all(|m| m["fn"] == "page_count"),
        "{:?}",
        buggy.mismatches
    );
    std::fs::write(package.join("__init__.py"), format!("{original}\n{stack}")).unwrap();
    let fixed = diff(&dir);
    assert_eq!(fixed.failed, 0, "{:?}", fixed.mismatches);
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn module_is_refused_for_a_python_crate() {
    let root = std::env::temp_dir().join(format!(
        "rust-anything-module-python-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("pyproject.toml"),
        "[project]\nname = \"t\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    std::fs::write(
        root.join("words.py"),
        "def words(s: str) -> int:\n    return len(s.split())\n",
    )
    .unwrap();
    std::fs::write(root.join("built.js"), "module.exports = {}\n").unwrap();
    let bridged = common::cli()
        .args(["bridge", ".", "words.py"])
        .current_dir(&root)
        .output()
        .unwrap();
    assert!(
        bridged.status.success(),
        "{}",
        String::from_utf8_lossy(&bridged.stderr)
    );
    let crate_dir = root.join("rust/words-rs");

    for args in [
        vec!["record", "--count", "2", "--module", "built.js"],
        vec!["diff", "--module", "built.js"],
    ] {
        let mut cmd = common::cli();
        cmd.arg(args[0]).arg(&crate_dir).args(&args[1..]);
        let out = cmd.current_dir(&root).output().unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "{stderr}");
        assert!(stderr.contains("--module is for TS/JS crates"), "{stderr}");
        assert!(stderr.contains("Python"), "{stderr}");
    }
    // Nothing ran: no recording was written for the refused `record`.
    assert!(!crate_dir.join("cases.jsonl").exists());
    std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn c_bridge_string_helper_does_not_collide_with_source_names() {
    let root = std::env::temp_dir().join(format!("rust-anything-c-names-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("names.c"),
        "int c_str(const char *c_str) { return c_str != 0; }\n",
    )
    .unwrap();
    let dir = root.join("bridge");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "names.c",
        kind: None,
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: Some(rust_anything::lang::Lang::C),
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let status = Command::new("cargo")
        .args(["check", "--quiet"])
        .current_dir(&dir)
        .status()
        .unwrap();
    std::fs::remove_dir_all(root).unwrap();
    assert!(status.success());
}

#[test]
fn c_units_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/c");
    let dir = std::env::temp_dir().join(format!("rust-anything-c-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let options = |batch: Vec<String>| bridge::Options {
        root: &root,
        unit: "src/text.c",
        kind: None,
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch,
        as_json: Vec::new(),
        allocator: Default::default(),
    };
    let batch = bridge::bridge(&options(vec!["count_words:s".into()]))
        .unwrap_err()
        .to_string();
    assert_eq!(batch, "`--batch` is not available for C units yet");
    assert!(!dir.exists());
    let outcome = bridge::bridge(&options(Vec::new())).unwrap();
    assert_eq!(outcome.kind, Kind::CAbi);
    let before = std::fs::read_to_string(dir.join("rust-anything.json")).unwrap();
    let refresh_batch = bridge::add_batches(&dir, &["count_words:s".into()])
        .unwrap_err()
        .to_string();
    assert_eq!(refresh_batch, "`--batch` is not available for C units yet");
    assert_eq!(
        std::fs::read_to_string(dir.join("rust-anything.json")).unwrap(),
        before
    );
    let manifest = Manifest::load(&dir).unwrap();
    // A returned pointer needs an ownership design: it stays in C.
    let kept: Vec<&str> = manifest.js_only.iter().map(|j| j.name.as_str()).collect();
    assert_eq!(kept, ["upper_copy"]);
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains("pub extern \"C\" fn count_words(s: *const c_char) -> usize"),
        "{lib}"
    );
    let header = std::fs::read_to_string(dir.join("include/text_rs.h")).unwrap();
    assert!(
        header.contains("bool is_palindrome(const char *s);"),
        "{header}"
    );
    if !(common::have("cc") && common::have("python3")) {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 40,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases - recorded.traps, 120);
    // `vowels` forgets upper case: the diff must notice.
    std::fs::write(
        dir.join("src/port.rs"),
        "pub fn count_words(s: Option<&[u8]>) -> usize {\n    s.map_or(0, |s| s.split(|b| b.is_ascii_whitespace() || *b == 0x0b).filter(|w| !w.is_empty()).count())\n}\n\
         pub fn vowels(s: Option<&[u8]>) -> std::ffi::c_int {\n    s.map_or(-1, |s| s.iter().filter(|b| b\"aeiou\".contains(b)).count() as std::ffi::c_int)\n}\n\
         pub fn is_palindrome(s: Option<&[u8]>) -> bool {\n    s.is_some_and(|s| s.iter().eq(s.iter().rev()))\n}\n",
    )
    .unwrap();
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert!(diff.missing.is_empty());
    assert!(diff.failed > 0 && diff.failed < 40, "{diff:?}");
    assert!(
        diff.mismatches.iter().all(|m| m["fn"] == "vowels"),
        "{diff:?}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn go_packages_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/go");
    let dir = std::env::temp_dir().join(format!("rust-anything-go-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "strkit/",
        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();
    assert_eq!(outcome.kind, Kind::Ffi);
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<&str> = manifest.js_only.iter().map(|j| j.name.as_str()).collect();
    assert_eq!(kept, ["Join"]);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(
        port.contains("pub fn parse_port(s: String) -> Result<i64, String>"),
        "{port}"
    );
    let wrapper = std::fs::read_to_string(dir.join("go/strkit.go")).unwrap();
    assert!(
        wrapper.contains("func ParsePort(raArg0 string) (int, error) {"),
        "{wrapper}"
    );
    assert!(wrapper.contains("type Point struct"), "{wrapper}");
    // Batches: a map result cannot be batched; the others get a handle type in the package.
    assert!(bridge::add_batches(&dir, &["WordFreq:text".into()]).is_err());
    bridge::add_batches(&dir, &["Slugify:s".into(), "ParsePort:s".into()]).unwrap();
    let wrapper = std::fs::read_to_string(dir.join("go/strkit.go")).unwrap();
    assert!(
        wrapper.contains("func NewSlugifyBatch(items []string) *SlugifyBatch {"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("func (b *SlugifyBatch) Run(max int) []string {"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("func (b *ParsePortBatch) Rank(min float64) ([]int, error) {"),
        "{wrapper}"
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("static GLOBAL: mimalloc::MiMalloc"), "{lib}");
    let cargo = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap();
    assert!(!cargo.contains("staticlib"), "{cargo}");
    if !common::have("go") {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 100, "{recorded:?}");
    assert!(recorded.errors > 0, "ParsePort returns errors");
    assert!(error_checks(&dir, "ParsePort")[1].passed);
    // A port where every function fails: the diff must run through the Go wrapper and say so.
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.passed, 0, "{diff:?}");
    assert_eq!(diff.total, recorded.cases);
    let _ = std::fs::remove_dir_all(&dir);
}

/// `[4]int` and `[32]byte` cross like slices, and a list of another length is refused by the
/// driver instead of padded or cut by encoding/json (#1044).
#[test]
fn go_fixed_size_arrays_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/go");
    let dir = std::env::temp_dir().join(format!("rust-anything-go-arrays-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "arrays/",
        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();
    let manifest = Manifest::load(&dir).unwrap();
    assert!(manifest.js_only.is_empty(), "{:?}", manifest.js_only);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(
        port.contains("pub fn rev(a: Vec<i64>) -> Result<Vec<i64>, String>"),
        "{port}"
    );
    assert!(
        port.contains("pub fn digest(s: String) -> Result<Vec<i64>, String>"),
        "{port}"
    );
    let wrapper = std::fs::read_to_string(dir.join("go/arrays.go")).unwrap();
    assert!(
        wrapper.contains("func Rev(raArg0 [4]int) [4]int {"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("func Digest(raArg0 string) [32]byte {"),
        "{wrapper}"
    );
    assert!(
        port.contains("pub fn scale(a: Vec<f64>, k: f64) -> Result<Vec<f64>, String>"),
        "{port}"
    );
    if !common::have("go") {
        return;
    }
    // A NaN inside an array argument reaches the port as it reached the original.
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"Scale\", \"args\": [[{\"$num\": \"NaN\"}, 1.5], 2]}
         {\"fn\": \"Size\", \"args\": [[{\"$num\": \"NaN\"}, 2.5]]}
",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.per_function["Rev"] > 10, "{recorded:?}");
    // Items in a byte's range: one out of it would make Go refuse the whole `[8]byte`.
    assert!(recorded.per_function["Sum"] > 10, "{recorded:?}");
    // The list one item too long is not called with four of its items: the driver refuses it.
    assert!(recorded.inapplicable > 0, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    for line in cases.lines() {
        let case: serde_json::Value = serde_json::from_str(line).unwrap();
        if case["fn"] == "Rev" {
            assert_eq!(case["args"][0].as_array().map(Vec::len), Some(4), "{line}");
            assert_eq!(case["ok"].as_array().map(Vec::len), Some(4), "{line}");
        } else if case["fn"] == "Digest" {
            assert_eq!(case["ok"].as_array().map(Vec::len), Some(32), "{line}");
        } else if case["fn"] == "Sum" {
            let items = case["args"][0].as_array().unwrap();
            assert_eq!(items.len(), 8, "{line}");
            assert!(
                items
                    .iter()
                    .all(|v| (0..=255).contains(&v.as_i64().unwrap())),
                "{line}"
            );
        }
    }
    assert!(cases.contains(r#"{"$num":"NaN"}"#), "{cases}");
    let ported = |rev: &str| {
        port.replace("unimplemented!(\"port `Rev` from arrays/arrays.go\")", rev)
            .replace(
                "unimplemented!(\"port `Digest` from arrays/arrays.go\")",
                "let mut d = [0u8; 32]; for (i, b) in s.bytes().enumerate() { d[i % 32] ^= b; \
             let j = (i * 7 + 3) % 32; d[j] = d[j].wrapping_add(b); } \
             Ok(d.iter().map(|&b| i64::from(b)).collect())",
            )
            .replace(
                "unimplemented!(\"port `Sum` from arrays/arrays.go\")",
                "Ok(b.iter().sum())",
            )
            .replace(
                "unimplemented!(\"port `Scale` from arrays/arrays.go\")",
                "Ok(a.iter().map(|x| x * k).collect())",
            )
            .replace(
                "unimplemented!(\"port `Size` from arrays/arrays.go\")",
                "Ok(xs.len() as i64)",
            )
    };
    let diff_options = DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    };
    let good = ported("let mut a = a; a.reverse(); Ok(a)");
    assert_ne!(good, port, "the port stubs were not found");
    std::fs::write(dir.join("src/port.rs"), &good).unwrap();
    harness::build(&dir).unwrap();
    let diff = harness::diff(&diff_options).unwrap();
    assert_eq!(diff.failed, 0, "{diff:?}");
    assert_eq!(diff.passed, recorded.cases, "{diff:?}");
    // A port that answers with five items is not cut to four on its way back.
    std::fs::write(
        dir.join("src/port.rs"),
        ported("let mut a = a; a.reverse(); a.push(0); Ok(a)"),
    )
    .unwrap();
    harness::build(&dir).unwrap();
    let diff = harness::diff(&diff_options).unwrap();
    assert_eq!(diff.failed, recorded.per_function["Rev"], "{diff:?}");
    assert!(
        diff.mismatches.iter().all(|m| m["fn"] == "Rev"
            && m["actual"]["panic"]
                .as_str()
                .is_some_and(|p| p.contains("wrong length"))),
        "{diff:?}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn ruby_modules_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ruby");
    let dir = std::env::temp_dir().join(format!("rust-anything-ruby-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "lib/textkit/",
        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();
    assert_eq!(outcome.kind, Kind::Ffi);
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<&str> = manifest.js_only.iter().map(|j| j.name.as_str()).collect();
    assert_eq!(kept, ["each_word"]);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    // YARD types, a literal default kept as a plain value, and `nil` as an Option.
    assert!(
        port.contains("pub fn slugify(text: String, sep: String, max: Option<i64>)"),
        "{port}"
    );
    let wrapper = std::fs::read_to_string(dir.join("ruby/textkit_rs.rb")).unwrap();
    assert!(
        wrapper.contains("class << Textkit::Words\n  def slugify(text, sep = \"-\", max: nil)"),
        "{wrapper}"
    );
    // Batches keep the original's other parameters, defaults and keywords.
    bridge::add_batches(&dir, &["slugify:text".into(), "page_count:total".into()]).unwrap();
    let wrapper = std::fs::read_to_string(dir.join("ruby/textkit_rs.rb")).unwrap();
    assert!(
        wrapper.contains("class Textkit::Words::SlugifyBatch"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("def run(sep = \"-\", max: nil)"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("def rank(per_page = 10, min: 0)"),
        "{wrapper}"
    );
    if !common::have_ruby_3() {
        return;
    }
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"digit\", \"args\": [\"7\"]}\n\
         {\"fn\": \"digit\", \"args\": [\"abc\"]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 100, "{recorded:?}");
    // `page_count` raises ArgumentError; `digit` raises Textkit::ParseError.
    assert!(recorded.errors > 0);
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(
        cases.contains(r#"{"fn":"digit","args":["7"],"ok":7}"#),
        "{cases}"
    );
    assert!(
        cases.contains(r#""error_type":"Textkit::ParseError""#),
        "{cases}"
    );
    assert!(error_checks(&dir, "the fixture")[1].passed);
    let mut port = port;
    for (name, body) in [
        (
            "page_count",
            "if per_page <= 0 { return Err(\"ArgumentError: per_page must be positive\".into()); } \
             let q = total.div_euclid(per_page); let r = total.rem_euclid(per_page); \
             Ok(q + i64::from(r > 0))",
        ),
        (
            "digit",
            "if text.len() == 1 && text.as_bytes()[0].is_ascii_digit() { \
             Ok(i64::from(text.as_bytes()[0] - b'0')) } else { \
             Err(\"Textkit::ParseError: not a digit\".into()) }",
        ),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from lib/textkit/nums.rb\")");
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let (diff, counts) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.total, recorded.cases);
    assert!(diff.passed > 0, "{diff:?}");
    for f in ["digit", "page_count"] {
        let (p, t) = counts[f];
        assert!(t > 0 && p == t, "{f}: {p}/{t}");
    }
    assert!(
        !diff
            .mismatches
            .iter()
            .any(|m| matches!(m["fn"].as_str(), Some("digit" | "page_count"))),
        "{:?}",
        diff.mismatches
    );
    // Unported functions panic, which Ruby sees as a RuntimeError.
    assert!(
        diff.failed > 0
            && diff.mismatches.iter().all(|m| {
                !matches!(m["fn"].as_str(), Some("digit" | "page_count"))
                    && m["actual"]["error"]
                        .as_str()
                        .is_some_and(|e| e.contains("Rust panic:"))
            }),
        "{:?}",
        diff.mismatches
    );

    let echo_port = port.replace(
        "if text.len() == 1 && text.as_bytes()[0].is_ascii_digit() { \
         Ok(i64::from(text.as_bytes()[0] - b'0')) } else { \
         Err(\"Textkit::ParseError: not a digit\".into()) }",
        "Err(text)",
    );
    assert_ne!(echo_port, port);
    std::fs::write(dir.join("src/port.rs"), echo_port).unwrap();
    harness::build(&dir).unwrap();
    let check_rb = dir.join("check_errors.rb");
    std::fs::write(
        &check_rb,
        format!(
            r#"require {:?}
module Textkit
  class ParseError < StandardError; end
end

cases = [
  ["ArgumentError: bad", "ArgumentError", "bad"],
  ["Textkit::ParseError: bad", "Textkit::ParseError", "bad"],
  ["::ArgumentError: bad", "RuntimeError", "::ArgumentError: bad"],
  ["Textkit::ArgumentError: bad", "RuntimeError", "Textkit::ArgumentError: bad"],
  ["Textkit::Nums: bad", "RuntimeError", "Textkit::Nums: bad"],
  ["String: bad", "RuntimeError", "String: bad"],
  ["Textkit::Missing: bad", "RuntimeError", "Textkit::Missing: bad"],
  ["Textkit::ParseError::: bad", "RuntimeError", "Textkit::ParseError::: bad"],
  ["bad_name: bad", "RuntimeError", "bad_name: bad"],
  ["plain error", "RuntimeError", "plain error"],
]
cases.each do |input, expected_type, expected_msg|
  begin
    Textkit::Nums.digit(input)
    raise "expected exception for #{{input.inspect}}"
  rescue Exception => e
    unless e.class.name == expected_type && e.message == expected_msg
      abort "mismatch for #{{input.inspect}}: got #{{e.class.name}} (#{{e.message.inspect}}), expected #{{expected_type}} (#{{expected_msg.inspect}})"
    end
  end
end
"#,
            dir.join("ruby/textkit_rs.rb")
        ),
    )
    .unwrap();
    let out = Command::new("ruby")
        .args(["-E", "UTF-8:UTF-8"])
        .arg(&check_rb)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}\n{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A module that calls `extend self` exports its public instance methods, including those defined
/// before the call, and records and replays through `Slug.name(...)`.
#[test]
fn ruby_extend_self_module_bridges_records_and_diffs() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ruby-extend-self");
    let dir = std::env::temp_dir().join(format!(
        "rust-anything-ruby-extend-self-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "lib/slug/",
        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();
    let manifest = Manifest::load(&dir).unwrap();
    let names: Vec<&str> = manifest.exports.iter().map(|e| e.name.as_str()).collect();
    assert_eq!(names, ["size", "make", "flip"]);
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(port.contains("pub fn make(text: String)"), "{port}");
    if !common::have_ruby_3() {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    for f in ["size", "make", "flip"] {
        assert!(cases.contains(&format!("\"fn\":\"{f}\"")), "{f}: {cases}");
    }
    for (name, body) in [
        ("size", "Ok(text.chars().count() as i64)"),
        ("flip", "Ok(text.chars().rev().collect())"),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from lib/slug/slug.rb\")");
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let (diff, counts) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.total, recorded.cases);
    for f in ["size", "flip"] {
        let (p, t) = counts[f];
        assert!(t > 0 && p == t, "{f}: {p}/{t} {:?}", diff.mismatches);
    }
    // `make` is not ported, so it panics in Rust.
    assert!(
        diff.failed > 0
            && diff
                .mismatches
                .iter()
                .all(|m| m["fn"].as_str() == Some("make")),
        "{:?}",
        diff.mismatches
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A Java unit that imports a class from outside its source tree, as a Gradle or Maven module
/// imports its dependencies, records with that class on CLASSPATH.
#[test]
fn java_record_reads_classpath_for_classes_outside_the_tree() {
    if !common::have("javac") {
        return;
    }
    let tmp = std::env::temp_dir().join(format!(
        "rust-anything-java-classpath-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    let (repo, deps) = (tmp.join("repo"), tmp.join("deps"));
    let pads = repo.join("src/main/java/com/example/pad");
    std::fs::create_dir_all(&pads).unwrap();
    std::fs::create_dir_all(deps.join("dep")).unwrap();
    std::fs::write(
        deps.join("dep/Fill.java"),
        "package dep;\n\npublic final class Fill {\n    \
         public static String left(String s, int n) {\n        \
         StringBuilder b = new StringBuilder();\n        \
         for (int i = s.length(); i < n; i++) b.append('.');\n        \
         return b.append(s).toString();\n    }\n}\n",
    )
    .unwrap();
    let status = Command::new("javac")
        .args(["-d", "classes", "dep/Fill.java"])
        .current_dir(&deps)
        .status()
        .unwrap();
    assert!(status.success());
    std::fs::write(
        pads.join("Pads.java"),
        "package com.example.pad;\n\nimport dep.Fill;\n\npublic final class Pads {\n    \
         public static String pad(String s, int n) {\n        return Fill.left(s, n);\n    }\n}\n",
    )
    .unwrap();
    let crate_dir = tmp.join("pad-rs");
    bridge::bridge(&bridge::Options {
        root: &repo,
        unit: "src/main/java/com/example/pad/",
        kind: None,
        out: Some(crate_dir.clone()),
        name: Some("pad-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let inputs = tmp.join("inputs.jsonl");
    std::fs::write(&inputs, "{\"fn\": \"pad\", \"args\": [\"ab\", 4]}\n").unwrap();
    let record = |classpath: Option<&Path>| {
        let mut cmd = common::cli();
        cmd.arg("record")
            .arg(&crate_dir)
            .arg("--inputs")
            .arg(&inputs)
            .args(["--count", "0"])
            .env_remove("CLASSPATH");
        if let Some(cp) = classpath {
            cmd.env("CLASSPATH", cp);
        }
        cmd.output().unwrap()
    };

    let without = record(None);
    let stderr = String::from_utf8_lossy(&without.stderr);
    assert!(!without.status.success(), "{stderr}");
    assert!(stderr.contains("Set CLASSPATH"), "{stderr}");

    let with = record(Some(&deps.join("classes")));
    assert!(
        with.status.success(),
        "{}",
        String::from_utf8_lossy(&with.stderr)
    );
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(crate_dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(cases.contains("\"..ab\""), "{cases}");
    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn java_classes_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/java");
    let dir = std::env::temp_dir().join(format!("rust-anything-java-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/main/java/com/example/text/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("text-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(
        port.contains("pub fn parse_port(text: String) -> Result<i64, String>"),
        "{port}"
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains("fn Java_rustanything_TextRsNative_call"),
        "{lib}"
    );
    let wrapper = std::fs::read_to_string(dir.join("java/com/example/text/Strings.java")).unwrap();
    assert!(
        wrapper.contains("public static List<String> words(String text)"),
        "{wrapper}"
    );
    // Batches: a list result cannot be batched; the others get a class beside the original.
    assert!(bridge::add_batches(&dir, &["words:text".into()]).is_err());
    bridge::add_batches(&dir, &["slugify:text".into(), "pages:total".into()]).unwrap();
    let batch =
        std::fs::read_to_string(dir.join("java/com/example/text/SlugifyBatch.java")).unwrap();
    assert!(
        batch.contains("public final class SlugifyBatch implements AutoCloseable"),
        "{batch}"
    );
    assert!(batch.contains("public String[] run(int max)"), "{batch}");
    let pages = std::fs::read_to_string(dir.join("java/com/example/text/PagesBatch.java")).unwrap();
    assert!(
        pages.contains("public int[] rank(int perPage, double min)"),
        "{pages}"
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains("fn Java_com_example_text_SlugifyBatch_nRun"),
        "{lib}"
    );
    if !common::have("javac") {
        return;
    }
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"digit\", \"args\": [\"7\"]}\n\
         {\"fn\": \"digit\", \"args\": [\"x\"]}\n\
         {\"fn\": \"parsePort\", \"args\": [\"8080\"]}\n\
         {\"fn\": \"parsePort\", \"args\": [\"0\"]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 100, "{recorded:?}");
    // `parsePort` throws NumberFormatException/IllegalArgumentException; `digit` throws ParseException.
    assert!(recorded.errors > 0);
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(
        cases.contains(r#"{"fn":"digit","args":["7"],"ok":7}"#),
        "{cases}"
    );
    assert!(
        cases.contains(r#""error_type":"ParseException""#),
        "{cases}"
    );
    assert!(error_checks(&dir, "the fixture")[1].passed);
    let mut port = port;
    for (name, body) in [
        (
            "parsePort",
            "let trimmed = text.trim(); \
             let port: i32 = trimmed.parse().map_err(|_| format!(\"NumberFormatException: For input string: \\\"{trimmed}\\\"\"))?; \
             if !(1..=65535).contains(&port) { return Err(format!(\"IllegalArgumentException: port out of range: {port}\")); } \
             Ok(i64::from(port))",
        ),
        (
            "digit",
            "if text.len() == 1 && text.as_bytes()[0].is_ascii_digit() { \
             Ok(i64::from(text.as_bytes()[0] - b'0')) } else { \
             Err(\"com.example.text.ParseException: not a digit\".into()) }",
        ),
    ] {
        let stub = format!(
            "unimplemented!(\"port `{name}` from src/main/java/com/example/text/Strings.java\")"
        );
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    harness::build(&dir).unwrap();
    let (diff, counts) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.total, recorded.cases);
    assert!(diff.passed > 0, "{diff:?}");
    for f in ["digit", "parsePort"] {
        let (p, t) = counts[f];
        assert!(
            t > 0 && p == t,
            "{f}: {p}/{t} {:?}",
            diff.mismatches
                .iter()
                .filter(|m| m["fn"] == f)
                .take(3)
                .collect::<Vec<_>>()
        );
    }
    assert!(
        !diff
            .mismatches
            .iter()
            .any(|m| matches!(m["fn"].as_str(), Some("digit" | "parsePort"))),
        "{:?}",
        diff.mismatches
    );
    // Unported functions panic, which Java sees as a RuntimeException.
    assert!(
        diff.failed > 0
            && diff.mismatches.iter().all(|m| {
                !matches!(m["fn"].as_str(), Some("digit" | "parsePort"))
                    && m["actual"]["error"]
                        .as_str()
                        .is_some_and(|e| e.contains("Rust panic:"))
            }),
        "{:?}",
        diff.mismatches
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn kotlin_functions_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/kotlin");
    let dir = std::env::temp_dir().join(format!("rust-anything-kotlin-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/main/kotlin/com/example/text/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("text-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    assert!(
        port.contains("pub fn slugify(text: String, max: i64) -> Result<String, String>"),
        "{port}"
    );
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(
        lib.contains("fn Java_rustanything_TextRsNative_call"),
        "{lib}"
    );
    // Kotlin type names must become Java ones, or javac rejects the wrapper.
    let wrapper =
        std::fs::read_to_string(dir.join("java/com/example/text/StringsKt.java")).unwrap();
    assert!(
        wrapper.contains("public static String slugify(String text, int max)"),
        "{wrapper}"
    );
    assert!(
        wrapper.contains("public static Map<String, Integer> frequencies(String text)"),
        "{wrapper}"
    );
    let nums = std::fs::read_to_string(dir.join("java/com/example/text/Nums.java")).unwrap();
    assert!(
        nums.contains("public static long gcd(long a, long b)"),
        "{nums}"
    );
    if !common::have("kotlinc") || !common::have("javac") {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 10,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 50, "{recorded:?}");
    // `pages` divides by zero for a generated per-page of 0.
    assert!(recorded.errors > 0, "{recorded:?}");
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    // Unported functions panic, which Java sees as a RuntimeException: nothing can match.
    assert_eq!(diff.passed, 0, "{diff:?}");
    assert_eq!(diff.total, recorded.cases);
    let _ = std::fs::remove_dir_all(&dir);
}

/// The Android half: build the same JNI crate for an Android ABI and install it into `jniLibs/`.
/// Skips when there is no NDK or the Rust target is missing, as CI usually has neither.
#[test]
fn android_build_installs_a_jni_library() {
    let Ok(ndk) = rust_anything::android::ndk_root(None) else {
        return;
    };
    let installed = Command::new("rustup")
        .args(["target", "list", "--installed"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
        .unwrap_or_default();
    let Some(abi) = rust_anything::android::DEFAULT_ABIS
        .iter()
        .find(|abi| installed.lines().any(|l| l.trim() == abi.triple()))
    else {
        return;
    };
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/kotlin");
    let dir = std::env::temp_dir().join(format!(
        "rust-anything-android-{}-{}",
        std::process::id(),
        abi.name()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/main/kotlin/com/example/text/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("text-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    // Also exercise --jni-libs: Gradle's default is src/main/jniLibs, not the crate root.
    let jni_libs = dir.join("libs");
    let report = harness::build_android(
        &dir,
        &rust_anything::android::Options {
            abis: vec![abi.name().into(), abi.name().into()], // duplicate ABIs build once
            api: rust_anything::android::DEFAULT_API,
            ndk: None,
            out: Some(jni_libs),
        },
    )
    .unwrap();
    assert_eq!(report.ndk, ndk);
    assert_eq!(report.libraries.len(), 1, "{report:?}");
    let library = &report.libraries[0];
    assert_eq!(library.abi, abi.name());
    assert!(library.path.is_file(), "{library:?}");
    assert!(
        library
            .path
            .ends_with(format!("libs/{}/libtext_rs.so", abi.name())),
        "{library:?}"
    );
    // call + the five exported functions.
    assert_eq!(library.entry_points, 6, "{library:?}");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn batches_keep_items_in_rust() {
    let dir = bridged("batch");
    std::fs::write(
        dir.join("src/port.rs"),
        "pub fn range_of(text: String, word: String) -> Result<serde_json::Value, String> { let _ = (text, word); Ok(serde_json::Value::Null) }\n\
         pub fn words(text: String) -> Vec<String> { vec![text] }\n\
         pub fn count(text: String) -> f64 { text.matches(' ').count() as f64 }\n",
    )
    .unwrap();
    // Structured results cannot be batched, and a refused batch leaves the crate as it was.
    let refused = bridge::add_batches(&dir, &["rangeOf:text".into()]).unwrap_err();
    assert!(
        format!("{refused:#}").contains("numbers, booleans or strings"),
        "{refused:#}"
    );
    assert!(Manifest::load(&dir).unwrap().batches.is_empty());
    assert!(bridge::add_batches(&dir, &["count:nope".into()]).is_err());

    bridge::add_batches(&dir, &["count:text".into()]).unwrap();
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("#[napi(js_name = \"CountBatch\")]"), "{lib}");
    assert!(lib.contains("pub struct CountDefaultIndex"));
    assert!(lib.contains("par_iter()"), "napi batches run on all cores");
    assert!(
        lib.contains("Float64Array"),
        "number results cross as one typed array"
    );
    assert!(lib.contains("pub fn rank("));
    let cargo = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("rayon"));

    // An index in port.rs replaces the default one.
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    port.push_str(
        "pub struct CountIndex(Vec<String>);\n\
         impl CountIndex {\n    pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
         pub fn run(&self) -> Result<Vec<f64>, String> { Ok(self.0.iter().map(|t| count(t.clone())).collect()) }\n}\n",
    );
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    bridge::refresh(&dir).unwrap();
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("inner: port::CountIndex,"));
    assert!(!lib.contains("CountDefaultIndex"));
    assert!(
        lib.contains("self.inner.run()"),
        "no `rank` of its own yet: {lib}"
    );
    // An index with its own `rank` (say, narrowing as the user types) is called for `rank`.
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    port = port.replace(
        "    pub fn run(&self)",
        "    pub fn rank(&self, min: f64) -> Result<Vec<u32>, String> {\n        let _ = min;\n        Ok(Vec::new())\n    }\n    pub fn run(&self)",
    );
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    bridge::refresh(&dir).unwrap();
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("self.inner.rank(min)"), "{lib}");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn custom_batch_index_is_checked_by_diff_and_gate_while_default_index_is_not_checked_twice() {
    if !common::have("node") {
        return;
    }
    let root =
        std::env::temp_dir().join(format!("rust-anything-batch-check-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"batch-check","version":"0.1.0"}"#,
    )
    .unwrap();
    std::fs::write(
        root.join("src/count.ts"),
        "export function count(text: string): number {\n  return text.split(' ').length - 1;\n}\n\
         export function scaleCount(text: string, factor: number): number {\n  if (!Number.isFinite(factor)) return 0;\n  return (text.split(' ').length - 1) * factor;\n}\n",
    )
    .unwrap();
    let dir = root.join("rust/unit");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/count.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: vec!["count:text".into(), "scaleCount:text".into()],
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    // Provide deterministic multi-group inputs alongside generated ones.
    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\":\"count\",\"args\":[\"a b c\"]}\n\
         {\"fn\":\"count\",\"args\":[\"one two\"]}\n\
         {\"fn\":\"scaleCount\",\"args\":[\"a b\",2]}\n\
         {\"fn\":\"scaleCount\",\"args\":[\"a b c\",2]}\n\
         {\"fn\":\"scaleCount\",\"args\":[\"a b\",3]}\n\
         {\"fn\":\"scaleCount\",\"args\":[\"a b c\",3]}\n",
    )
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 10,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();

    let base_port = "#![forbid(unsafe_code)]\n\n\
        /// Port of `count` (`count.ts:1`).\n\
        pub fn count(text: String) -> Result<f64, String> {\n    \
            Ok(text.matches(' ').count() as f64)\n\
        }\n\n\
        /// Port of `scaleCount` (`count.ts:4`).\n\
        pub fn scale_count(text: String, factor: f64) -> Result<f64, String> {\n    \
            if !factor.is_finite() { return Ok(0.0); }\n    \
            Ok((text.matches(' ').count() as f64) * factor)\n\
        }\n";
    std::fs::write(dir.join("src/port.rs"), base_port).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();

    // 1. Default indexes (no CountIndex / ScaleCountIndex) are not checked twice.
    let diff_opts = DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    };
    let default_diff = harness::diff(&diff_opts).unwrap();
    assert_eq!(default_diff.failed, 0, "{:?}", default_diff.mismatches);
    assert!(
        default_diff.batches.is_empty(),
        "default index must not be checked twice: {:?}",
        default_diff.batches
    );
    assert!(!dir.join(rust_anything::batch_check::TEST_FILE).exists());
    let default_gate = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(default_gate.passed, "{:?}", default_gate.checks);
    assert!(
        !default_gate.checks.iter().any(|c| c.name == "batch"),
        "default index must not emit a batch gate check: {:?}",
        default_gate.checks
    );

    // 2. A wrong CountIndex::run (+1) must fail diff and gate while per-item `count` passes.
    let wrong_run = format!(
        "{base_port}\n\
         pub struct CountIndex(Vec<String>);\n\
         impl CountIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Ok(self.0.iter().map(|t| (t.matches(' ').count() as f64) + 1.0).collect())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), wrong_run).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();

    let wrong_diff = harness::diff(&diff_opts).unwrap();
    assert_eq!(wrong_diff.failed, 0, "{:?}", wrong_diff.mismatches);
    assert_eq!(wrong_diff.batches.len(), 1, "{:?}", wrong_diff.batches);
    assert_eq!(wrong_diff.batches[0].index, "CountIndex");
    assert!(wrong_diff.batches[0].failed > 0, "{:?}", wrong_diff.batches);

    let cli_diff = common::cli().arg("diff").arg(&dir).output().unwrap();
    assert!(!cli_diff.status.success());
    let cli_out = String::from_utf8_lossy(&cli_diff.stdout);
    assert!(
        cli_out.contains("Batch CountIndex (count):"),
        "diff must report batch check on its own line:\n{cli_out}"
    );

    let gate_wrong_run = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(
        gate_wrong_run
            .checks
            .iter()
            .find(|c| c.name == "behavior")
            .unwrap()
            .passed,
        "per-item behavior should pass: {:?}",
        gate_wrong_run.checks
    );
    let batch_check = gate_wrong_run
        .checks
        .iter()
        .find(|c| c.name == "batch")
        .expect("gate must include a `batch` check");
    assert!(!batch_check.passed, "{batch_check:?}");
    assert!(
        gate_wrong_run
            .checks
            .iter()
            .find(|c| c.name == "cargo test")
            .unwrap()
            .passed,
        "general `cargo test` must stay green on a batch-only mismatch: {:?}",
        gate_wrong_run.checks
    );
    assert!(!gate_wrong_run.passed, "{:?}", gate_wrong_run.checks);
    assert!(gate_wrong_run.failed.contains(&"batch"));
    assert!(!dir.join(rust_anything::batch_check::TEST_FILE).exists());

    // MCP `diff` must mark a batch-only failure as `isError: true` / `verdict: "fail"`.
    let mcp_diff = rust_anything::mcp::handle(&serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "diff",
            "arguments": { "crate": dir.to_string_lossy() }
        }
    }))
    .unwrap();
    assert_eq!(mcp_diff["result"]["isError"], true, "{mcp_diff}");
    assert_eq!(
        mcp_diff["result"]["structuredContent"]["verdict"], "fail",
        "{mcp_diff}"
    );
    assert_eq!(
        mcp_diff["result"]["structuredContent"]["ok"], false,
        "{mcp_diff}"
    );

    // 3. Correct `CountIndex::run` + wrong `CountIndex::rank` must fail diff and gate.
    let wrong_rank = format!(
        "{base_port}\n\
         pub struct CountIndex(Vec<String>);\n\
         impl CountIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Ok(self.0.iter().map(|t| t.matches(' ').count() as f64).collect())\n    \
             }}\n    \
             pub fn rank(&self, _min: f64) -> Result<Vec<u32>, String> {{\n        \
                 Ok(Vec::new())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), wrong_rank).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();

    let diff_wrong_rank = harness::diff(&diff_opts).unwrap();
    assert_eq!(diff_wrong_rank.batches.len(), 1);
    assert_eq!(diff_wrong_rank.batches[0].failed, 0);
    assert!(
        diff_wrong_rank.batches[0].rank_failed > 0,
        "{:?}",
        diff_wrong_rank.batches
    );
    let gate_wrong_rank = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(!gate_wrong_rank.passed);
    assert!(gate_wrong_rank.failed.contains(&"batch"));

    // 4. Correct `CountIndex` (with `rank` and non-newline stdout) and `ScaleCountIndex` pass.
    let all_good = format!(
        "{base_port}\n\
         pub struct CountIndex(Vec<String>);\n\
         impl CountIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 print!(\"progress-without-newline\");\n        \
                 Ok(self.0.iter().map(|t| t.matches(' ').count() as f64).collect())\n    \
             }}\n    \
             pub fn rank(&self, min: f64) -> Result<Vec<u32>, String> {{\n        \
                 let scores = self.run()?;\n        \
                 let mut hits: Vec<(f64, u32)> = scores\n            \
                     .into_iter()\n            \
                     .enumerate()\n            \
                     .map(|(i, s)| (s, u32::try_from(i).unwrap_or(u32::MAX)))\n            \
                     .filter(|(s, _)| *s >= min)\n            \
                     .collect();\n        \
                 hits.sort_by(|a, b| b.0.total_cmp(&a.0));\n        \
                 Ok(hits.into_iter().map(|(_, i)| i).collect())\n    \
             }}\n\
         }}\n\n\
         pub struct ScaleCountIndex(Vec<String>);\n\
         impl ScaleCountIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self, factor: f64) -> Result<Vec<f64>, String> {{\n        \
                 if !factor.is_finite() {{ return Ok(vec![0.0; self.0.len()]); }}\n        \
                 Ok(self.0.iter().map(|t| (t.matches(' ').count() as f64) * factor).collect())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), all_good).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();

    let good_diff = harness::diff(&diff_opts).unwrap();
    assert_eq!(good_diff.failed, 0);
    assert_eq!(good_diff.batches.len(), 2, "{:?}", good_diff.batches);
    assert!(
        good_diff.batches.iter().all(|b| b.ok()),
        "{:?}",
        good_diff.batches
    );
    assert!(good_diff.batches[0].rank_checks > 0);
    assert!(
        good_diff.batches[1].groups >= 2,
        "scaleCount cases should be grouped by `factor`: {:?}",
        good_diff.batches[1]
    );

    let good_gate = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(good_gate.passed, "{:?}", good_gate.checks);
    assert!(
        good_gate
            .checks
            .iter()
            .find(|c| c.name == "batch")
            .unwrap()
            .passed
    );

    // 5. Removing custom indexes cleans up the generated batch test and passes gate.
    std::fs::write(dir.join("src/port.rs"), base_port).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let cleaned_gate = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(cleaned_gate.passed, "{:?}", cleaned_gate.checks);
    assert!(!dir.join(rust_anything::batch_check::TEST_FILE).exists());
    assert!(!cleaned_gate.checks.iter().any(|c| c.name == "batch"));

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn custom_batch_check_preserves_handwritten_tests_and_enforces_tolerance_and_rank_edges() {
    if !common::have("node") {
        return;
    }
    let root =
        std::env::temp_dir().join(format!("rust-anything-batch-edge-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"batch-edge","version":"0.1.0"}"#,
    )
    .unwrap();
    std::fs::write(
        root.join("src/edge.ts"),
        "export function score(tag: string): number {\n  \
           if (tag === 'big') return 1000000000;\n  \
           if (tag === 'huge') return 1e300;\n  \
           if (tag === 'pow53') return 9007199254740992;\n  \
           if (tag === 'frac') return 1.5;\n  \
           return 2;\n\
         }\n",
    )
    .unwrap();
    let dir = root.join("rust/unit");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/edge.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: Some("batch-edge-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: vec!["score:tag".into()],
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\":\"score\",\"args\":[\"big\"]}\n\
         {\"fn\":\"score\",\"args\":[\"huge\"]}\n\
         {\"fn\":\"score\",\"args\":[\"pow53\"]}\n\
         {\"fn\":\"score\",\"args\":[\"frac\"]}\n",
    )
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();

    let base_port = "#![forbid(unsafe_code)]\n\n\
        pub fn score(tag: String) -> Result<f64, String> {\n    \
            match tag.as_str() {\n        \
                \"big\" => Ok(1_000_000_000.0),\n        \
                \"huge\" => Ok(1e300),\n        \
                \"pow53\" => Ok(9_007_199_254_740_992.0),\n        \
                \"frac\" => Ok(1.5),\n        \
                _ => Ok(2.0),\n    \
            }\n\
        }\n";
    let exact_index = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 self.0.iter().cloned().map(score).collect()\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), &exact_index).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();

    // 1. A handwritten `tests/rust_anything_batch.rs` is preserved (never overwritten/deleted),
    // `behavior` and `cargo test` stay green, `batch` fails with a collision error, and
    // `enable::select_matching` refuses to switch on the unverified custom batch export.
    let handwritten_path = dir.join(rust_anything::batch_check::TEST_FILE);
    std::fs::create_dir_all(handwritten_path.parent().unwrap()).unwrap();
    let handwritten = "// handwritten integration test\n#[test]\nfn user_keeps_this() {}\n";
    std::fs::write(&handwritten_path, handwritten).unwrap();

    let gate_collision = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!(
        std::fs::read_to_string(&handwritten_path).unwrap(),
        handwritten,
        "handwritten test must not be modified or deleted"
    );
    assert!(
        gate_collision
            .checks
            .iter()
            .find(|c| c.name == "cargo test")
            .unwrap()
            .passed,
        "{:?}",
        gate_collision.checks
    );
    assert!(
        gate_collision
            .checks
            .iter()
            .find(|c| c.name == "behavior")
            .unwrap()
            .passed,
        "{:?}",
        gate_collision.checks
    );
    let batch_collision = gate_collision
        .checks
        .iter()
        .find(|c| c.name == "batch")
        .expect("collision must report as failed batch check");
    assert!(!batch_collision.passed, "{batch_collision:?}");
    assert!(
        batch_collision
            .detail
            .contains("not generated by rust-anything"),
        "{batch_collision:?}"
    );
    assert!(
        batch_collision.fix.as_deref().is_some_and(|f| {
            !f.contains("src/port.rs") && f.contains(rust_anything::batch_check::TEST_FILE)
        }),
        "collision fix must explain how to clear the collision instead of pointing to src/port.rs: {batch_collision:?}"
    );
    let manifest = Manifest::load(&dir).unwrap();
    let (diff_col, counts_col) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let err = rust_anything::enable::select_matching(&manifest, &diff_col, &counts_col, &[])
        .unwrap_err()
        .to_string();
    assert!(
        err.contains("not generated by rust-anything"),
        "unverified batch must block enable: {err}"
    );
    std::fs::remove_file(&handwritten_path).unwrap();

    // 2. Malformed `known-diffs.jsonl` must not abort `gate` before independent checks run.
    let known_path = dir.join(rust_anything::recording::KNOWN_DIFFS);
    std::fs::write(&known_path, "{not valid json\n").unwrap();
    let gate_bad_known = rust_anything::gate::gate_with(
        &dir,
        &[],
        &rust_anything::gate::GateOptions {
            held_out_cases: 0,
            ..Default::default()
        },
    )
    .unwrap();
    assert!(!gate_bad_known.passed);
    assert!(
        gate_bad_known
            .checks
            .iter()
            .any(|c| c.name == "cargo test" && c.passed),
        "independent checks must still run: {:?}",
        gate_bad_known.checks
    );
    std::fs::remove_file(&known_path).unwrap();

    // 3. Whole-number mismatch (1e9 vs 1e9+1) must fail even with float_tolerance = 1e-8,
    // while fractional rounding (1.5 vs 1.500000001) and >= 2^52 float rounding (1e300 vs
    // 1.0000000000001e300) pass.
    let whole_bug_index = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Ok(self.0.iter().map(|t| match t.as_str() {{\n            \
                     \"big\" => 1_000_000_001.0,\n            \
                     \"huge\" => 1.000_000_000_000_1e300,\n            \
                     \"pow53\" => 9_007_199_254_740_992.0,\n            \
                     \"frac\" => 1.500_000_001,\n            \
                     _ => 2.0,\n        \
                 }}).collect())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), whole_bug_index).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let tol_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: Some(1e-8),
        node_args: &[],
    })
    .unwrap();
    assert_eq!(tol_diff.batches.len(), 1, "{:?}", tol_diff.batches);
    assert_eq!(
        tol_diff.batches[0].failed, 1,
        "1e9+1 must fail exact whole-number check while 1.500000001 passes tolerance: {:?}",
        tol_diff.batches[0]
    );

    // 4. Rank thresholds must be strictly above 2^53 so a rank() ignoring `min` fails.
    let pow53_only = root.join("pow53.jsonl");
    std::fs::write(&pow53_only, "{\"fn\":\"score\",\"args\":[\"pow53\"]}\n").unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&pow53_only),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let bad_rank_pow53 = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 self.0.iter().cloned().map(score).collect()\n    \
             }}\n    \
             pub fn rank(&self, _min: f64) -> Result<Vec<u32>, String> {{\n        \
                 Ok((0..self.0.len()).map(|i| i as u32).collect())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), bad_rank_pow53).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let pow53_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(pow53_diff.batches.len(), 1);
    assert_eq!(
        pow53_diff.batches[0].failed, 0,
        "{:?}",
        pow53_diff.batches[0]
    );
    assert!(
        pow53_diff.batches[0].rank_failed > 0,
        "rank ignoring `min` at 2^53 must be caught: {:?}",
        pow53_diff.batches[0]
    );

    // 5. Known diff switching recorded ok -> allowed error runs individually: rejects unrelated
    // Ok(999.0), accepts Err(...) and recorded Ok(2^53).
    std::fs::write(
        &known_path,
        "{\"fn\":\"score\",\"args\":[\"pow53\"],\"actual\":{\"error\":\"rejected\"},\"reason\":\"intentional\"}\n",
    )
    .unwrap();
    let wrong_ok_index = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Ok(vec![999.0; self.0.len()])\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), wrong_ok_index).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let kd_wrong = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(
        kd_wrong.batches[0].failed, 1,
        "unrelated Ok(999.0) must fail ok->error known-diff check: {:?}",
        kd_wrong.batches[0]
    );

    let err_ok_index = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Err(\"rejected\".into())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), err_ok_index).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let kd_err = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert!(
        kd_err.batches[0].ok(),
        "allowed Err(...) must pass ok->error known-diff check: {:?}",
        kd_err.batches[0]
    );

    let unrelated_err_index = format!(
        "{base_port}\n\
         pub struct ScoreIndex(Vec<String>);\n\
         impl ScoreIndex {{\n    \
             pub fn new(items: Vec<String>) -> Self {{ Self(items) }}\n    \
             pub fn run(&self) -> Result<Vec<f64>, String> {{\n        \
                 Err(\"unrelated failure\".into())\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(dir.join("src/port.rs"), unrelated_err_index).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let kd_unrelated = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(
        kd_unrelated.batches[0].failed, 1,
        "an error other than the listed one must fail: {:?}",
        kd_unrelated.batches[0]
    );

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn custom_batch_index_checks_typed_errors_singleton_rank_and_partial_abort() {
    if !common::have("node") {
        return;
    }
    let root = std::env::temp_dir().join(format!(
        "rust-anything-batch-typed-errors-rank-partial-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    let src = root.join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"pair-batch","version":"0.1.0"}"#,
    )
    .unwrap();
    std::fs::write(
        src.join("pair.ts"),
        "export function alpha(tag: string): number {\n\
         \x20 if (tag === 'bad') throw new RangeError('out of range')\n\
         \x20 return 1.0\n\
         }\n\
         export function beta(tag: string): number {\n\
         \x20 return tag.length\n\
         }\n",
    )
    .unwrap();
    let dir = root.join("rust/pair-rs");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/pair.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: Some("pair-batch-rs".into()),
        force: true,
        keep: Vec::new(),
        lang: None,
        batch: vec!["alpha:tag".into(), "beta:tag".into()],
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\":\"alpha\",\"args\":[\"ok\"]}\n\
         {\"fn\":\"alpha\",\"args\":[\"bad\"]}\n\
         {\"fn\":\"beta\",\"args\":[\"hi\"]}\n",
    )
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();

    // 1. Typed recorded error (`RangeError`): returning `TypeError` in `AlphaIndex::run` must fail,
    // while returning `RangeError` passes.
    let wrong_err_type = "#![forbid(unsafe_code)]\n\n\
        pub fn alpha(tag: String) -> Result<f64, String> {\n    \
            if tag == \"bad\" { return Err(\"RangeError: out of range\".into()); }\n    \
            Ok(1.0)\n\
        }\n\
        pub fn beta(tag: String) -> Result<f64, String> {\n    \
            Ok(tag.len() as f64)\n\
        }\n\
        pub struct AlphaIndex(Vec<String>);\n\
        impl AlphaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> {\n        \
                if self.0.iter().any(|t| t == \"bad\") {\n            \
                    return Err(\"TypeError: wrong class\".into());\n        \
                }\n        \
                Ok(vec![1.0; self.0.len()])\n    \
            }\n\
        }\n\
        pub struct BetaIndex(Vec<String>);\n\
        impl BetaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> {\n        \
                Ok(self.0.iter().map(|t| t.len() as f64).collect())\n    \
            }\n\
        }\n";
    std::fs::write(dir.join("src/port.rs"), wrong_err_type).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let wrong_err_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let alpha_bad = wrong_err_diff
        .batches
        .iter()
        .find(|b| b.function == "alpha")
        .unwrap();
    assert_eq!(
        alpha_bad.failed, 1,
        "wrong error class in batch Index::run must fail: {alpha_bad:?}"
    );
    assert!(
        alpha_bad
            .mismatches
            .first()
            .and_then(|m| m["expected"].as_str())
            .is_some_and(|s| s.contains("RangeError")),
        "{alpha_bad:?}"
    );

    let right_err_type =
        wrong_err_type.replace("TypeError: wrong class", "RangeError: out of range");
    std::fs::write(dir.join("src/port.rs"), &right_err_type).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let right_err_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let alpha_ok = right_err_diff
        .batches
        .iter()
        .find(|b| b.function == "alpha")
        .expect("alpha batch report must be present");
    assert!(
        alpha_ok.ok(),
        "matching RangeError must pass: {:?}",
        right_err_diff.batches
    );
    assert!(
        right_err_diff.batches.iter().all(|b| b.ok()),
        "matching RangeError must pass: {:?}",
        right_err_diff.batches
    );

    // 2. Singleton ok->error known-diff branch checks `rank` when `run` returns Ok([1.0]), and
    // skips `rank` when `run` returns an accepted error.
    let single_inputs = root.join("single.jsonl");
    std::fs::write(
        &single_inputs,
        "{\"fn\":\"alpha\",\"args\":[\"ok\"]}\n{\"fn\":\"beta\",\"args\":[\"hi\"]}\n",
    )
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&single_inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let known_path = dir.join(rust_anything::recording::KNOWN_DIFFS);
    std::fs::write(
        &known_path,
        "{\"fn\":\"alpha\",\"args\":[\"ok\"],\"actual\":{\"error\":\"RangeError: intentional\",\"error_type\":\"RangeError\"},\"reason\":\"singleton test\"}\n",
    )
    .unwrap();
    let singleton_bad_rank = "#![forbid(unsafe_code)]\n\n\
        pub fn alpha(tag: String) -> Result<f64, String> {\n    \
            if tag == \"bad\" { return Err(\"RangeError: out of range\".into()); }\n    \
            Ok(1.0)\n\
        }\n\
        pub fn beta(tag: String) -> Result<f64, String> {\n    \
            Ok(tag.len() as f64)\n\
        }\n\
        pub struct AlphaIndex(Vec<String>);\n\
        impl AlphaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> { Ok(vec![1.0; self.0.len()]) }\n    \
            pub fn rank(&self, _min: f64) -> Result<Vec<u32>, String> { Ok(Vec::new()) }\n\
        }\n\
        pub struct BetaIndex(Vec<String>);\n\
        impl BetaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> {\n        \
                Ok(self.0.iter().map(|t| t.len() as f64).collect())\n    \
            }\n\
        }\n";
    std::fs::write(dir.join("src/port.rs"), singleton_bad_rank).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let rank_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let alpha_rank = rank_diff
        .batches
        .iter()
        .find(|b| b.function == "alpha")
        .unwrap();
    assert_eq!(alpha_rank.failed, 0, "{alpha_rank:?}");
    assert!(
        alpha_rank.rank_failed > 0,
        "singleton Ok([1.0]) must still check custom rank: {alpha_rank:?}"
    );
    assert!(
        !rank_diff.stale_known.is_empty(),
        "known-diffs unused by both per-item and batch must stay stale: {:?}",
        rank_diff.stale_known
    );

    let singleton_accepted_err = singleton_bad_rank.replace(
        "pub fn run(&self) -> Result<Vec<f64>, String> { Ok(vec![1.0; self.0.len()]) }",
        "pub fn run(&self) -> Result<Vec<f64>, String> { Err(\"RangeError: intentional\".into()) }",
    );
    std::fs::write(dir.join("src/port.rs"), singleton_accepted_err).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let err_rank_diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let alpha_err_ok = err_rank_diff
        .batches
        .iter()
        .find(|b| b.function == "alpha")
        .unwrap();
    assert!(
        alpha_err_ok.ok() && alpha_err_ok.rank_checks == 0,
        "accepted singleton error must pass without calling rank: {alpha_err_ok:?}"
    );
    assert!(
        err_rank_diff.stale_known.is_empty(),
        "known-diffs entry used by custom batch index must not be reported stale: {:?}",
        err_rank_diff.stale_known
    );
    std::fs::remove_file(&known_path).unwrap();

    // 3. When one custom batch index finishes and another aborts the test process, the completed
    // index keeps its passing report so partial enable can select it while rejecting the aborted one.
    let partial_abort_port = "#![forbid(unsafe_code)]\n\n\
        pub fn alpha(tag: String) -> Result<f64, String> { let _ = tag; Ok(1.0) }\n\
        pub fn beta(tag: String) -> Result<f64, String> { Ok(tag.len() as f64) }\n\
        pub struct AlphaIndex(Vec<String>);\n\
        impl AlphaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> { Ok(vec![1.0; self.0.len()]) }\n\
        }\n\
        pub struct BetaIndex(Vec<String>);\n\
        impl BetaIndex {\n    \
            pub fn new(items: Vec<String>) -> Self { Self(items) }\n    \
            pub fn run(&self) -> Result<Vec<f64>, String> {\n        \
                if let Some(dir) = std::env::var_os(\"RUST_ANYTHING_BATCH_OUT_DIR\") {\n            \
                    let alpha_report = std::path::PathBuf::from(dir).join(\"0_alpha.json\");\n            \
                    for _ in 0..200 {\n                \
                        if alpha_report.is_file() { break; }\n                \
                        std::thread::sleep(std::time::Duration::from_millis(25));\n            \
                    }\n        \
                }\n        \
                std::process::exit(1);\n    \
            }\n\
        }\n";
    std::fs::write(dir.join("src/port.rs"), partial_abort_port).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let manifest = Manifest::load(&dir).unwrap();
    let (partial_diff, partial_counts) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    let alpha_res = partial_diff
        .batches
        .iter()
        .find(|b| b.function == "alpha")
        .unwrap();
    let beta_res = partial_diff
        .batches
        .iter()
        .find(|b| b.function == "beta")
        .unwrap();
    assert!(
        alpha_res.ok() && alpha_res.passed == 1,
        "completed alpha index must keep its passing report: {alpha_res:?}"
    );
    assert!(
        !beta_res.ok() && beta_res.error.is_some(),
        "aborted beta index must carry an execution error: {beta_res:?}"
    );
    let (selected, skipped) =
        rust_anything::enable::select_matching(&manifest, &partial_diff, &partial_counts, &[])
            .unwrap();
    assert_eq!(selected, vec!["alpha"]);
    assert!(
        skipped.iter().any(|s| s.starts_with("beta:")),
        "beta must stay skipped: {skipped:?}"
    );

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn diff_compares_own_proto_named_properties_in_arguments_and_results() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("proto-properties");
    std::fs::write(
        dir.join(harness::CASES),
        r#"{"fn":"echo","args":[{"__proto__":{"value":1}}],"ok":{"__proto__":{"value":1}}}"#,
    )
    .unwrap();
    let module = dir.join("index.cjs");
    let opts = DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    };
    std::fs::write(
        &module,
        "exports.echo = x => Object.hasOwn(x, '__proto__') ? x : {}",
    )
    .unwrap();
    let matching = harness::diff(&opts).unwrap();
    std::fs::write(&module, "exports.echo = () => ({})").unwrap();
    let changed = harness::diff(&opts).unwrap();
    std::fs::remove_dir_all(dir).unwrap();
    assert_eq!(matching.passed, 1);
    assert_eq!(changed.failed, 1);
}

/// A crate for `util.ts` with a `count:text` batch, bridged as `kind` with `allocator`.
fn batch_crate(name: &str, kind: Kind, allocator: bridge::Allocator) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("rust-anything-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/util.ts",
        kind: Some(kind),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator,
    })
    .unwrap();
    std::fs::write(
        dir.join("src/port.rs"),
        "pub fn count(text: String) -> f64 { text.matches(' ').count() as f64 }\n",
    )
    .unwrap();
    bridge::add_batches(&dir, &["count:text".into()]).unwrap();
    dir
}

#[test]
fn batches_use_the_chosen_allocator() {
    let read = |dir: &Path, file: &str| std::fs::read_to_string(dir.join(file)).unwrap();

    // The default stays mimalloc, and the manifest does not mention it.
    let dir = batch_crate("alloc-mi", Kind::Napi, bridge::Allocator::Mimalloc);
    assert!(read(&dir, "src/lib.rs").contains("static GLOBAL: mimalloc::MiMalloc"));
    assert!(read(&dir, "Cargo.toml").contains("mimalloc = \"0.1\""));
    assert!(!read(&dir, "rust-anything.json").contains("allocator"));
    std::fs::remove_dir_all(&dir).unwrap();

    // rusty_alloc replaces it, and `refresh` keeps the choice from the manifest.
    let dir = batch_crate("alloc-ra", Kind::Napi, bridge::Allocator::RustyAlloc);
    for _ in 0..2 {
        let lib = read(&dir, "src/lib.rs");
        assert!(
            lib.contains(
                "static GLOBAL: rusty_alloc_api::RustyAlloc = rusty_alloc_api::RustyAlloc;"
            ),
            "{lib}"
        );
        assert!(!lib.contains("mimalloc"), "{lib}");
        let cargo = read(&dir, "Cargo.toml");
        assert!(cargo.contains("rusty_alloc-api = \"2.6\""), "{cargo}");
        assert!(!cargo.contains("mimalloc"), "{cargo}");
        assert!(read(&dir, "rust-anything.json").contains("\"allocator\": \"rusty_alloc\""));
        assert_eq!(
            Manifest::load(&dir).unwrap().allocator,
            bridge::Allocator::RustyAlloc
        );
        bridge::refresh(&dir).unwrap();
    }
    std::fs::remove_dir_all(&dir).unwrap();

    // wasm keeps Rust's allocator under the default, and takes rusty_alloc when asked.
    let dir = batch_crate("alloc-wasm-mi", Kind::Wasm, bridge::Allocator::Mimalloc);
    assert!(!read(&dir, "src/lib.rs").contains("global_allocator"));
    assert!(!read(&dir, "Cargo.toml").contains("mimalloc"));
    std::fs::remove_dir_all(&dir).unwrap();
    let dir = batch_crate("alloc-wasm-ra", Kind::Wasm, bridge::Allocator::RustyAlloc);
    assert!(read(&dir, "src/lib.rs").contains("static GLOBAL: rusty_alloc_api::RustyAlloc"));
    assert!(read(&dir, "Cargo.toml").contains("rusty_alloc-api"));
    std::fs::remove_dir_all(&dir).unwrap();

    // Without batches there is no global allocator to choose.
    let dir = std::env::temp_dir().join(format!("rust-anything-alloc-none-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    bridge::bridge(&bridge::Options {
        root: &fixture(),
        unit: "packages/a/src/util.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: bridge::Allocator::RustyAlloc,
    })
    .unwrap();
    assert!(!read(&dir, "src/lib.rs").contains("global_allocator"));
    assert!(!read(&dir, "Cargo.toml").contains("rusty_alloc"));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn php_functions_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/php-functions");
    let dir = std::env::temp_dir().join(format!("rust-anything-php-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let options = |batch: Vec<String>| bridge::Options {
        root: &root,
        unit: "src/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("textfns-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch,
        as_json: Vec::new(),
        allocator: Default::default(),
    };
    let batch = bridge::bridge(&options(vec!["slugify:text".into()]))
        .unwrap_err()
        .to_string();
    assert_eq!(batch, "`--batch` is not available for PHP units yet");
    let outcome = bridge::bridge(&options(Vec::new())).unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    let before = std::fs::read_to_string(dir.join("rust-anything.json")).unwrap();
    let refresh_batch = bridge::add_batches(&dir, &["slugify:text".into()])
        .unwrap_err()
        .to_string();
    assert_eq!(
        refresh_batch,
        "`--batch` is not available for PHP units yet"
    );
    assert_eq!(
        std::fs::read_to_string(dir.join("rust-anything.json")).unwrap(),
        before
    );
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<(&str, &str)> = manifest
        .js_only
        .iter()
        .map(|j| (j.name.as_str(), j.reason.as_str()))
        .collect();
    assert_eq!(
        kept,
        [
            ("each_word", "returns an object (`\\Generator`)"),
            ("stamp", "takes an object `$at` (`\\DateTimeInterface`)"),
        ]
    );
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for signature in [
        "pub fn slugify(text: String, sep: String, max: Option<i64>) -> Result<String, String>",
        "pub fn mean(xs: Vec<f64>) -> Result<f64, String>",
        "pub fn words(text: String) -> Result<Vec<String>, String>",
        "pub fn count_words(text: String) -> Result<serde_json::Value, String>",
    ] {
        assert!(port.contains(signature), "{signature}\n{port}");
    }
    let wrapper = std::fs::read_to_string(dir.join("php/textfns_rs.php")).unwrap();
    assert!(wrapper.contains("namespace Acme\\Text {"), "{wrapper}");
    assert!(
        wrapper.contains(
            "function slugify(string $text, string $sep = '-', ?int $max = null)\n    {\n        \
             return \\RustAnything\\NativeTextfnsRs::call('slugify', [$text, $sep, $max]);"
        ),
        "{wrapper}"
    );
    let refused = shadow::shadow(&dir, None).unwrap_err().to_string();
    assert!(refused.contains("cannot redefine a function"), "{refused}");
    let statics_dir = dir.join("statics");
    let statics = bridge::bridge(&bridge::Options {
        root: &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/php"),
        unit: "src/Text/Slug.php",
        kind: None,
        out: Some(statics_dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(statics.kind, Kind::Ffi);
    let statics_manifest = Manifest::load(&statics_dir).unwrap();
    let statics_wrapper =
        std::fs::read_to_string(statics_dir.join(codegen_php::wrapper_path(&statics_manifest)))
            .unwrap();
    assert!(
        statics_wrapper.contains("namespace Acme\\Textkit\\Text {"),
        "{statics_wrapper}"
    );
    assert!(
        statics_wrapper.contains("final class Slug"),
        "{statics_wrapper}"
    );
    assert!(
        statics_wrapper.contains("public static function slugify(string $text, string $sep = '-')"),
        "{statics_wrapper}"
    );
    assert!(
        statics_wrapper.contains("public static function truncate(string $text, int $max)"),
        "{statics_wrapper}"
    );
    if !common::have_with(
        "php",
        &[
            "-d",
            "ffi.enable=1",
            "-r",
            "exit(class_exists('FFI') ? 0 : 1);",
        ],
        "is missing or has no FFI extension",
    ) {
        return;
    }
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"count_words\", \"args\": [\"to be or not to be\"]}\n\
         {\"fn\": \"count_words\", \"args\": [\"10 010 10\"]}\n\
         {\"fn\": \"clamp\", \"args\": [42, {\"$undefined\": true}, 50]}\n\
         {\"fn\": \"digit\", \"args\": [\"7\"]}\n\
         {\"fn\": \"digit\", \"args\": [\"abc\"]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 100, "{recorded:?}");
    assert!(recorded.errors > 0);
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(
        cases.contains("\"ok\":{\"to\":2,\"be\":2,\"or\":1,\"not\":1}"),
        "{cases}"
    );
    assert!(
        cases.contains("{\"fn\":\"clamp\",\"args\":[42,{\"$undefined\":true},50],\"ok\":42}"),
        "the default applies to an omitted middle argument"
    );
    assert!(
        cases.contains(r#"{"fn":"digit","args":["7"],"ok":7}"#),
        "{cases}"
    );
    assert!(cases.contains("\"error_type\":\"DivisionByZeroError\""));
    assert!(
        cases.contains(r#""error_type":"Acme\\Numbers\\ParseException""#),
        "{cases}"
    );
    let mut port = port;
    for (name, body) in [
        (
            "clamp",
            "if lo > hi { return Err(\"InvalidArgumentException: lo is above hi\".into()); } \
             Ok(lo.max(hi.min(value)))",
        ),
        (
            "mean",
            "if xs.is_empty() { return Err(\"DomainException: mean of nothing\".into()); } \
             Ok(xs.iter().fold(0.0, |a, b| a + b) / xs.len() as f64)",
        ),
        (
            "ratio",
            "if b == 0.0 { return Err(\"DivisionByZeroError: Division by zero\".into()); } \
             Ok(a / b)",
        ),
        (
            "digit",
            "if text.len() == 1 && text.as_bytes()[0].is_ascii_digit() { \
             Ok(i64::from(text.as_bytes()[0] - b'0')) } else { \
             Err(\"Acme\\\\Numbers\\\\ParseException: not a digit\".into()) }",
        ),
        (
            "words",
            "Ok(text.split(' ').filter(|w| !w.is_empty()).map(String::from).collect())",
        ),
        (
            "count_words",
            "let mut counts = serde_json::Map::new(); \
             for w in text.split(' ').filter(|w| !w.is_empty()) { \
             let n = counts.get(w).and_then(serde_json::Value::as_i64).unwrap_or(0); \
             counts.insert(w.to_string(), (n + 1).into()); } \
             Ok(serde_json::Value::Object(counts))",
        ),
    ] {
        let file = if matches!(name, "clamp" | "mean" | "ratio" | "digit") {
            "numbers"
        } else {
            "text"
        };
        let stub = format!("unimplemented!(\"port `{name}` from src/{file}.php\")");
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.total, recorded.cases);
    let unported = cases
        .lines()
        .filter(|l| l.starts_with("{\"fn\":\"slugify\"") || l.starts_with("{\"fn\":\"top\""))
        .filter(|l| !l.contains("\"error_type\":\"TypeError\""))
        .count();
    assert_eq!(diff.failed, unported, "{:?}", diff.mismatches);
    assert!(
        diff.mismatches
            .iter()
            .all(|m| matches!(m["fn"].as_str(), Some("slugify" | "top"))),
        "{:?}",
        diff.mismatches
    );
    assert!(diff.passed > 0);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn php_static_methods_bridge_record_and_diff() {
    if !common::have_with(
        "php",
        &[
            "-d",
            "ffi.enable=1",
            "-r",
            "exit(class_exists('FFI') ? 0 : 1);",
        ],
        "is missing or has no FFI extension",
    ) {
        return;
    }
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/php-static");
    let dir = std::env::temp_dir().join(format!("rust-anything-php-static-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("static-text-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<(&str, &str)> = manifest
        .js_only
        .iter()
        .map(|j| (j.name.as_str(), j.reason.as_str()))
        .collect();
    assert_eq!(kept.len(), 6, "{kept:?}");
    assert!(
        kept.contains(&(
            "cap",
            "`Consts` has public constants, so its static methods stay in PHP"
        )),
        "{kept:?}"
    );
    assert!(
        kept.contains(&(
            "twice",
            "`Blend` also has instance methods, so its static methods stay in PHP"
        )),
        "{kept:?}"
    );
    assert!(
        kept.contains(&(
            "bounded",
            "`Defined` is in a file with top-level code (a constant, a require or a side effect), \
             so the wrapper cannot replace the file"
        )),
        "{kept:?}"
    );
    assert!(
        kept.contains(&(
            "one",
            "`StaticHelper` shares its file with another declaration, so the wrapper cannot \
             replace the file"
        )),
        "{kept:?}"
    );
    assert!(
        kept.contains(&(
            "reset",
            "returns nothing: the recording only compares return values, so a port that does \
             nothing would pass"
        )),
        "{kept:?}"
    );
    assert!(
        kept.iter().any(|(name, reason)| *name == "size"
            && reason.contains("`Voided` has a method that stays in PHP")
            && reason.contains("`reset`: returns nothing")),
        "{kept:?}"
    );
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for signature in [
        "pub fn count(text: String) -> Result<i64, String>",
        "pub fn clamp(value: i64, lo: i64, hi: i64) -> Result<i64, String>",
    ] {
        assert!(port.contains(signature), "{signature}\n{port}");
    }
    assert!(!port.contains("pub fn size"), "{port}");
    assert!(!port.contains("pub fn reset"), "{port}");
    assert!(!port.contains("pub fn bounded"), "{port}");
    assert!(!port.contains("pub fn one"), "{port}");
    let wrapper = std::fs::read_to_string(dir.join(codegen_php::wrapper_path(&manifest))).unwrap();
    for expected in [
        "namespace Acme\\StaticText {",
        "final class Words",
        "public static function count(string $text)",
        "public static function clamp(int $value, int $lo = 0, int $hi = 10)",
        "\\RustAnything\\NativeStaticTextRs::call('count', [$text]);",
    ] {
        assert!(wrapper.contains(expected), "{expected}\n{wrapper}");
    }
    assert!(!wrapper.contains("class Blend"), "{wrapper}");
    assert!(!wrapper.contains("class Consts"), "{wrapper}");
    assert!(!wrapper.contains("class Voided"), "{wrapper}");
    assert!(!wrapper.contains("class Defined"), "{wrapper}");
    assert!(!wrapper.contains("class StaticHelper"), "{wrapper}");
    assert!(!wrapper.contains("class InstanceHelper"), "{wrapper}");
    let lint = Command::new("php")
        .arg("-l")
        .arg(dir.join(codegen_php::wrapper_path(&manifest)))
        .output()
        .unwrap();
    assert!(
        lint.status.success(),
        "invalid wrapper: {}",
        String::from_utf8_lossy(&lint.stderr)
    );

    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"count\", \"args\": [\"hello\"]}\n\
         {\"fn\": \"clamp\", \"args\": [42, {\"$undefined\": true}, 50]}\n\
         {\"fn\": \"clamp\", \"args\": [5, 10, 0]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
    assert!(recorded.errors > 0, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(
        cases.contains("{\"fn\":\"clamp\",\"args\":[42,{\"$undefined\":true},50],\"ok\":42}"),
        "the default applies to an omitted middle argument: {cases}"
    );
    assert!(
        cases.contains("\"error_type\":\"InvalidArgumentException\""),
        "{cases}"
    );

    let mut port = port;
    for (name, body) in [
        ("count", "Ok(text.len() as i64)"),
        (
            "clamp",
            "if lo > hi { return Err(\"InvalidArgumentException: lo is above hi\".into()); } \
             Ok(lo.max(hi.min(value)))",
        ),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from src/Words.php\")");
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.failed, 0, "{:?}", diff.mismatches);
    assert!(diff.passed > 0);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn php_static_methods_with_same_name_bridge_record_and_diff() {
    if !common::have_with(
        "php",
        &[
            "-d",
            "ffi.enable=1",
            "-r",
            "exit(class_exists('FFI') ? 0 : 1);",
        ],
        "is missing or has no FFI extension",
    ) {
        return;
    }
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/php-static-clash");
    let dir = std::env::temp_dir().join(format!(
        "rust-anything-php-static-clash-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("clash-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    assert_eq!(outcome.exports, ["Arr::length", "Str::length"]);

    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"Str::length\", \"args\": [\"hello world\"]}\n\
         {\"fn\": \"Arr::length\", \"args\": [\"hello world\"]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 10,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(
        cases.contains("{\"fn\":\"Str::length\",\"args\":[\"hello world\"],\"ok\":11}"),
        "{cases}"
    );
    assert!(
        cases.contains("{\"fn\":\"Arr::length\",\"args\":[\"hello world\"],\"ok\":2}"),
        "{cases}"
    );

    let port_template = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let str_stub = "unimplemented!(\"port `Str::length` from src/Str.php\")";
    let arr_stub = "unimplemented!(\"port `Arr::length` from src/Arr.php\")";
    assert!(port_template.contains(str_stub), "{port_template}");
    assert!(port_template.contains(arr_stub), "{port_template}");
    let write_port = |str_body: &str, arr_body: &str| {
        let port = port_template
            .replace(str_stub, str_body)
            .replace(arr_stub, arr_body);
        std::fs::write(dir.join("src/port.rs"), port).unwrap();
    };

    // Correct bodies pass.
    write_port(
        "Ok(s.len() as i64)",
        "Ok(s.split(' ').filter(|w| !w.is_empty()).count() as i64)",
    );
    harness::build(&dir).unwrap();
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.failed, 0, "{:?}", diff.mismatches);
    assert!(diff.passed > 0);

    // Swapped bodies fail.
    write_port(
        "Ok(s.split(' ').filter(|w| !w.is_empty()).count() as i64)",
        "Ok(s.len() as i64)",
    );
    harness::build(&dir).unwrap();
    let swapped = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert!(swapped.failed > 0, "expected swapped bodies to fail");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn csharp_static_methods_bridge_record_and_diff() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/csharp-units");
    let dir = std::env::temp_dir().join(format!("rust-anything-csharp-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let options = |batch: Vec<String>| bridge::Options {
        root: &root,
        unit: "src/",
        kind: None,
        out: Some(dir.clone()),
        name: Some("geo-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch,
        as_json: Vec::new(),
        allocator: Default::default(),
    };
    let batch = bridge::bridge(&options(vec!["Mean:xs".into()]))
        .unwrap_err()
        .to_string();
    assert!(
        batch.contains("`--batch` is not available for C#"),
        "{batch}"
    );
    let outcome = bridge::bridge(&options(Vec::new())).unwrap();
    assert_eq!(outcome.kind, Kind::Ffi);
    let before = std::fs::read_to_string(dir.join("rust-anything.json")).unwrap();
    let refresh_batch = bridge::add_batches(&dir, &["Mean:xs".into()])
        .unwrap_err()
        .to_string();
    assert_eq!(refresh_batch, "`--batch` is not available for C# units yet");
    assert_eq!(
        std::fs::read_to_string(dir.join("rust-anything.json")).unwrap(),
        before
    );
    let manifest = Manifest::load(&dir).unwrap();
    let kept: Vec<(&str, &str)> = manifest
        .js_only
        .iter()
        .map(|j| (j.name.as_str(), j.reason.as_str()))
        .collect();
    assert_eq!(
        kept,
        [
            ("Identity", "generic"),
            (
                "Price",
                "uses `decimal`, a 128-bit decimal no JSON number keeps exactly"
            ),
            ("TryHalf", "takes a parameter by reference"),
        ]
    );
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for signature in [
        "pub fn distance(a: serde_json::Value, b: serde_json::Value) -> Result<f64, String>",
        "pub fn total(r#box: serde_json::Value) -> Result<i64, String>",
        "pub fn clamp(value: i64, lo: i64, hi: i64) -> Result<i64, String>",
        "pub fn words(text: String) -> Result<Vec<String>, String>",
        "pub fn first_index(text: String, needle: String) -> Result<Option<i64>, String>",
        "pub fn digit(s: String) -> Result<i64, String>",
    ] {
        assert!(port.contains(signature), "{signature}\n{port}");
    }
    let wrapper = std::fs::read_to_string(dir.join("cs/GeoRs.cs")).unwrap();
    for expected in [
        "namespace Acme.Geo.Rust\n{\n    public static class Geometry",
        "public static int Clamp(int value, int lo = 0, int hi = 100) =>\n            \
         global::RustAnything.GeoRsNative.Call<int>(\"Clamp\", new object?[] { value, lo, hi });",
        "public static Point Midpoint(Point a, Point b) =>",
        "using System.Collections.Generic;",
    ] {
        assert!(wrapper.contains(expected), "{expected}\n{wrapper}");
    }
    let header = wrapper.lines().take(4).collect::<Vec<_>>().join("\n");
    assert!(header.contains("Acme.Geo.Rust"), "{header}");
    assert!(
        header.contains("using Geometry = Acme.Geo.Rust.Geometry;"),
        "{header}"
    );
    assert!(!wrapper.contains("<namespace>"), "{wrapper}");
    assert!(!wrapper.contains("Acme.Text.Rust"), "{wrapper}");
    let readme = std::fs::read_to_string(dir.join("README.md")).unwrap();
    assert!(readme.contains("Acme.Geo.Rust"), "{readme}");
    assert!(!readme.contains("<namespace>"), "{readme}");
    assert!(!readme.contains("Acme.Text.Rust"), "{readme}");
    let refused = shadow::shadow(&dir, None).unwrap_err().to_string();
    assert!(
        refused.contains("C# binds calls when it compiles"),
        "{refused}"
    );
    assert!(refused.contains("Acme.Geo.Rust"), "{refused}");
    assert!(!refused.contains("<namespace>"), "{refused}");
    if !common::have("dotnet") {
        return;
    }
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 200, "{recorded:?}");
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    for expected in [
        "\"error_type\":\"System.ArgumentException\"",
        "\"error_type\":\"System.OverflowException\"",
        "\"error_type\":\"System.NullReferenceException\"",
        "{\"fn\":\"Mean\",\"args\":[[]],\"error\":\"mean of nothing\",\
         \"error_type\":\"System.InvalidOperationException\"}",
    ] {
        assert!(cases.contains(expected), "{expected}");
    }
    assert!(
        cases.lines().any(|line| {
            let case: serde_json::Value = serde_json::from_str(line).unwrap();
            case["fn"] == "Digit" && case["error_type"] == "Acme.Geo.Geometry+ParseException"
        }),
        "Digit should record the nested exception"
    );
    assert!(
        cases
            .lines()
            .any(|l| l.starts_with("{\"fn\":\"Clamp\",\"args\":[") && l.contains("$undefined")),
        "the default applies to an omitted argument"
    );
    assert!(
        !cases.contains("\"args\":[9223372036854775807"),
        "an input that does not fit `int` is not recorded"
    );
    let mut port = port;
    for (name, body) in [
        (
            "Distance",
            "if a.is_null() || b.is_null() { return Err(NRE.into()); } \
             let (dx, dy) = (num(&a[\"X\"]) - num(&b[\"X\"]), num(&a[\"Y\"]) - num(&b[\"Y\"])); \
             Ok((dx * dx + dy * dy).sqrt())",
        ),
        (
            "Midpoint",
            "if a.is_null() || b.is_null() { return Err(NRE.into()); } \
             Ok(serde_json::json!({ \"X\": out((num(&a[\"X\"]) + num(&b[\"X\"])) / 2.0), \
             \"Y\": out((num(&a[\"Y\"]) + num(&b[\"Y\"])) / 2.0) }))",
        ),
        (
            "Total",
            "if r#box.is_null() { return Err(NRE.into()); } \
             let mut total: i32 = 0; \
             for s in r#box[\"Sizes\"].as_array().into_iter().flatten() { \
             total = total.checked_add(s.as_i64().unwrap_or(0) as i32).ok_or(\
             \"System.OverflowException: Arithmetic operation resulted in an overflow.\")?; } \
             Ok(i64::from(total))",
        ),
        (
            "Mean",
            "if xs.is_empty() { return Err(\"System.InvalidOperationException: mean of nothing\".into()); } \
             Ok(xs.iter().fold(0.0, |a, b| a + b) / xs.len() as f64)",
        ),
        (
            "Clamp",
            "if lo > hi { return Err(\"System.ArgumentException: lo is above hi\".into()); } \
             Ok(lo.max(hi.min(value)))",
        ),
        (
            "Words",
            "Ok(text.split(' ').filter(|w| !w.is_empty()).map(String::from).collect())",
        ),
        (
            "CountWords",
            "let mut counts = serde_json::Map::new(); \
             for w in text.split(' ').filter(|w| !w.is_empty()) { \
             let n = counts.get(w).and_then(serde_json::Value::as_i64).unwrap_or(0); \
             counts.insert(w.to_string(), (n + 1).into()); } \
             Ok(serde_json::Value::Object(counts))",
        ),
        (
            "Digit",
            "if s.len() == 1 && s.as_bytes()[0].is_ascii_digit() { \
             Ok(i64::from(s.as_bytes()[0] - b'0')) } else { \
             Err(\"Acme.Geo.Geometry+ParseException: not a digit\".into()) }",
        ),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from src/Geometry.cs\")");
        assert!(port.contains(&stub), "{stub}");
        port = port.replace(&stub, body);
    }
    port.push_str(
        "\nconst NRE: &str = \"System.NullReferenceException: Object reference not set to an \
         instance of an object.\";\n\
         fn num(v: &serde_json::Value) -> f64 { match v[\"$num\"].as_str() { \
         Some(\"NaN\") => f64::NAN, Some(\"Infinity\") => f64::INFINITY, \
         Some(\"-Infinity\") => f64::NEG_INFINITY, Some(\"-0\") => -0.0, \
         _ => v.as_f64().unwrap_or(0.0) } }\n\
         fn out(x: f64) -> serde_json::Value { if x.is_nan() { serde_json::json!({\"$num\": \"NaN\"}) } \
         else if x.is_infinite() { serde_json::json!({\"$num\": if x > 0.0 { \"Infinity\" } else { \"-Infinity\" }}) } \
         else { serde_json::json!(x) } }\n",
    );
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    harness::build(&dir).unwrap();
    let (diff, counts) = harness::diff_full_with_counts(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.total, recorded.cases);
    let (passed, total) = counts["Digit"];
    assert_eq!(
        passed, total,
        "Digit replay mismatches: {:?}",
        diff.mismatches
    );
    let unported = cases
        .lines()
        .filter(|l| l.starts_with("{\"fn\":\"FirstIndex\""))
        .count();
    assert_eq!(diff.failed, unported, "{:?}", diff.mismatches);
    assert!(
        diff.mismatches.iter().all(|m| m["fn"] == "FirstIndex"
            && m["actual"]["error_type"]
                .as_str()
                .is_some_and(|t| t.ends_with("RustPanicException"))),
        "{:?}",
        diff.mismatches
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn python_float_subclass_records_as_its_float_value() {
    // NumPy 2's `repr(np.float64(0.0))` is "np.float64(0.0)"; a float subclass with that kind of
    // repr must record as the float it is, or a port returning a plain float can never match.
    // Its `__float__` is overridden too: the value recorded is the one stored, not what it returns.
    let Some(_) = common::python() else {
        return;
    };
    let root = std::env::temp_dir().join(format!("rust-anything-pyfloat-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("src/floatkit")).unwrap();
    std::fs::write(
        root.join("pyproject.toml"),
        "[project]\nname = \"floatkit\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    std::fs::write(
        root.join("src/floatkit/__init__.py"),
        "class _F64(float):\n    def __repr__(self):\n        return f\"_F64({float.__repr__(self)})\"\n\n\
         \x20   def __float__(self):\n        return 2.0\n\n\n\
         def centre(x: float) -> float:\n    return _F64(x - x)\n",
    )
    .unwrap();
    let dir = root.join("crate");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/floatkit/",
        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();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 20,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    // `post` marks a line that also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#","post":true"#, "");
    assert!(cases.contains(r#"{"$float": "0.0"}"#), "{cases}");
    assert!(!cases.contains("_F64"), "{cases}");
    // A pure-Python stand-in for the built package that returns plain floats.
    let manifest = Manifest::load(&dir).unwrap();
    let package = dir
        .join("python")
        .join(manifest.crate_name.replace('-', "_"));
    std::fs::create_dir_all(&package).unwrap();
    std::fs::write(
        package.join("__init__.py"),
        "def centre(x):\n    return float(x - x)\n",
    )
    .unwrap();
    common::mark_built(&dir);
    let diff = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(diff.failed, 0, "{:?}", diff.mismatches);
    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn gate_catches_hard_coded_results_edited_recordings_and_removed_tests() {
    if !common::have("node") {
        return;
    }
    let dir = bridged("cheat");
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 60,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let manifest = Manifest::load(&dir).unwrap();
    let source = std::fs::read_to_string(fixture().join("packages/a/src/util.ts")).unwrap();
    let cases = std::fs::read_to_string(dir.join(harness::CASES)).unwrap();
    let mut outputs: Vec<String> = Vec::new();
    for line in cases.lines() {
        let Ok(case) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        let mut leaves = vec![&case["ok"]];
        while let Some(v) = leaves.pop() {
            match v {
                serde_json::Value::String(s)
                    if s.chars().count() >= 8
                        && !source.contains(s.as_str())
                        && !outputs.contains(s) =>
                {
                    outputs.push(s.clone());
                }
                serde_json::Value::Array(a) => leaves.extend(a),
                serde_json::Value::Object(o) => leaves.extend(o.values()),
                _ => {}
            }
        }
    }
    assert!(outputs.len() >= 3, "{outputs:?}");
    let port = |mark: &str| {
        let arms: String = outputs[..3]
            .iter()
            .enumerate()
            .map(|(i, s)| format!("        {i} => {s:?},{mark}\n"))
            .collect();
        format!(
            "pub fn answer(i: u8) -> &'static str {{\n    match i {{\n{arms}        _ => \"\",\n    }}\n}}\n"
        )
    };
    std::fs::write(dir.join("src/port.rs"), port("")).unwrap();
    let check = rust_anything::gate::literals_check(&dir, &manifest).unwrap();
    assert!(!check.passed, "{check:?}");
    assert!(
        check.detail.starts_with("3 recorded values"),
        "{}",
        check.detail
    );
    // A marker excuses a constant the original takes from a library, not a table of results:
    // three recorded values under markers still fail.
    std::fs::write(
        dir.join("src/port.rs"),
        port(" // recorded-literal: a fixed table in the original's library"),
    )
    .unwrap();
    let check = rust_anything::gate::literals_check(&dir, &manifest).unwrap();
    assert!(!check.passed, "{check:?}");
    assert!(
        check.detail.contains("a marker excuses a constant"),
        "{}",
        check.detail
    );
    // One or two such constants, marked with a reason, are fine.
    let two_marked: String = port("")
        .lines()
        .enumerate()
        .map(|(n, line)| {
            if (3..5).contains(&n) {
                format!(
                    "{line} // recorded-literal: a constant the original takes from a library\n"
                )
            } else {
                format!("{line}\n")
            }
        })
        .collect();
    std::fs::write(dir.join("src/port.rs"), two_marked).unwrap();
    let check = rust_anything::gate::literals_check(&dir, &manifest).unwrap();
    assert!(check.passed, "{check:?}");

    assert_eq!(rust_anything::recording::cases_tampered(&dir), None);
    let first = cases.lines().next().unwrap();
    std::fs::write(
        dir.join(harness::CASES),
        cases.strip_prefix(&format!("{first}\n")).unwrap(),
    )
    .unwrap();
    let why = rust_anything::recording::cases_tampered(&dir).expect("a removed case");
    assert!(why.contains("cases.jsonl changed"), "{why}");
    std::fs::write(dir.join(harness::CASES), format!("{cases}{first}\n")).unwrap();
    assert_eq!(rust_anything::recording::cases_tampered(&dir), None);

    let tested = |asserts: &str| {
        std::fs::write(
            dir.join("src/port.rs"),
            format!(
                "pub fn two() -> u8 {{ 2 }}\n\n#[cfg(test)]\nmod tests {{\n    #[test]\n    fn two() {{\n{asserts}    }}\n}}\n"
            ),
        )
        .unwrap();
        rust_anything::gate::tests_check(&dir)
    };
    let both = "        assert_eq!(super::two(), 2);\n        assert!(super::two() > 1);\n";
    let first_run = tested(both);
    assert!(first_run.passed, "{first_run:?}");
    assert!(
        first_run.detail.contains("baseline once gate passes"),
        "{first_run:?}"
    );
    rust_anything::gate::save_tests_baseline(&dir).unwrap();
    assert!(tested(both).passed);
    let weaker = tested("        assert_eq!(super::two(), 2);\n");
    assert!(!weaker.passed, "{weaker:?}");
    assert_eq!(
        weaker.detail,
        "assertions 2 -> 1 since the last passing gate"
    );
    std::fs::remove_dir_all(&dir).unwrap();
}

#[cfg(unix)]
#[test]
fn go_lets_its_agent_run_diff_while_it_holds_the_recording() {
    let Some(python) = common::python() else {
        return;
    };
    let repo = std::env::temp_dir().join(format!("rust-anything-go-agent-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join("pyproject.toml"),
        "[project]\nname = \"calc\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    std::fs::write(
        repo.join("calc.py"),
        "def score(s: str) -> int:\n    total = 0\n    for ch in s:\n        total += ord(ch) % 7\n    return total\n",
    )
    .unwrap();
    std::fs::write(
        repo.join("main.py"),
        "from calc import score\n\nfor i in range(20000):\n    score(\"hello world %d\" % i)\n",
    )
    .unwrap();
    let agent = repo.join("agent.sh");
    std::fs::write(
        &agent,
        "cat > /dev/null\n\
         cat > src/port.rs <<'RS'\n\
         pub fn score(s: String) -> Result<i64, String> {\n    \
         Ok(s.chars().map(|c| i64::from(u32::from(c) % 7)).sum())\n\
         }\n\
         RS\n\
         (\"$RA_TEST_BIN\" build . && \"$RA_TEST_BIN\" diff .) > /dev/null 2>&1 &\n\
         pid=$!\n\
         (sleep 120; kill $pid) > /dev/null 2>&1 &\n\
         watchdog=$!\n\
         wait $pid\n\
         echo $? > diffed\n\
         kill $watchdog 2> /dev/null\n",
    )
    .unwrap();
    let out = common::cli()
        .current_dir(&repo)
        .env("RA_TEST_BIN", env!("CARGO_BIN_EXE_rust-anything"))
        .args(["go", "--root", ".", "--json", "--agent"])
        .arg(format!("sh {}", agent.display()))
        .args(["--", python, "main.py"])
        .output()
        .unwrap();
    let diffed = std::fs::read_to_string(repo.join("rust/score-rs/diffed")).unwrap_or_default();
    let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap_or_default();
    std::fs::remove_dir_all(&repo).unwrap();
    assert_eq!(
        diffed.trim(),
        "0",
        "the agent's diff did not finish: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        matches!(json["stage"].as_str(), Some("on" | "slower")),
        "{json}"
    );
}

#[test]
fn csharp_value_tuples_bridge_record_and_diff() {
    // Issue #1048: a value tuple crosses as a JSON array, not as `{"Item1": …}`.
    let root =
        std::env::temp_dir().join(format!("rust-anything-csharp-tuple-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("tuple.csproj"),
        "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>\n",
    )
    .unwrap();
    std::fs::write(
        root.join("Tuple.cs"),
        "public static class Measure\n{\n    \
         public static (int Count, int Width) Sizes(string s) { return (s.Length, s.Length * 2); }\n    \
         public static double Area((double W, double H) box) { return box.W * box.H; }\n    \
         public static (int, string) Pair(int n) { return (n, \"n\" + n); }\n}\n",
    )
    .unwrap();
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "Tuple.cs",
        kind: None,
        out: Some(dir.clone()),
        name: Some("tuple-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for signature in [
        "pub fn sizes(s: String) -> Result<serde_json::Value, String>",
        "pub fn pair(n: i64) -> Result<serde_json::Value, String>",
        "pub fn area(r#box: serde_json::Value) -> Result<f64, String>",
    ] {
        assert!(port.contains(signature), "{signature}\n{port}");
    }
    let wrapper = std::fs::read_to_string(dir.join("cs/TupleRs.cs")).unwrap();
    assert!(wrapper.contains("RATupleConverterFactory"), "{wrapper}");
    assert!(
        wrapper.contains("ITuple"),
        "the converter reads tuples by interface"
    );

    if !common::have("dotnet") {
        let _ = std::fs::remove_dir_all(&root);
        return;
    }
    std::fs::write(
        dir.join("src/port.rs"),
        "pub fn sizes(s: String) -> Result<serde_json::Value, String> {\n    \
         let n = s.encode_utf16().count() as i64;\n    Ok(serde_json::json!([n, n * 2]))\n}\n\n\
         pub fn area(r#box: serde_json::Value) -> Result<f64, String> {\n    \
         Ok(r#box[0].as_f64().unwrap_or(0.0) * r#box[1].as_f64().unwrap_or(0.0))\n}\n\n\
         pub fn pair(n: i64) -> Result<serde_json::Value, String> {\n    \
         Ok(serde_json::json!([n, format!(\"n{n}\")]))\n}\n",
    )
    .unwrap();
    // Explicit inputs for the parameter direction: generated ones need not reach `Area`, whose
    // argument is a tuple.
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\":\"Area\",\"args\":[[2.5, 4]]}\n\
         {\"fn\":\"Area\",\"args\":[[0, 0]]}\n\
         {\"fn\":\"Area\",\"args\":[[3]]}\n\
         {\"fn\":\"Area\",\"args\":[[1, 2, 3]]}\n\
         {\"fn\":\"Area\",\"args\":[{\"W\":1,\"H\":2}]}\n\
         {\"fn\":\"Pair\",\"args\":[7]}\n\
         {\"fn\":\"Sizes\",\"args\":[\"hi\"]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 40,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 20, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    // The parameter direction: a tuple went in as an array and came back as its area.
    assert!(
        cases.lines().any(|l| l.starts_with("{\"fn\":\"Area\"")
            && l.contains("\"args\":[[2.5,4]]")
            && l.contains("\"ok\":10")),
        "{cases}"
    );
    // An array of the wrong length, or an object, is not a tuple: it is not padded or cut to fit.
    for args in ["[[3]]", "[[1,2,3]]", "[{\"W\":1,\"H\":2}]"] {
        assert!(
            !cases.contains(&format!("\"args\":{args}")),
            "{args}: {cases}"
        );
    }
    // A named and an unnamed tuple both record as arrays of their values.
    assert!(
        cases
            .lines()
            .any(|l| l.starts_with("{\"fn\":\"Sizes\"") && l.contains("\"ok\":[")),
        "{cases}"
    );
    assert!(
        cases
            .lines()
            .any(|l| l.starts_with("{\"fn\":\"Pair\"") && l.contains("\"ok\":[")),
        "{cases}"
    );
    assert!(
        !cases.contains("Item1"),
        "the element names are not data: {cases}"
    );

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        float_tolerance: None,
        node_args: &[],
    })
    .unwrap();
    assert_eq!(outcome.failed, 0, "{:?}", outcome.mismatches);
    let _ = std::fs::remove_dir_all(&root);
}