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.

206 KB
Raw Blame
//! Steps 3 and 5's runtime half: record what the original code does, build the Rust module, and
//! replay the recorded cases against it.
//!
//! Both sides run in Node through small generated scripts, so the comparison sees exactly
//! what a JS caller sees. Values are encoded so `undefined`, `NaN`, `-0`, `Map`, `Set`,
//! `BigInt` and key order survive JSON.

use crate::walk::Canonical;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::bridge::{Kind, Manifest, RType, param_type};
use crate::ts::exports::LocalType;
use crate::ts::shape::{self, Shape};

pub const CASES: &str = "cases.jsonl";
pub(crate) const WORK_DIR: &str = ".rust-anything";
pub(crate) const COVERAGE_DIR: &str = "coverage";

/// Strings that break naive ports: empty, case, whitespace, non-ASCII, astral, combining.
const STRINGS: &[&str] = &[
    "",
    "a",
    "ab",
    "abc",
    "hello",
    "hello world",
    "Hello World",
    "HELLO",
    "  padded  ",
    "a.b.c",
    "ns:key.path",
    "a:b:c",
    ":",
    ".leading",
    "trailing.",
    "a..b",
    "src/a/b.ts",
    "./x/**/*.json",
    "key_name-1",
    "{name} has {count} items",
    "line1\nline2",
    "tab\tseparated",
    "ünïcödé",
    "straße",
    "İstanbul",
    "ΣΊΣΥΦΟΣ",
    "日本語のテキスト",
    "emoji 👍🏽 mix",
    "😀",
    "a😀b😀c",
    "e\u{301}",
    "\u{FEFF}bom",
];
pub(crate) const JSON_VALUES: &str =
    r#"[null, true, 0, "x", [], {}, {"a": "b"}, {"a": {"b": "c"}}, ["a", 1]]"#;

#[derive(Debug, Serialize)]
pub struct RecordOutcome {
    pub path: PathBuf,
    pub cases: usize,
    pub errors: usize,
    /// Cases from the semantic traps (added to the generated ones for every function).
    pub traps: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub nested: usize,
    pub per_function: BTreeMap<String, usize>,
    /// Functions in files that use regexes: their string parameters also got the regex traps.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub regex_functions: Vec<String>,
    /// TS/JS functions that decode a parameter, listed by function and parameter name.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub decoded: Vec<String>,
    /// Inputs left out because the original ran past the per-case time limit on them.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub timed_out: Vec<Value>,
    /// Lines of the original the cases ran (TS/JS from V8's coverage, Python from the driver's).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coverage: Option<Value>,
    /// The clock and seed the original ran with (`--pin-clock`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pinned: Option<crate::pin::Pin>,
    /// Inputs the generator asked for (recorded, timed out or dropped); 0 when not counted.
    #[serde(skip_serializing_if = "is_zero")]
    pub generated: usize,
    /// Inputs that were generated but are not in the recording, other than by the time limit,
    /// allowed with `--allow-dropped`: the driver could not encode or decode them, or the
    /// original ended the run before them.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub dropped: Vec<DroppedCase>,
    /// Generated inputs whose arguments do not fit the original's parameter types: not in the
    /// recording, and no loss, since the original cannot be called with them.
    #[serde(skip_serializing_if = "is_zero")]
    pub inapplicable: usize,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct DiffOutcome {
    pub total: usize,
    pub passed: usize,
    pub failed: usize,
    /// Exports the Rust module does not provide.
    pub missing: Vec<String>,
    /// The first mismatches: `{ fn, args, expected, actual }`.
    pub mismatches: Vec<Value>,
    /// Mismatches `known-diffs.jsonl` explains, counted in `passed`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub accepted: usize,
    /// `known-diffs.jsonl` entries no mismatch matched any more.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stale_known: Vec<Value>,
    /// Matches across the last changes to `port.rs`, and whether they stopped going up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trend: Option<crate::recording::Trend>,
    /// The distinct differences among all the mismatches (not only the first ones), most cases
    /// first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<crate::mismatch::Group>,
    /// Recorded errors that carry no error class (a recording from before classes were kept):
    /// for these the port only has to throw, not to throw the same class.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub untyped_errors: usize,
    /// Cases whose recording holds no post-call state (made before it was kept, or captured from
    /// a project's tests): compared by return value only.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub legacy_cases: usize,
    /// Recorded cases the original crashed on (C): counted in `passed` without running the port.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub not_rerun: usize,
    /// What loosened this verdict, one sentence each: the float tolerance, ignored key order,
    /// errors compared without their class, crash cases not re-run. Show them next to the count.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
    /// Version of this JSON ([`crate::state::schema`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// When the diff ran, UTC.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<String>,
    /// The port version it ran on ([`crate::state::port_version`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<String>,
    /// Custom batch index checks (`port::<Fn>Index::run` and `rank`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub batches: Vec<crate::batch_check::BatchDiff>,
}

/// Stamps a diff of the crate's own port with `port`, the version taken before it ran, and saves
/// it as `.rust-anything/last-diff.json`, with the first mismatches only, as `diff` prints it.
fn keep_last(crate_dir: &Path, outcome: &mut DiffOutcome, port: String) {
    let stamp = crate::state::Stamp::of(port, "diff");
    outcome.schema = Some(stamp.schema);
    outcome.at = Some(stamp.at);
    outcome.port = Some(stamp.port);
    if let Ok(mut saved) = serde_json::to_value(&*outcome) {
        if let Some(m) = saved["mismatches"].as_array_mut() {
            m.truncate(SHOWN_MISMATCHES);
        }
        if let Some(batches) = saved.get_mut("batches").and_then(Value::as_array_mut) {
            for b in batches {
                if let Some(m) = b.get_mut("mismatches").and_then(Value::as_array_mut) {
                    m.truncate(SHOWN_MISMATCHES);
                }
            }
        }
        crate::state::save(crate_dir, crate::state::LAST_DIFF, &saved);
    }
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

pub struct RecordOptions<'a> {
    pub crate_dir: &'a Path,
    /// Generated cases per function.
    pub count: usize,
    /// Extra cases, one `{"fn": name, "args": [...]}` JSON object per line, with `"kwargs": {...}`
    /// for Python and Ruby arguments passed by keyword.
    pub inputs: Option<&'a Path>,
    /// Import the original from this JS module instead of the TS source files.
    pub module: Option<&'a Path>,
    /// Resolve npm packages the original imports from this folder's `node_modules`.
    pub resolve_from: Option<&'a Path>,
    pub node_args: &'a [String],
    /// Run the original with no network, its repository read-only and a CPU limit and, on Linux only, a memory limit
    /// ([`crate::process::Sandbox`]).
    pub sandbox: bool,
}

/// The dataclasses a Python file can take: its own and its package's, so a type imported from
/// a sibling module (`from .models import Limits`) is found too.
fn python_types(root: &Path, file: &str) -> Vec<LocalType> {
    let dir = root.join(file).parent().map(Path::to_path_buf);
    let mut files = vec![root.join(file)];
    if let Some(dir) = dir
        && let Ok(entries) = std::fs::read_dir(dir)
    {
        let mut siblings: Vec<PathBuf> = entries
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|e| e == "py") && !files.contains(p))
            .collect();
        siblings.sort();
        files.extend(siblings);
    }
    files
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .flat_map(|text| crate::lang::python::dataclass_types(&text))
        .collect()
}

/// Generates the cases a recording runs, shared by the host and on-device drivers.
fn generate_cases(opts: &RecordOptions, manifest: &Manifest) -> Result<Generated> {
    generate_cases_salted(opts, manifest, 0, &[])
}

pub(crate) struct Generated {
    pub cases: Vec<Value>,
    pub traps: usize,
    pub regex_functions: Vec<String>,
    pub nested: usize,
    pub decoded: Vec<String>,
}

/// [`generate_cases`] with the generator's seeds mixed with `salt`. A non-zero salt gives fresh
/// inputs (`fuzz`): no traps and no `--inputs`, which the recording already has.
pub(crate) fn generate_cases_salted(
    opts: &RecordOptions,
    manifest: &Manifest,
    salt: u64,
    seeds: &[Value],
) -> Result<Generated> {
    let mut cases: Vec<Value> = Vec::new();
    let mut inputs: Vec<Value> = Vec::new();
    let module_for = |file: &str| module_path(opts, manifest, file);
    let mut scopes: BTreeMap<String, Vec<LocalType>> = BTreeMap::new();
    let mut regex_files: BTreeMap<String, bool> = BTreeMap::new();
    let mut regex_functions = Vec::new();
    let mut decoded_files: BTreeMap<String, Vec<crate::ts::scan::Decoded>> = BTreeMap::new();
    let mut decoded = Vec::new();
    let mut traps = 0;
    for f in &manifest.exports {
        let module = module_for(&f.file)?;
        if !scopes.contains_key(&f.file) {
            let text = std::fs::read_to_string(manifest.root.join(&f.file)).unwrap_or_default();
            regex_files.insert(
                f.file.clone(),
                crate::risks::uses_regex(manifest.language, &text),
            );
            if manifest.language == crate::lang::Lang::Ts {
                let code = crate::ts::script_of(&f.file, &text);
                decoded_files.insert(
                    f.file.clone(),
                    crate::ts::scan::scan(&f.file, &code).decoded,
                );
            }
            let types = if manifest.language == crate::lang::Lang::Python {
                python_types(&manifest.root, &f.file)
            } else {
                crate::bridge::types_in_scope(&manifest.root, &f.file, &text)
            };
            scopes.insert(f.file.clone(), types);
        }
        let regex = regex_files[&f.file];
        if regex && f.params.iter().any(|p| param_type(p) == RType::Str) {
            regex_functions.push(f.name.clone());
        }
        let params: Vec<String> = decoded_files
            .get(&f.file)
            .into_iter()
            .flatten()
            .filter(|d| d.function == f.name)
            .map(|d| format!("`{}`", d.param))
            .collect();
        if !params.is_empty() {
            decoded.push(format!("{} ({})", f.name, params.join(", ")));
        }
        let types = &scopes[&f.file];
        let mut all = generate_salted(f, opts.count, types, salt);
        let mut seen: std::collections::HashSet<String> = all
            .iter()
            .map(|a| serde_json::to_string(a).unwrap_or_default())
            .collect();
        let base: Vec<Value> = all
            .first()
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        for args in trap_args(&f.params, &base, regex)
            .into_iter()
            .filter(|_| salt == 0)
        {
            let args = Value::Array(args);
            if seen.insert(serde_json::to_string(&args).unwrap_or_default()) {
                all.push(args);
                traps += 1;
            }
        }
        for (i, mut args) in all.into_iter().enumerate() {
            // Python callers pass ints where floats are expected, and int-ness can leak into
            // results: every fourth case passes integral `number` arguments as ints.
            if manifest.language == crate::lang::Lang::Python && i % 4 == 3 {
                intify(&f.params, &mut args);
            }
            let mut case = json!({ "fn": f.name, "module": module, "args": args });
            split_keyword_only(&f.params, &mut case);
            cases.push(case);
        }
    }
    for class in &manifest.classes {
        let module = module_for(&class.file)?;
        let text = std::fs::read_to_string(manifest.root.join(&class.file)).unwrap_or_default();
        let types = crate::bridge::types_in_scope(&manifest.root, &class.file, &text);
        for mut scenario in scenarios_salted(class, opts.count.max(20), &types, salt) {
            scenario["module"] = Value::String(module.clone());
            cases.push(scenario);
        }
    }
    if let Some(path) = opts.inputs.filter(|_| salt == 0) {
        let text =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        for case in parse_inputs(opts, manifest, &text, |n| format!("{}:{n}", path.display()))? {
            if case.get("class").is_none() {
                inputs.push(case.clone());
            }
            cases.push(case);
        }
    }
    let local = crate::pin::supported(manifest)
        && crate::pin::load(opts.crate_dir).ok().flatten().is_some();
    let seeds = if salt == 0 { &inputs[..] } else { seeds };
    let mut nested = 0;
    for mut case in crate::nested::cases(seeds, opts.count, salt, local) {
        let Some(f) = manifest
            .exports
            .iter()
            .find(|f| case["fn"].as_str() == Some(f.name.as_str()))
        else {
            continue;
        };
        case["module"] = Value::String(module_for(&f.file)?);
        cases.push(case);
        nested += 1;
    }

    Ok(Generated {
        cases,
        traps,
        regex_functions,
        nested,
        decoded,
    })
}

/// The module a case of `file` is imported from: `--module` when given, else the file in the
/// original's repository.
fn module_path(opts: &RecordOptions, manifest: &Manifest, file: &str) -> Result<String> {
    let path = match opts.module {
        Some(m) => m
            .canonical()
            .with_context(|| format!("resolving {}", m.display()))?,
        None => manifest.root.join(file),
    };
    Ok(path.to_string_lossy().into_owned())
}

/// Cases from lines in the `record --inputs` format (`{"fn": .., "args": [..]}`, `kwargs`, and
/// `class` lines), each checked against the unit and given its module. `at(n)` names line `n`
/// (from 1) in errors. `fuzz --generator` reads its command's output with this too.
pub(crate) fn parse_inputs(
    opts: &RecordOptions,
    manifest: &Manifest,
    text: &str,
    at: impl Fn(usize) -> String,
) -> Result<Vec<Value>> {
    let module_for = |file: &str| module_path(opts, manifest, file);
    let mut cases = Vec::new();
    for (i, line) in crate::lang::without_bom(text)
        .lines()
        .enumerate()
        .filter(|(_, l)| !l.trim().is_empty())
    {
        let mut case: Value = parse_deep(line).with_context(|| {
            format!(
                "{} (values use the record codec: {{\"$undefined\": true}}, {{\"$num\": \"NaN\"}}, \
                 {{\"$utf16\": [code units]}} for strings with lone surrogates, and in Python \
                 {{\"$codepoints\": [code points]}} for those where a high surrogate comes right \
                 before a low one)",
                at(i + 1)
            )
        })?;
        if let Some(class) = case["class"].as_str() {
            let Some(c) = manifest.classes.iter().find(|c| c.name == class) else {
                bail!("{}: {}", at(i + 1), unknown_class(manifest, class));
            };
            // The drivers read `ctor` and `calls` as arrays; a line without them would record
            // the driver's own error as if the original had thrown it.
            if !case["ctor"].is_array() {
                bail!(
                    "{}: \"ctor\" must be an array of constructor arguments",
                    at(i + 1)
                );
            }
            let Some(calls) = case["calls"].as_array() else {
                bail!(
                    "{}: \"calls\" must be an array of {{\"method\": name, \"args\": [..]}} calls",
                    at(i + 1)
                );
            };
            for (n, call) in calls.iter().enumerate() {
                let named = call["method"].as_str().is_some_and(|m| !m.is_empty());
                if !named || !call["args"].is_array() {
                    bail!(
                        "{}: \"calls\"[{n}] must be {{\"method\": name, \"args\": [..]}}",
                        at(i + 1)
                    );
                }
            }
            case["module"] = Value::String(module_for(&c.file)?);
            cases.push(case);
            continue;
        }
        let Some(name) = case["fn"].as_str().filter(|s| !s.is_empty()) else {
            bail!("{}: \"fn\" is missing", at(i + 1));
        };
        let Some(f) = manifest.exports.iter().find(|f| f.name == name) else {
            bail!("{}: {}", at(i + 1), unknown_function(manifest, name));
        };
        if !case["args"].is_array() {
            bail!("{}: \"args\" must be an array of arguments", at(i + 1));
        }
        let has_kwargs = match &case["kwargs"] {
            Value::Null => false,
            Value::Object(m) => !m.is_empty(),
            _ => true,
        };
        if has_kwargs
            && !matches!(
                manifest.language,
                crate::lang::Lang::Python | crate::lang::Lang::Ruby
            )
        {
            bail!(
                "{}: \"kwargs\" is only for Python and Ruby, and this unit is {}: pass these arguments in \"args\"",
                at(i + 1),
                manifest.language.name()
            );
        }
        if !matches!(&case["kwargs"], Value::Null | Value::Object(_)) {
            bail!(
                "{}: \"kwargs\" must be an object of argument names to values",
                at(i + 1)
            );
        }
        if matches!(case.get("kwargs"), Some(Value::Null))
            && let Some(obj) = case.as_object_mut()
        {
            obj.remove("kwargs");
        }
        case["module"] = Value::String(module_for(&f.file)?);
        cases.push(case);
    }
    Ok(cases)
}

/// `--module` names a JS module the original is imported from, so only a TS/JS crate can
/// take it; any other language would hand the path to its own driver as an import name.
fn check_module(module: Option<&Path>, manifest: &Manifest) -> Result<()> {
    if module.is_some() {
        anyhow::ensure!(
            manifest.language == crate::lang::Lang::Ts,
            "--module is for TS/JS crates, and this crate is {}",
            manifest.language.name()
        );
    }
    Ok(())
}

/// `--count 0` with no `--inputs` (or `--from-tests`) would record nothing and replace
/// `cases.jsonl` with an empty file, so it is refused before anything is touched.
fn check_count(opts: &RecordOptions) -> Result<()> {
    if opts.count == 0 && opts.inputs.is_none() {
        bail!(
            "`--count 0` records nothing: pass --count 1 or more, or give cases with --inputs or \
             --from-tests"
        );
    }
    Ok(())
}

/// Parts of an environment variable's name that say its value is a secret.
const SECRET_NAME_PARTS: [&str; 8] = [
    "SECRET",
    "TOKEN",
    "PASSWORD",
    "PASSWD",
    "PASSPHRASE",
    "CREDENTIAL",
    "API_KEY",
    "PRIVATE_KEY",
];
/// A shorter value is too likely to be an ordinary word to say it was recorded by accident.
const MIN_SECRET_CHARS: usize = 8;

/// Whether `line` of the recording holds `value`: in one of its decoded strings (a driver may
/// escape `<` as `\u003c`, and the escape differs between languages), or, for a line that is
/// not JSON, as written.
fn line_holds(line: &str, value: &str) -> bool {
    fn in_strings(json: &Value, value: &str) -> bool {
        match json {
            Value::String(text) => text.contains(value),
            Value::Array(items) => items.iter().any(|item| in_strings(item, value)),
            Value::Object(fields) => fields
                .iter()
                .any(|(key, item)| key.contains(value) || in_strings(item, value)),
            _ => false,
        }
    }
    match serde_json::from_str::<Value>(line) {
        Ok(json) => in_strings(&json, value),
        Err(_) => line.contains(value),
    }
}

/// The environment variables with a secret-looking name whose value appears in the recorded
/// `cases`, each with the functions whose cases hold it. Only names come back, never values.
pub(crate) fn recorded_secrets(
    cases: &str,
    environment: impl IntoIterator<Item = (String, String)>,
) -> Vec<(String, Vec<String>)> {
    let mut found = Vec::new();
    for (name, value) in environment {
        let upper = name.to_uppercase();
        if value.chars().count() < MIN_SECRET_CHARS
            || !SECRET_NAME_PARTS.iter().any(|part| upper.contains(part))
        {
            continue;
        }
        let mut functions: Vec<String> = Vec::new();
        for line in cases.lines().filter(|line| line_holds(line, &value)) {
            let function = serde_json::from_str::<Value>(line)
                .ok()
                .and_then(|case| {
                    case["fn"]
                        .as_str()
                        .or_else(|| case["class"].as_str())
                        .map(str::to_string)
                })
                .unwrap_or_else(|| "?".to_string());
            if !functions.contains(&function) {
                functions.push(function);
            }
        }
        if !functions.is_empty() {
            found.push((name, functions));
        }
    }
    found.sort();
    found
}

/// Environment variables whose name and value are valid Unicode.
pub(crate) fn unicode_env() -> impl Iterator<Item = (String, String)> {
    std::env::vars_os()
        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
}

/// Takes the recording away: removed, or, when the folder does not let it be removed, emptied.
/// Returns what was done.
fn discard_recording(path: &Path) -> std::io::Result<&'static str> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok("removed"),
        Err(_) => std::fs::write(path, b"").map(|()| "emptied"),
    }
}

/// Fails when `cases.jsonl` holds the value of a secret-looking environment variable: the file
/// is meant to be committed. The recording that was there before (`previous`) is put back when it
/// holds none; else the new one is removed. Variables whose name or value is not valid Unicode
/// cannot be searched for as text and are skipped.
fn refuse_recorded_secrets(
    cases_path: &Path,
    previous: Option<Vec<u8>>,
    environment: impl IntoIterator<Item = (String, String)>,
) -> Result<()> {
    let Ok(cases) = std::fs::read_to_string(cases_path) else {
        return Ok(());
    };
    let environment: Vec<(String, String)> = environment.into_iter().collect();
    let found = recorded_secrets(&cases, environment.iter().cloned());
    if found.is_empty() {
        return Ok(());
    }
    let clean_previous = previous.filter(|bytes| {
        recorded_secrets(&String::from_utf8_lossy(bytes), environment.iter().cloned()).is_empty()
    });
    let done = match clean_previous {
        Some(bytes) if std::fs::write(cases_path, &bytes).is_ok() => {
            "removed, and the previous recording put back"
        }
        _ => discard_recording(cases_path).with_context(|| {
            format!(
                "the recording holds an environment secret and {} could be neither removed nor emptied: delete it by hand",
                cases_path.display()
            )
        })?,
    };
    let listed: Vec<String> = found
        .iter()
        .map(|(name, functions)| format!("{name} (in {})", functions.join(", ")))
        .collect();
    bail!(
        "the recording held the value of {}, and {} is meant to be committed: it was {done}. \
         Record without those variables (`env -u NAME rust-anything record ...`), or change \
         the functions or inputs that return them",
        listed.join("; "),
        CASES,
        done = done
    )
}

pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
    record_allowing_dropped(opts, 0)
}

/// [`record`] that may leave out up to `allowed` generated inputs it could not record
/// (`--allow-dropped N`); `RUST_ANYTHING_ALLOW_DROPPED` raises it. With 0 a recording that lost
/// an input fails and the previous one is kept.
pub fn record_allowing_dropped(opts: &RecordOptions, allowed: usize) -> Result<RecordOutcome> {
    check_count(opts)?;
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let _lock = crate::fuzz::RecordingLock::take_recovered(&crate_dir)?;
    let opts = &RecordOptions {
        crate_dir: &crate_dir,
        ..*opts
    };
    let manifest = Manifest::load(opts.crate_dir)?;
    check_module(opts.module, &manifest)?;
    let fingerprint = crate::recording::fingerprint(&manifest);
    let Generated {
        cases,
        traps,
        regex_functions,
        nested,
        decoded,
    } = generate_cases(opts, &manifest)?;
    check_original(opts.module, &manifest)?;

    let timed_out_path = opts.crate_dir.join(WORK_DIR).join(TIMED_OUT);
    let _ = std::fs::remove_file(&timed_out_path);
    let coverage_dir = opts.crate_dir.join(WORK_DIR).join(COVERAGE_DIR);
    let _ = std::fs::remove_dir_all(&coverage_dir);
    let dropped_path = opts.crate_dir.join(WORK_DIR).join(DROPPED);
    let _ = std::fs::remove_file(&dropped_path);
    // The drivers write `cases.jsonl` as they go; the recording that was there is put back unless
    // this run turns out complete.
    let previous = std::fs::read(opts.crate_dir.join(CASES)).ok();
    let out = record_with(opts, &manifest, &cases)?;
    let (generated, counted) = match drops(opts.crate_dir, &out, cases.len()) {
        Ok(found) => found,
        Err(error) => {
            restore_recording(&out, previous);
            return Err(error);
        }
    };
    let (inapplicable, dropped): (Vec<DroppedCase>, Vec<DroppedCase>) =
        counted.into_iter().partition(|d| d.kind == INAPPLICABLE);
    if dropped.len() > allow_dropped(allowed) {
        restore_recording(&out, previous);
        bail!("{}", dropped_message(generated, &dropped));
    }
    if !dropped.is_empty() {
        eprintln!("{}", dropped_message(generated, &dropped));
    }
    if !inapplicable.is_empty() {
        eprintln!(
            "{} of {generated} generated inputs do not fit the original's parameter types, so it \
             cannot be called with them: they are not in the recording",
            inapplicable.len()
        );
    }
    refuse_recorded_secrets(&out, previous, unicode_env())?;
    let coverage = if manifest.language == crate::lang::Lang::Python {
        crate::recording::python_coverage(&coverage_dir, &manifest)
    } else {
        crate::recording::node_coverage(&coverage_dir, &manifest)
    };
    if let Some(fingerprint) = &fingerprint {
        crate::recording::save_recorded_from(
            opts.crate_dir,
            &manifest,
            fingerprint,
            coverage.as_ref(),
            serde_json::json!({
                "generated": generated,
                "dropped": dropped.len(),
                "inapplicable": inapplicable.len(),
            }),
        )?;
    }
    let mut outcome = summarize(opts, &out, traps, regex_functions, coverage)?;
    outcome.nested = nested;
    outcome.decoded = decoded;
    outcome.pinned = crate::pin::load(opts.crate_dir)?.filter(|_| crate::pin::supported(&manifest));
    outcome.generated = generated;
    outcome.dropped = dropped;
    outcome.inapplicable = inapplicable.len();
    Ok(outcome)
}

/// Refuses a recording with no original to run: the unit is not where the manifest says (a
/// repository cloned or moved since `bridge`), and a driver would record its failure to load it.
fn check_original(module: Option<&Path>, manifest: &Manifest) -> Result<()> {
    let unit = manifest.root.join(&manifest.unit);
    if module.is_none() && matches!(unit.try_exists(), Ok(false)) {
        bail!(
            "the original {} is not at {}: there is nothing to record. If the repository moved \
             or was cloned since `bridge`, run `rust-anything bridge` again from where it is now",
            manifest.unit,
            unit.display()
        );
    }
    Ok(())
}

fn allow_dropped(allowed: usize) -> usize {
    let env = std::env::var("RUST_ANYTHING_ALLOW_DROPPED")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(0);
    allowed.max(env)
}

/// What the drivers left out of the recording: what they counted themselves, or, when a path
/// counted nothing, the inputs that are missing from `cases.jsonl` without a timeout.
fn drops(crate_dir: &Path, recorded: &Path, asked: usize) -> Result<(usize, Vec<DroppedCase>)> {
    let work = crate_dir.join(WORK_DIR);
    if let Some(counted) = read_dropped(&work) {
        return Ok(counted);
    }
    let lines = std::fs::read_to_string(recorded)
        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
        .unwrap_or(0);
    let timed_out = std::fs::read_to_string(work.join(TIMED_OUT))
        .ok()
        .and_then(|t| serde_json::from_str::<Vec<Value>>(&t).ok())
        .map_or(0, |t| t.len());
    let missing = asked.saturating_sub(lines + timed_out);
    let unknown = DroppedCase {
        kind: NOT_ENCODED.to_string(),
        function: "?".to_string(),
        input: String::new(),
    };
    Ok((asked, vec![unknown; missing]))
}

fn restore_recording(path: &Path, previous: Option<Vec<u8>>) {
    let _ = match previous {
        Some(bytes) => std::fs::write(path, bytes),
        None => std::fs::remove_file(path),
    };
}

fn dropped_message(generated: usize, dropped: &[DroppedCase]) -> String {
    let mut text = format!(
        "{} of {generated} generated inputs are not in the recording, so no port is ever checked          against them:",
        dropped.len()
    );
    for d in dropped.iter().take(20) {
        let _ = write!(text, "\n  - {} (input {}): {}", d.function, d.input, d.kind);
    }
    if dropped.len() > 20 {
        let _ = write!(text, "\n  ... and {} more", dropped.len() - 20);
    }
    text.push_str(
        "\nChange the original or the inputs so each one records. To accept the loss, run \
         `record --allow-dropped N` (N = the number of inputs above). The previous cases.jsonl \
         was kept.",
    );
    text
}

/// Runs `cases` through the original with the language's driver and writes `cases.jsonl`.
pub(crate) fn record_with(
    opts: &RecordOptions,
    manifest: &Manifest,
    cases: &[Value],
) -> Result<PathBuf> {
    let sandbox = opts.sandbox.then_some(manifest.root.as_path());
    Ok(if manifest.language == crate::lang::Lang::Python {
        crate::harness_py::record(opts.crate_dir, cases, sandbox)?
    } else if manifest.kind == Kind::CAbi {
        crate::harness_c::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Go {
        crate::harness_go::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Ruby {
        crate::harness_ruby::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Php {
        crate::harness_php::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Csharp {
        crate::harness_csharp::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Powershell {
        crate::harness_powershell::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Swift {
        crate::harness_swift::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Java {
        crate::harness_java::record(opts.crate_dir, manifest, cases, sandbox)?
    } else if manifest.language == crate::lang::Lang::Kotlin {
        crate::harness_kotlin::record(opts.crate_dir, manifest, cases, sandbox)?
    } else {
        record_node(opts, manifest, cases, sandbox)?
    })
}

/// Records on a connected Android device: the cases are generated here, the original Kotlin
/// runs under ART, and the results come back as the same `cases.jsonl`.
pub fn record_android(opts: &RecordOptions, device: Option<&str>) -> Result<RecordOutcome> {
    anyhow::ensure!(
        !opts.sandbox,
        "`--sandbox` runs the original on this machine; it does not apply to `--profile android`"
    );
    check_count(opts)?;
    let _lock = crate::fuzz::RecordingLock::take_recovered(opts.crate_dir)?;
    let manifest = Manifest::load(opts.crate_dir)?;
    check_module(opts.module, &manifest)?;
    let fingerprint = crate::recording::fingerprint(&manifest);
    let Generated {
        cases,
        traps,
        regex_functions,
        nested,
        decoded,
    } = generate_cases(opts, &manifest)?;
    let _ = std::fs::remove_file(opts.crate_dir.join(WORK_DIR).join(TIMED_OUT));
    let out = crate::android_device::record(opts.crate_dir, &manifest, &cases, device)?;
    if let Some(fingerprint) = &fingerprint {
        crate::recording::save_recorded_from(
            opts.crate_dir,
            &manifest,
            fingerprint,
            None,
            serde_json::json!({}),
        )?;
    }
    let mut outcome = summarize(opts, &out, traps, regex_functions, None)?;
    outcome.nested = nested;
    outcome.decoded = decoded;
    Ok(outcome)
}

fn summarize(
    opts: &RecordOptions,
    out: &Path,
    traps: usize,
    regex_functions: Vec<String>,
    coverage: Option<Value>,
) -> Result<RecordOutcome> {
    let text = std::fs::read_to_string(out)?;
    let mut per_function = BTreeMap::new();
    let mut errors = 0;
    let mut count = 0;
    for line in text.lines().filter(|l| !l.is_empty()) {
        let case: Value = parse_deep(line)?;
        count += 1;
        let class_error = case["results"]
            .as_array()
            .is_some_and(|r| r.iter().any(|x| x.get("error").is_some()));
        errors +=
            usize::from(case.get("error").is_some() || case.get("panic").is_some() || class_error);
        let name = case["fn"]
            .as_str()
            .or_else(|| case["class"].as_str())
            .unwrap_or_default();
        *per_function.entry(name.to_string()).or_default() += 1;
    }
    let timed_out_path = opts.crate_dir.join(WORK_DIR).join(TIMED_OUT);
    let timed_out: Vec<Value> = std::fs::read_to_string(&timed_out_path)
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_default();
    Ok(RecordOutcome {
        path: out.to_path_buf(),
        cases: count,
        errors,
        traps,
        nested: 0,
        per_function,
        regex_functions,
        decoded: Vec::new(),
        timed_out: timed_out
            .iter()
            .map(|c| serde_json::json!({ "fn": c["fn"].clone(), "args": c["args"].clone() }))
            .collect(),
        coverage,
        pinned: None,
        generated: 0,
        dropped: Vec::new(),
        inapplicable: 0,
    })
}

/// Runs the recorded inputs through Node: the original TS/JS, with the resolve hook.
fn record_node(
    opts: &RecordOptions,
    manifest: &Manifest,
    cases: &[Value],
    sandbox: Option<&Path>,
) -> Result<PathBuf> {
    let work = opts.crate_dir.join(WORK_DIR);
    std::fs::create_dir_all(&work)?;
    let script = work.join("record.mjs");
    std::fs::write(
        &script,
        format!(
            "{CODEC_JS}\n{ERROR_JS}\n{POST_JS}\n{}\n{RECORD_JS}",
            crate::pin::PIN_JS
        ),
    )?;
    let out = opts.crate_dir.join(CASES);
    // TS sources often import the way bundlers resolve (`./errors`, `./types`): a resolve hook
    // lets Node follow them, so the original runs as it is.
    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
    let register = work.canonical()?.join("register.mjs");
    let mut node_args: Vec<String> = strip_types_args().iter().map(|a| a.to_string()).collect();
    node_args.push(format!("--import={}", file_url(&register)));
    node_args.extend(opts.node_args.iter().cloned());
    let aliases = alias_env(manifest);
    let resolve_from = opts
        .resolve_from
        .map(|dir| {
            dir.canonical()
                .with_context(|| format!("resolving {}", dir.display()))
        })
        .transpose()?;
    let record = |transform: bool| {
        record_cases(cases, &work, &out, "node", sandbox, |inputs, part| {
            let mut cmd = Command::new("node");
            if transform {
                // Enums and parameter properties need Node to transform TS, not only strip types.
                cmd.args(transform_flag())
                    .arg("--no-warnings=ExperimentalWarning");
            }
            cmd.args(&node_args)
                .arg(&script)
                .arg(inputs)
                .arg(part)
                .env("NODE_V8_COVERAGE", work.join(COVERAGE_DIR))
                .env("RUST_ANYTHING_PATHS", &aliases)
                .env("RUST_ANYTHING_WORKSPACE", workspace_env(manifest));
            if let Some(dir) = &resolve_from {
                cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
            }
            crate::pin::apply(&mut cmd, opts.crate_dir)?;
            crate::enable::original_only(&mut cmd, &Manifest::load(opts.crate_dir)?);
            Ok(cmd)
        })
    };
    if let Err(error) = record(false) {
        if !format!("{error:#}").contains("ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
            return Err(error);
        }
        record(true)?;
    }
    Ok(out)
}

/// The flags Node needs to load `.ts` sources: none from 22.18 and 23.6, which strip types by
/// default, but `--experimental-strip-types` on 22.6 to 22.17 and 23.0 to 23.5.
fn strip_types_args() -> &'static [&'static str] {
    static NEEDED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let needed = *NEEDED.get_or_init(|| {
        let mut cmd = Command::new("node");
        cmd.arg("--version");
        crate::process::output(&mut cmd, crate::process::QUICK)
            .ok()
            .and_then(|out| crate::doctor::parse_version(&String::from_utf8_lossy(&out.stdout)))
            .is_some_and(needs_strip_types_flag)
    });
    if needed {
        &[
            "--experimental-strip-types",
            "--no-warnings=ExperimentalWarning",
        ]
    } else {
        &[]
    }
}

fn needs_strip_types_flag(node: crate::doctor::Version) -> bool {
    let crate::doctor::Version(major, minor, _) = node;
    (major == 22 && (6..18).contains(&minor)) || (major == 23 && minor < 6)
}

fn transform_flag() -> Option<&'static str> {
    static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let supported = *SUPPORTED.get_or_init(|| {
        let mut cmd = Command::new("node");
        cmd.args(["--experimental-transform-types", "--no-warnings", "-e", "0"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null());
        crate::process::status(&mut cmd, crate::process::QUICK).is_ok_and(|s| s.success())
    });
    supported.then_some("--experimental-transform-types")
}

/// Copies a freshly built library into place by renaming, so a process that has the old one
/// loaded keeps a valid file.
///
/// The installed file is dated now, whatever the file it came from was: a copy that keeps its
/// source's time (a clone on macOS) would look older than a port written after the library it
/// came from was built, and `stale_build` would refuse a build that is current.
pub(crate) fn install(built: &Path, dest: &Path) -> Result<()> {
    copy_dated(built, dest, std::time::SystemTime::now())
}

/// [`install`] dated when the build of `crate_dir` that made `built` began (`started`), or when
/// cargo wrote its `Cargo.lock` if that came later: a source saved while cargo compiled is then
/// newer than the library, and `stale_build` refuses the library instead of testing the version
/// before the edit.
pub(crate) fn install_dated(
    built: &Path,
    dest: &Path,
    crate_dir: &Path,
    started: std::time::SystemTime,
) -> Result<()> {
    let locked = std::fs::metadata(crate_dir.join("Cargo.lock")).and_then(|m| m.modified());
    let dated = match locked {
        Ok(at) if at > started => at,
        _ => started,
    };
    copy_dated(built, dest, dated)
}

fn copy_dated(built: &Path, dest: &Path, at: std::time::SystemTime) -> Result<()> {
    let tmp = dest.with_extension(format!("tmp-{}", std::process::id()));
    std::fs::copy(built, &tmp).with_context(|| format!("copying {}", built.display()))?;
    if let Ok(copy) = std::fs::File::options().write(true).open(&tmp) {
        let _ = copy.set_modified(at);
    }
    std::fs::rename(&tmp, dest).with_context(|| format!("installing {}", dest.display()))
}

/// Confirms the port's native library exists before running diff, bench or fuzz against it.
pub(crate) fn ensure_built(crate_dir: &Path, manifest: &Manifest) -> Result<()> {
    match manifest.kind {
        Kind::Napi => {
            let node_file = crate_dir.join(format!("{}.node", manifest.lib_name()));
            if !node_file.exists() {
                bail!(
                    "no built library in {} (run `rust-anything build {}` first)",
                    crate_dir.display(),
                    crate::app::cli_path(crate_dir)
                );
            }
        }
        Kind::Wasm => {
            let pkg = crate_dir.join("pkg");
            let js = pkg.join(format!("{}.js", manifest.lib_name()));
            if !pkg.is_dir() || !js.exists() {
                bail!(
                    "no built library in {} (run `rust-anything build {}` first)",
                    pkg.display(),
                    crate::app::cli_path(crate_dir)
                );
            }
        }
        Kind::Pyo3 => {
            let native = crate::harness_py::native_file(crate_dir, manifest);
            if !native.exists() {
                let dir = native.parent().unwrap_or(crate_dir);
                bail!(
                    "no built library in {} (run `rust-anything build {}` first)",
                    dir.display(),
                    crate::app::cli_path(crate_dir)
                );
            }
        }
        Kind::CAbi => {
            crate::harness_c::built_library(crate_dir, manifest)?;
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Go => {
            crate::harness_c::built_library(crate_dir, manifest)?;
        }
        Kind::Ffi
            if manifest.language == crate::lang::Lang::Php
                && crate::harness_php::built_file(crate_dir, manifest).is_none() =>
        {
            bail!(
                "no built library in {} (run `rust-anything build {}` first)",
                crate_dir.join("php").display(),
                crate::app::cli_path(crate_dir)
            );
        }
        Kind::Ffi
            if manifest.language == crate::lang::Lang::Csharp
                && crate::harness_csharp::built_file(crate_dir, manifest).is_none() =>
        {
            bail!(
                "no built library in {} (run `rust-anything build {}` first)",
                crate_dir.join("cs").display(),
                crate::app::cli_path(crate_dir)
            );
        }
        Kind::Ffi
            if manifest.language == crate::lang::Lang::Powershell
                && crate::harness_powershell::built_file(crate_dir, manifest).is_none() =>
        {
            bail!(
                "no built library in {} (run `rust-anything build {}` first)",
                crate_dir.join("ps").display(),
                crate::app::cli_path(crate_dir)
            );
        }
        Kind::Ffi
            if manifest.language == crate::lang::Lang::Swift
                && crate::harness_swift::built_file(crate_dir, manifest).is_none() =>
        {
            bail!(
                "no built library in {} (run `rust-anything build {}` first)",
                crate_dir.join("swift").display(),
                crate::app::cli_path(crate_dir)
            );
        }
        _ => {}
    }
    Ok(())
}

/// The library `diff` loads, when it is older than the crate's sources: a forgotten `build`
/// would otherwise test the previous port.
fn stale_build(crate_dir: &Path, manifest: &Manifest) -> Option<PathBuf> {
    let built = match manifest.kind {
        Kind::Napi => crate_dir.join(format!("{}.node", manifest.lib_name())),
        Kind::Pyo3 => crate::harness_py::native_file(crate_dir, manifest),
        Kind::Ffi if manifest.language == crate::lang::Lang::Php => {
            crate::harness_php::built_file(crate_dir, manifest)?
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Csharp => {
            crate::harness_csharp::built_file(crate_dir, manifest)?
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Powershell => {
            crate::harness_powershell::built_file(crate_dir, manifest)?
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Swift => {
            crate::harness_swift::built_file(crate_dir, manifest)?
        }
        // The libraries Go, Java, Kotlin and C load from `target/release`, the Ruby extension
        // beside its wrapper, and the wasm module in `pkg/`.
        Kind::CAbi => crate::harness_c::built_library(crate_dir, manifest).ok()?,
        Kind::Ffi
            if matches!(
                manifest.language,
                crate::lang::Lang::Go | crate::lang::Lang::Java | crate::lang::Lang::Kotlin
            ) =>
        {
            crate::harness_c::built_library(crate_dir, manifest).ok()?
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Ruby => ["so", "bundle"]
            .iter()
            .map(|ext| crate_dir.join(format!("ruby/{}_native.{ext}", manifest.lib_name())))
            .find(|p| p.exists())?,
        Kind::Wasm => {
            let pkg = crate_dir.join("pkg");
            let wasm = pkg.join(format!("{}_bg.wasm", manifest.lib_name()));
            if wasm.exists() {
                wasm
            } else {
                pkg.join(format!("{}.js", manifest.lib_name()))
            }
        }
        _ => return None,
    };
    sources_newer_than(crate_dir, &built).then_some(built)
}

/// True when the crate's `Cargo.toml`, `Cargo.lock`, `build.rs` or any `.rs` file under `src/`,
/// or the same of a crate it depends on by `path` (a split port, the crates a front door wires
/// in), is newer than `built`.
///
/// A library dated on a whole second, as a file system that keeps only seconds dates it (drvfs
/// under WSL), is compared by whole seconds: the `Cargo.lock` its own build wrote a moment before
/// the link can carry a fraction of the same second and would otherwise always look newer.
pub(crate) fn sources_newer_than(crate_dir: &Path, built: &Path) -> bool {
    let Ok(built_at) = std::fs::metadata(built).and_then(|m| m.modified()) else {
        return false;
    };
    let since_epoch = |t: std::time::SystemTime| t.duration_since(std::time::UNIX_EPOCH).ok();
    let whole_seconds = since_epoch(built_at).is_some_and(|d| d.subsec_nanos() == 0);
    let mut sources = Vec::new();
    crate_sources(
        crate_dir,
        &mut std::collections::BTreeSet::new(),
        &mut sources,
    );
    sources
        .iter()
        .filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
        .any(
            |changed| match (whole_seconds, since_epoch(changed), since_epoch(built_at)) {
                (true, Some(changed), Some(built)) => changed.as_secs() > built.as_secs(),
                _ => changed > built_at,
            },
        )
}

/// The files a crate is built from: its manifest, lockfile, build script and sources, then those
/// of each path dependency.
fn crate_sources(
    dir: &Path,
    seen: &mut std::collections::BTreeSet<PathBuf>,
    out: &mut Vec<PathBuf>,
) {
    let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
    if !seen.insert(key) {
        return;
    }
    out.extend(["Cargo.toml", "Cargo.lock", "build.rs"].map(|f| dir.join(f)));
    out.extend(
        walkdir_rs(&dir.join("src"))
            .into_iter()
            .filter(|p| p.extension().is_some_and(|e| e == "rs")),
    );
    let Ok(manifest) = std::fs::read_to_string(dir.join("Cargo.toml")) else {
        return;
    };
    static PATH: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let path = PATH.get_or_init(|| regex::Regex::new(r#"\bpath\s*=\s*"([^"]+)""#).unwrap());
    for found in path.captures_iter(&manifest) {
        let dependency = dir.join(&found[1]);
        if dependency.join("Cargo.toml").is_file() {
            crate_sources(&dependency, seen, out);
        }
    }
}

fn walkdir_rs(dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            out.extend(walkdir_rs(&path));
        } else {
            out.push(path);
        }
    }
    out
}

/// Builds a JNI crate for Android: one library per ABI, installed into `jniLibs/`.
pub fn build_android(
    crate_dir: &Path,
    opts: &crate::android::Options,
) -> Result<crate::android::Report> {
    let manifest = Manifest::load(crate_dir)?;
    crate::android::build(crate_dir, &manifest, opts)
}

pub fn build(crate_dir: &Path) -> Result<PathBuf> {
    let manifest = Manifest::load(crate_dir)?;
    match manifest.kind {
        Kind::Pyo3 => crate::harness_py::build(crate_dir, &manifest),
        Kind::Ffi if manifest.language == crate::lang::Lang::Ruby => {
            crate::harness_ruby::build(crate_dir, &manifest)
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Php => {
            crate::harness_php::build(crate_dir, &manifest)
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Csharp => {
            crate::harness_csharp::build(crate_dir, &manifest)
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Powershell => {
            crate::harness_powershell::build(crate_dir, &manifest)
        }
        Kind::Ffi if manifest.language == crate::lang::Lang::Swift => {
            crate::harness_swift::build(crate_dir, &manifest)
        }
        Kind::CAbi | Kind::Ffi => crate::harness_c::build(crate_dir, &manifest),
        Kind::Napi => {
            let target = crate::cache::target_for(crate_dir)?;
            let started = std::time::SystemTime::now();
            run(
                Command::new("cargo")
                    .args(["build", "--release", "--manifest-path"])
                    .arg(crate_dir.join("Cargo.toml"))
                    .env("CARGO_TARGET_DIR", &target.dir),
                "cargo build",
            )
            .map_err(explain_libnode)?;
            let lib = manifest.lib_name();
            let release = target.dir.join("release");
            let built = [
                format!("lib{lib}.so"),
                format!("lib{lib}.dylib"),
                format!("{lib}.dll"),
            ]
            .iter()
            .map(|name| release.join(name))
            .find(|p| p.exists())
            .with_context(|| format!("no native library for `{lib}` in {}", release.display()))?;
            let artifact = crate_dir.join(format!("{lib}.node"));
            install_dated(&built, &artifact, crate_dir, started)?;
            Ok(artifact)
        }
        Kind::Wasm => {
            let target = crate::cache::target_for(crate_dir)?.dir;
            run(
                Command::new("cargo")
                    .args([
                        "build",
                        "--release",
                        "--target",
                        "wasm32-unknown-unknown",
                        "--manifest-path",
                    ])
                    .arg(crate_dir.join("Cargo.toml"))
                    .env("CARGO_TARGET_DIR", &target),
                "cargo build --target wasm32-unknown-unknown (needs `rustup target add wasm32-unknown-unknown`)",
            )?;
            // wasm-bindgen's CLI must match the crate's wasm-bindgen version exactly.
            let lock = std::fs::read_to_string(crate_dir.join("Cargo.lock")).unwrap_or_default();
            let wanted = locked_version(&lock, "wasm-bindgen")
                .context("wasm-bindgen missing from Cargo.lock")?;
            let installed = Command::new("wasm-bindgen")
                .arg("--version")
                .output()
                .ok()
                .map(|o| {
                    String::from_utf8_lossy(&o.stdout)
                        .trim()
                        .rsplit(' ')
                        .next()
                        .unwrap_or_default()
                        .to_string()
                });
            if installed.as_deref() != Some(wanted.as_str()) {
                bail!(
                    "the crate uses wasm-bindgen {wanted}; the CLI must match:\n  cargo install wasm-bindgen-cli --version {wanted} --locked{}",
                    installed
                        .map(|v| format!(" (found {v})"))
                        .unwrap_or_default()
                );
            }
            let lib = manifest.lib_name();
            let wasm = target
                .join("wasm32-unknown-unknown/release")
                .join(format!("{lib}.wasm"));
            run(
                Command::new("wasm-bindgen")
                    .args(["--target", "nodejs", "--out-dir"])
                    .arg(crate_dir.join("pkg"))
                    .arg(&wasm),
                "wasm-bindgen",
            )?;
            std::fs::write(
                crate_dir.join("pkg").join("package.json"),
                "{\n  \"type\": \"commonjs\"\n}\n",
            )?;
            Ok(crate_dir.join("pkg").join(format!("{lib}.js")))
        }
    }
}

/// Per-function timing of the original against the Rust module.
/// What `bench` concludes: the geometric-mean speedup and what to do.
#[derive(Debug, Serialize)]
pub struct Verdict {
    pub speedup: f64,
    pub faster: Vec<String>,
    pub slower: Vec<String>,
    pub advice: String,
    /// Functions whose recorded cases do not all match: timed, but not counted (#341).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub left_out: Vec<String>,
}

/// Faster means at least 1.1x, slower below 0.9x; between is a tie (timing noise). Functions
/// whose cases do not all match are left out: their time is the cost of failing (a panic caught
/// at the bridge), not of the work.
pub fn verdict(rows: &[BenchRow], lang: crate::lang::Lang, crate_dir: &std::path::Path) -> Verdict {
    let left_out: Vec<String> = rows
        .iter()
        .filter(|r| r.failing)
        .map(|r| r.name.clone())
        .collect();
    let rows: Vec<&BenchRow> = rows.iter().filter(|r| !r.failing).collect();
    let faster: Vec<String> = rows
        .iter()
        .filter(|r| r.speedup >= 1.1)
        .map(|r| r.name.clone())
        .collect();
    let slower: Vec<String> = rows
        .iter()
        .filter(|r| r.speedup < 0.9)
        .map(|r| r.name.clone())
        .collect();
    let speedup = if rows.is_empty() {
        1.0
    } else {
        (rows.iter().map(|r| r.speedup.max(1e-9).ln()).sum::<f64>() / rows.len() as f64).exp()
    };
    let q = crate::app::cli_path(crate_dir);
    let can_enable = matches!(lang, crate::lang::Lang::Ts | crate::lang::Lang::Python);
    let only_flags = faster
        .iter()
        .map(|name| format!("--only {name}"))
        .collect::<Vec<_>>()
        .join(" ");
    let advice = if rows.is_empty() && !left_out.is_empty() {
        format!(
            "Nothing to compare: no function matches all its recorded cases yet. Run `rust-anything diff {q}`."
        )
    } else if rows.is_empty() {
        "Nothing to compare: record cases that do not throw first.".to_string()
    } else if slower.is_empty() && faster.len() == rows.len() {
        "Ship it: every function is faster in Rust, call included.".to_string()
    } else if slower.is_empty() && rows.len() == 1 {
        "Ship it: the function is not slower in Rust; it ties.".to_string()
    } else if slower.is_empty() {
        "Ship it: no function is slower in Rust; some only tie.".to_string()
    } else if lang == crate::lang::Lang::C && slower.len() == 1 {
        // C links the port directly: there is no crossing to blame.
        format!(
            "No call overhead in C: {} is slower as Rust code. Profile and optimize it, or keep it in C.",
            slower[0]
        )
    } else if lang == crate::lang::Lang::C {
        format!(
            "No call overhead in C: these are slower as Rust code. Profile and optimize them, or keep them in C: {}.",
            slower.join(", ")
        )
    } else if speedup >= 1.1 && slower.len() == 1 {
        if can_enable {
            format!(
                "Ship the faster functions. Keep the slower one in the original (`rust-anything enable {q} {only_flags}`) or move its callers to Rust too: {}.",
                slower.join(", ")
            )
        } else {
            format!(
                "Ship the faster functions. Keep calling the original for the slower one or move its callers to Rust too: {}.",
                slower.join(", ")
            )
        }
    } else if speedup >= 1.1 {
        if can_enable {
            format!(
                "Ship the faster functions. Keep the slower ones in the original (`rust-anything enable {q} {only_flags}`) or move their callers to Rust too: {}.",
                slower.join(", ")
            )
        } else {
            format!(
                "Ship the faster functions. Keep calling the original for the slower ones or move their callers to Rust too: {}.",
                slower.join(", ")
            )
        }
    } else if rows.len() == 1 {
        "Do not ship this unit for speed: calling across costs more than the work this function does. \
         Port a bigger unit (this function together with its callers), so one call does more work."
            .to_string()
    } else {
        "Do not ship this unit for speed: calling across costs more than the work these functions do. \
         Port a bigger unit (these functions together with their callers), so one call does more work."
            .to_string()
    };
    Verdict {
        speedup,
        faster,
        slower,
        advice,
        left_out,
    }
}

/// "Nx faster" at or above parity, "Nx slower" below it.
pub fn speed_phrase(speedup: f64) -> String {
    if speedup >= 1.0 {
        // Same rule on the faster side: `1.04x` is not `1.0x`, which reads as no change at all.
        if speedup < 1.05 {
            format!("{speedup:.2}x faster")
        } else {
            format!("{speedup:.1}x faster")
        }
    } else {
        let slower = 1.0 / speedup.max(1e-9);
        // A port a few percent behind reads as "1.0x slower" at one decimal, which says it is not
        // slower at all: below 1.05 the difference gets a second decimal, as `bench` prints it.
        if slower < 1.05 {
            format!("{slower:.2}x slower")
        } else {
            format!("{slower:.1}x slower")
        }
    }
}

/// Rows from two `{ name: { cases, ns } }` timing maps: the original's and the port's.
pub fn bench_rows(
    m: &Manifest,
    original: &serde_json::Map<String, Value>,
    rust: &serde_json::Map<String, Value>,
) -> Vec<BenchRow> {
    m.exports
        .iter()
        .filter_map(|f| {
            let (old, new) = (original.get(&f.name)?, rust.get(&f.name)?);
            let (o, n) = (old["ns"].as_f64()?, new["ns"].as_f64()?);
            Some(BenchRow {
                name: f.name.clone(),
                cases: usize::try_from(old["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
                original_ns: o,
                rust_ns: n,
                speedup: o / n,
                failing: false,
            })
        })
        .collect()
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BenchRow {
    #[serde(rename = "fn")]
    pub name: String,
    pub cases: usize,
    /// Nanoseconds per call.
    pub original_ns: f64,
    pub rust_ns: f64,
    /// `original_ns / rust_ns`: above 1 means Rust is faster, bridge included.
    pub speedup: f64,
    /// Some recorded cases of this function do not match (or the port lacks it), so its time is
    /// not the port's and `verdict` leaves it out (#341).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub failing: bool,
}

pub struct BenchOptions<'a> {
    pub crate_dir: &'a Path,
    /// Minimum measured time per function and side, in milliseconds.
    pub min_ms: u64,
    pub resolve_from: Option<&'a Path>,
    pub node_args: &'a [String],
}

/// Times the recorded cases against the original and the built Rust module, bridge included,
/// and marks the functions whose recorded cases do not all match.
pub fn bench(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
    if opts.min_ms == 0 {
        bail!("`--min-ms` must be at least 1");
    }
    let _lock = crate::fuzz::RecordingLock::take_recovered(&std::path::absolute(opts.crate_dir)?)?;
    let resolve_from = opts
        .resolve_from
        .map(|dir| {
            dir.canonical()
                .with_context(|| format!("resolving {}", dir.display()))
        })
        .transpose()?;
    let opts = &BenchOptions {
        resolve_from: resolve_from.as_deref(),
        ..*opts
    };
    let mut rows = time_functions(opts)?;
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let diff = DiffOptions {
        crate_dir: &crate_dir,
        module: None,
        ignore_key_order: false,
        node_args: opts.node_args,
        float_tolerance: None,
    };
    let cases_path = crate_dir.join(CASES);
    let cases = std::fs::read_to_string(&cases_path)
        .with_context(|| format!("reading {}", cases_path.display()))?;
    // `diff_exact` and `settle`, not `diff_full`: a bench is not a change to the port, so it adds
    // nothing to the match trend.
    let outcome = settle(&diff, diff_exact(&diff)?)?;
    let counts = counts_from_cases_text(&cases, &outcome)?;
    for row in &mut rows {
        row.failing = failing(&row.name, &outcome, &counts);
    }
    Ok(rows)
}

fn failing(row: &str, outcome: &DiffOutcome, counts: &BTreeMap<String, (usize, usize)>) -> bool {
    let name = row.strip_prefix("class ").unwrap_or(row);
    outcome.missing.iter().any(|m| m == name)
        || counts
            .get(name)
            .is_some_and(|&(passed, total)| passed < total)
}

fn time_functions(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let opts = &BenchOptions {
        crate_dir: &crate_dir,
        ..*opts
    };
    let manifest = Manifest::load(opts.crate_dir)?;
    if manifest.language == crate::lang::Lang::Python {
        return crate::harness_py::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.kind == Kind::CAbi {
        return crate::harness_c::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Go {
        return crate::harness_go::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Ruby {
        return crate::harness_ruby::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Php {
        return crate::harness_php::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Csharp {
        return crate::harness_csharp::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Powershell {
        return crate::harness_powershell::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Swift {
        return crate::harness_swift::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Java {
        return crate::harness_java::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    if manifest.language == crate::lang::Lang::Kotlin {
        return crate::harness_kotlin::bench(opts.crate_dir, &manifest, opts.min_ms);
    }
    let cases = opts.crate_dir.join(CASES);
    if !cases.exists() {
        bail!(
            "no {CASES} in {} (run `rust-anything record` first)",
            opts.crate_dir.display()
        );
    }
    ensure_built(opts.crate_dir, &manifest)?;
    let modules: BTreeMap<String, String> = manifest
        .exports
        .iter()
        .map(|f| {
            (
                f.name.clone(),
                manifest.root.join(&f.file).to_string_lossy().into_owned(),
            )
        })
        .collect();
    let work = opts.crate_dir.join(WORK_DIR);
    std::fs::create_dir_all(&work)?;
    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
    let class_modules: BTreeMap<String, String> = manifest
        .classes
        .iter()
        .map(|c| {
            (
                c.name.clone(),
                manifest.root.join(&c.file).to_string_lossy().into_owned(),
            )
        })
        .collect();
    let async_functions: Vec<&str> = manifest
        .exports
        .iter()
        .filter(|f| f.is_async)
        .map(|f| f.name.as_str())
        .collect();
    let modules_path = work.join("bench-modules.json");
    std::fs::write(
        &modules_path,
        serde_json::to_string(&json!({
            "functions": modules,
            "classes": class_modules,
            "asyncFunctions": async_functions,
        }))?,
    )?;
    let script = work.join("bench.mjs");
    std::fs::write(&script, format!("{CODEC_JS}\n{BENCH_JS}"))?;
    let out = work.join("bench.json");
    // A run that ends early must not leave the previous timings to be read as its own.
    let _ = std::fs::remove_file(&out);
    let native = opts.crate_dir.join("index.cjs").canonical()?;
    let register = work.canonical()?.join("register.mjs");
    let mut cmd = Command::new("node");
    crate::enable::original_only(&mut cmd, &manifest);
    cmd.args(strip_types_args())
        .args(transform_flag())
        .arg("--no-warnings")
        .arg(format!("--import={}", file_url(&register)))
        .args(opts.node_args)
        .arg(&script)
        .arg(&modules_path)
        .arg(&native)
        .arg(&cases)
        .arg(&out)
        .arg(opts.min_ms.to_string())
        .env("RUST_ANYTHING_PATHS", alias_env(&manifest))
        .env("RUST_ANYTHING_WORKSPACE", workspace_env(&manifest));
    if let Some(dir) = opts.resolve_from {
        cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
    }
    run(&mut cmd, "node")?;
    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
}

pub struct DiffOptions<'a> {
    pub crate_dir: &'a Path,
    /// The module to test; defaults to the crate's `index.cjs`.
    pub module: Option<&'a Path>,
    /// Compare objects regardless of key order.
    pub ignore_key_order: bool,
    pub node_args: &'a [String],
    /// Floats match within this tolerance; the one saved by `record` when `None`.
    pub float_tolerance: Option<f64>,
}

/// Whether objects compare regardless of key order: the flag for this run, or the choice
/// `record --ignore-key-order` saved with the crate, which `gate`, `enable`, `report` and `go` read
/// because they have no flag of their own.
fn ignores_key_order(opts: &DiffOptions) -> bool {
    opts.ignore_key_order || Manifest::load(opts.crate_dir).is_ok_and(|m| m.ignore_key_order)
}

/// What a driver compares of a thrown error: `messages` when `record --messages` saved it, else
/// `classes`.
pub(crate) fn error_text(crate_dir: &Path) -> &'static str {
    if Manifest::load(crate_dir).is_ok_and(|m| m.messages) {
        "messages"
    } else {
        "classes"
    }
}

/// Passes [`error_text`] to a compiled driver as `RUST_ANYTHING_MESSAGES=1`, and clears a value
/// the caller's environment set.
pub(crate) fn pass_error_text(cmd: &mut Command, m: &Manifest) {
    if m.messages {
        cmd.env("RUST_ANYTHING_MESSAGES", "1");
    } else {
        cmd.env_remove("RUST_ANYTHING_MESSAGES");
    }
}

/// The first mismatches a diff reports.
const SHOWN_MISMATCHES: usize = 20;

pub fn diff(opts: &DiffOptions) -> Result<DiffOutcome> {
    let _lock = crate::fuzz::RecordingLock::take_recovered(&std::path::absolute(opts.crate_dir)?)?;
    let mut outcome = diff_full(opts)?;
    outcome.mismatches.truncate(SHOWN_MISMATCHES);
    for b in &mut outcome.batches {
        b.mismatches.truncate(SHOWN_MISMATCHES);
    }
    Ok(outcome)
}

/// Like `diff`, without truncating `mismatches`, so callers can inspect per-function results.
pub fn diff_full(opts: &DiffOptions) -> Result<DiffOutcome> {
    let port = crate::state::port_version(opts.crate_dir);
    let mut outcome = located(settle(opts, diff_exact(opts)?)?);
    anyhow::ensure!(
        outcome.total > 0,
        "no recorded cases to compare; run `rust-anything record` first"
    );
    if opts.module.is_none() {
        outcome.batches = crate::batch_check::run_or_report(
            opts.crate_dir,
            opts.float_tolerance,
            opts.ignore_key_order,
        );
        let batch_used: std::collections::HashSet<usize> = outcome
            .batches
            .iter()
            .flat_map(|b| b.used_known_diffs.iter().copied())
            .collect();
        if !batch_used.is_empty()
            && let Ok(known_entries) = crate::recording::known_diffs(opts.crate_dir)
        {
            for idx in batch_used {
                if let Some(e) = known_entries.get(idx) {
                    let needle = serde_json::json!({
                        "fn": e["fn"],
                        "args": e["args"],
                        "reason": e["reason"],
                    });
                    if let Some(pos) = outcome.stale_known.iter().position(|s| s == &needle) {
                        outcome.stale_known.remove(pos);
                    }
                }
            }
        }
        outcome.trend = crate::recording::track(opts.crate_dir, outcome.passed, outcome.total);
        keep_last(opts.crate_dir, &mut outcome, port);
    }
    Ok(outcome)
}

/// `(passed, total)` recorded cases per function name.
pub type FunctionCounts = BTreeMap<String, (usize, usize)>;

/// `(passed, total)` recorded cases for each function in `cases.jsonl`, using the full
/// (untruncated) mismatches in `outcome`.
pub fn per_function_counts(crate_dir: &Path, outcome: &DiffOutcome) -> Result<FunctionCounts> {
    let cases_path = crate_dir.join(CASES);
    let text = std::fs::read_to_string(&cases_path)
        .with_context(|| format!("reading {}", cases_path.display()))?;
    counts_from_cases_text(&text, outcome)
}

/// Runs `diff_full` and computes [`per_function_counts`] from the exact `cases.jsonl` snapshot
/// that `diff_full` verified, failing if `cases.jsonl` was modified concurrently.
pub fn diff_full_with_counts(opts: &DiffOptions) -> Result<(DiffOutcome, FunctionCounts)> {
    let _lock = crate::fuzz::RecordingLock::take_recovered(&std::path::absolute(opts.crate_dir)?)?;
    let cases_path = opts.crate_dir.join(CASES);
    if !cases_path.exists() {
        bail!(
            "no {CASES} in {} (run `rust-anything record` first)",
            opts.crate_dir.display()
        );
    }
    let snapshot = std::fs::read_to_string(&cases_path)
        .with_context(|| format!("reading {}", cases_path.display()))?;
    let outcome = diff_full(opts)?;
    let current = std::fs::read_to_string(&cases_path)
        .with_context(|| format!("reading {}", cases_path.display()))?;
    anyhow::ensure!(
        current == snapshot,
        "{CASES} changed while diff was running; rerun `enable`"
    );
    let counts = counts_from_cases_text(&snapshot, &outcome)?;
    Ok((outcome, counts))
}

fn counts_from_cases_text(
    text: &str,
    outcome: &DiffOutcome,
) -> Result<BTreeMap<String, (usize, usize)>> {
    let mut totals: BTreeMap<String, usize> = BTreeMap::new();
    for line in text.lines().filter(|l| !l.is_empty()) {
        let case: Value = parse_deep(line)?;
        if let Some(name) = case["fn"].as_str().or_else(|| case["class"].as_str()) {
            *totals.entry(name.to_string()).or_default() += 1;
        }
    }
    let mut failed: BTreeMap<String, usize> = BTreeMap::new();
    for m in &outcome.mismatches {
        if let Some(name) = m["fn"].as_str().or_else(|| m["class"].as_str()) {
            *failed.entry(name.to_string()).or_default() += 1;
        }
    }
    Ok(totals
        .into_iter()
        .map(|(name, total)| {
            let passed = if outcome.missing.contains(&name) {
                0
            } else {
                total.saturating_sub(failed.get(&name).copied().unwrap_or(0))
            };
            (name, (passed, total))
        })
        .collect())
}

/// Diffs on a connected Android device, using the port built for the device's ABI.
pub fn diff_android(
    opts: &DiffOptions,
    device: Option<&str>,
    jni_libs: Option<&Path>,
) -> Result<DiffOutcome> {
    let manifest = Manifest::load(opts.crate_dir)?;
    check_module(opts.module, &manifest)?;
    let _lock = crate::fuzz::RecordingLock::take_recovered(&std::path::absolute(opts.crate_dir)?)?;
    let port = crate::state::port_version(opts.crate_dir);
    diff_after(
        opts,
        crate::android_device::diff(opts.crate_dir, &manifest, device, jni_libs)?,
        port,
    )
}

fn diff_after(opts: &DiffOptions, exact: DiffOutcome, port: String) -> Result<DiffOutcome> {
    let mut outcome = located(settle(opts, exact)?);
    outcome.mismatches.truncate(SHOWN_MISMATCHES);
    anyhow::ensure!(
        outcome.total > 0,
        "no recorded cases to compare; run `rust-anything record` first"
    );
    if opts.module.is_none() {
        outcome.trend = crate::recording::track(opts.crate_dir, outcome.passed, outcome.total);
        keep_last(opts.crate_dir, &mut outcome, port);
    }
    Ok(outcome)
}

/// Each mismatch with where it starts, and the distinct differences among them.
fn located(mut outcome: DiffOutcome) -> DiffOutcome {
    crate::mismatch::annotate(&mut outcome);
    outcome.groups = crate::mismatch::group_mismatches(&outcome.mismatches);
    outcome
}

/// Applies the float tolerance and `known-diffs.jsonl` to a driver's outcome, keeping every
/// mismatch.
pub(crate) fn settle(opts: &DiffOptions, exact: DiffOutcome) -> Result<DiffOutcome> {
    let mut outcome = exact;
    let manifest = Manifest::load(opts.crate_dir).ok();
    let saved = manifest.as_ref().and_then(|m| m.float_tolerance);
    if let Some(t) = opts.float_tolerance.or(saved) {
        let preserve_key_order = opts.module.is_some()
            || manifest.as_ref().is_none_or(|m| {
                matches!(
                    m.language,
                    crate::lang::Lang::Ts | crate::lang::Lang::Python
                )
            });
        let before = outcome.passed;
        outcome = crate::tolerance::apply(
            outcome,
            crate::tolerance::check(t)?,
            ignores_key_order(opts) || !preserve_key_order,
        );
        let forgiven = outcome.passed - before;
        outcome.notes.push(format!(
            "float tolerance {t} is on ({}): {forgiven} case{} matched only within it",
            if opts.float_tolerance.is_some() {
                "this run's `--float-tolerance`"
            } else {
                "saved by `record --float-tolerance`"
            },
            if forgiven == 1 { "" } else { "s" },
        ));
        if !ignores_key_order(opts) && !preserve_key_order {
            outcome.notes.push(
                "with a float tolerance on, the order of an object's keys is not compared for \
                 this language"
                    .to_string(),
            );
        }
    }
    if ignores_key_order(opts) {
        outcome.notes.push(
            "object key order is ignored (`--ignore-key-order`, saved by `record`)".to_string(),
        );
    }
    if outcome.untyped_errors > 0 {
        outcome.notes.push(format!(
            "{} recorded error{} carry no error class (recorded by an older version): for them \
             the port only has to throw. Run `rust-anything record` again to compare the class",
            outcome.untyped_errors,
            if outcome.untyped_errors == 1 { "" } else { "s" }
        ));
    }
    if outcome.legacy_cases > 0 {
        outcome.notes.push(format!(
            "legacy recording: {} of {} cases hold no post-call state, so for them only the return \
             value was compared, not the arguments after the call or what it printed. Run \
             `rust-anything record` again to compare both",
            outcome.legacy_cases, outcome.total
        ));
    }
    if outcome.not_rerun > 0 {
        outcome.notes.push(format!(
            "{} of the matched cases are cases the original crashed on: they were not re-run \
             against the port",
            outcome.not_rerun
        ));
    }
    Ok(crate::recording::apply_known(
        outcome,
        &crate::recording::known_diffs(opts.crate_dir)?,
    ))
}

pub(crate) fn diff_exact(opts: &DiffOptions) -> Result<DiffOutcome> {
    diff_exact_within(opts, None)
}

/// [`diff_exact`], with the Node driver that runs the port stopped after `limit` when there is
/// one: a port that loops on an input it was not recorded with would otherwise never return.
pub(crate) fn diff_exact_within(
    opts: &DiffOptions,
    limit: Option<std::time::Duration>,
) -> Result<DiffOutcome> {
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let opts = &DiffOptions {
        crate_dir: &crate_dir,
        ..*opts
    };
    if opts.module.is_some() {
        check_module(opts.module, &Manifest::load(opts.crate_dir)?)?;
    }
    if opts.module.is_none()
        && let Ok(manifest) = Manifest::load(opts.crate_dir)
        && let Some(built) = stale_build(opts.crate_dir, &manifest)
    {
        bail!(
            "{} is older than the crate's sources, so diff would test the previous port; run \
             `rust-anything build {}` first",
            built.display(),
            crate::app::cli_path(opts.crate_dir)
        );
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Python
        && opts.module.is_none()
    {
        return crate::harness_py::diff(opts.crate_dir, &manifest, ignores_key_order(opts));
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.kind == Kind::CAbi
        && opts.module.is_none()
    {
        return crate::harness_c::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Go
        && opts.module.is_none()
    {
        return crate::harness_go::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Csharp
        && opts.module.is_none()
    {
        return crate::harness_csharp::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Ruby
        && opts.module.is_none()
    {
        return crate::harness_ruby::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Php
        && opts.module.is_none()
    {
        return crate::harness_php::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Powershell
        && opts.module.is_none()
    {
        return crate::harness_powershell::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Swift
        && opts.module.is_none()
    {
        return crate::harness_swift::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Java
        && opts.module.is_none()
    {
        return crate::harness_java::diff(opts.crate_dir, &manifest);
    }
    if let Ok(manifest) = Manifest::load(opts.crate_dir)
        && manifest.language == crate::lang::Lang::Kotlin
        && opts.module.is_none()
    {
        return crate::harness_kotlin::diff(opts.crate_dir, &manifest);
    }
    let cases = opts.crate_dir.join(CASES);
    if !cases.exists() {
        bail!(
            "no {CASES} in {} (run `rust-anything record` first)",
            opts.crate_dir.display()
        );
    }
    if opts.module.is_none()
        && let Ok(manifest) = Manifest::load(opts.crate_dir)
    {
        ensure_built(opts.crate_dir, &manifest)?;
    }
    let module = match opts.module {
        Some(m) => m.to_path_buf(),
        None => opts.crate_dir.join("index.cjs"),
    };
    let module = module
        .canonical()
        .with_context(|| format!("resolving {}", module.display()))?;
    let work = opts.crate_dir.join(WORK_DIR);
    std::fs::create_dir_all(&work)?;
    let script = work.join("diff.mjs");
    std::fs::write(
        &script,
        format!(
            "{CODEC_JS}\n{ERROR_JS}\n{POST_JS}\n{}\n{DIFF_JS}",
            crate::pin::PIN_JS
        ),
    )?;
    let out = fresh_result(opts.crate_dir, "diff")?;
    let flag = if ignores_key_order(opts) {
        "sort"
    } else {
        "keep"
    };
    let mut cmd = Command::new("node");
    cmd.args(strip_types_args())
        .args(opts.node_args)
        .arg(&script)
        .args([&module, &cases, &out])
        .arg(flag)
        .arg(error_text(opts.crate_dir));
    crate::pin::apply(&mut cmd, opts.crate_dir)?;
    crate::enable::original_only(&mut cmd, &Manifest::load(opts.crate_dir)?);
    if opts.module.is_some() {
        // A package's loader falls back to the original JS when its native module will not load;
        // `new` makes it throw instead, so a diff through a package never passes without Rust
        // running. Set after `original_only`, which removes the variable, and harmless to the
        // original's side: an enabled unit there is switched off by its own `UNIT` variable.
        cmd.env("RUST_ANYTHING_MODE", "new");
    }
    match limit {
        None => run(&mut cmd, "node")?,
        Some(limit) => {
            let _scratch = scratch_cwd(&mut cmd)?;
            let output = crate::process::output(&mut cmd, limit)?;
            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
                bail!(
                    "node failed ({}):\n{}",
                    output.status,
                    tail.into_iter().rev().collect::<Vec<_>>().join("\n")
                );
            }
        }
    }
    read_result(opts.crate_dir, &out, "node")
}

/// The unit's files and the repository files they import, directly or not: what a recording
/// depends on. A change to a helper the unit calls changes what the original does, so the
/// recording's fingerprint covers these too (TS/JS imports, Python imports, Ruby `require_relative`).
pub(crate) fn imported_closure(m: &Manifest, files: Vec<PathBuf>) -> Vec<PathBuf> {
    match m.language {
        crate::lang::Lang::Ts => crate::gate::with_local_imports(&m.root, files),
        crate::lang::Lang::Python => python_closure(&m.root, files),
        crate::lang::Lang::Ruby => ruby_closure(&m.root, files),
        _ => files,
    }
}

fn closure(
    root: &Path,
    files: Vec<PathBuf>,
    imports: impl Fn(&Path, &str) -> Vec<PathBuf>,
) -> Vec<PathBuf> {
    let mut seen: std::collections::BTreeSet<PathBuf> = files.into_iter().collect();
    let mut todo: Vec<PathBuf> = seen.iter().cloned().collect();
    while let Some(file) = todo.pop() {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        for found in imports(&file, &text) {
            if found.starts_with(root)
                && !found.components().any(|c| {
                    matches!(
                        c.as_os_str().to_str(),
                        Some("node_modules" | ".git" | "site-packages" | "__pycache__")
                    )
                })
                && seen.insert(found.clone())
            {
                todo.push(found);
            }
        }
    }
    seen.into_iter().collect()
}

fn python_closure(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
    static IMPORT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let import = IMPORT.get_or_init(|| {
        regex::Regex::new(
            r"(?m)^[ \t]*(?:from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+\(?([\w, \t]+)|import[ \t]+([\w., \t]+))",
        )
        .unwrap()
    });
    let root = root.to_path_buf();
    closure(&root.clone(), files, move |file, text| {
        let here = file.parent().unwrap_or(&root).to_path_buf();
        let module_files = |base: &Path, dotted: &str| -> Vec<PathBuf> {
            if dotted.split('.').all(str::is_empty) {
                return Vec::new();
            }
            let mut path = base.to_path_buf();
            for part in dotted.split('.').filter(|p| !p.is_empty()) {
                path.push(part);
            }
            [path.with_extension("py"), path.join("__init__.py")]
                .into_iter()
                .filter(|p| p.is_file())
                .collect()
        };
        let mut found = Vec::new();
        for c in import.captures_iter(text) {
            if let Some(modules) = c.get(4) {
                for module in modules.as_str().split(',') {
                    let module = module.split_whitespace().next().unwrap_or_default();
                    found.extend(module_files(&here, module));
                    found.extend(module_files(&root, module));
                }
                continue;
            }
            let dots = c.get(1).map_or(0, |d| d.as_str().len());
            let module = c.get(2).map_or("", |m| m.as_str());
            let bases: Vec<PathBuf> = if dots > 0 {
                let mut base = here.clone();
                for _ in 1..dots {
                    base = base.parent().unwrap_or(&root).to_path_buf();
                }
                vec![base]
            } else {
                vec![here.clone(), root.clone()]
            };
            for base in bases {
                found.extend(module_files(&base, module));
                // `from pkg import sub`: a name that is itself a module.
                for name in c.get(3).map_or("", |n| n.as_str()).split(',') {
                    let name = name.split_whitespace().next().unwrap_or_default();
                    if !name.is_empty() {
                        found.extend(module_files(&base, &format!("{module}.{name}")));
                    }
                }
            }
        }
        found
    })
}

fn ruby_closure(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
    static REQUIRE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let require = REQUIRE.get_or_init(|| {
        regex::Regex::new(r#"(?m)^[ \t]*require_relative[ \t(]+['"]([^'"]+)['"]"#).unwrap()
    });
    closure(root, files, |file, text| {
        let here = file.parent().unwrap_or(Path::new("")).to_path_buf();
        require
            .captures_iter(text)
            .map(|c| {
                let target = here.join(&c[1]);
                if target.extension().is_some() {
                    target
                } else {
                    target.with_extension("rb")
                }
            })
            .filter(|p| p.is_file())
            .collect()
    })
}

/// The version of `package` in a Cargo.lock.
fn locked_version(lock: &str, package: &str) -> Option<String> {
    let mut lines = lock.lines();
    while let Some(line) = lines.next() {
        if line.trim() == format!("name = \"{package}\"") {
            let version = lines
                .next()?
                .trim()
                .strip_prefix("version = \"")?
                .strip_suffix('"')?;
            return Some(version.to_string());
        }
    }
    None
}

/// Deterministic inputs for one function: edge cases first, then seeded random mixes.
pub fn generate(
    f: &crate::ts::exports::ExportedFn,
    count: usize,
    types: &[LocalType],
) -> Vec<Value> {
    generate_salted(f, count, types, 0)
}

/// [`generate`] from another seed: `salt` 0 gives the recorded inputs, any other value fresh ones.
pub fn generate_salted(
    f: &crate::ts::exports::ExportedFn,
    count: usize,
    types: &[LocalType],
    salt: u64,
) -> Vec<Value> {
    let mut rng = Rng::new(
        f.name.bytes().fold(0x9E37_79B9_7F4A_7C15, |h, b| {
            (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
        }) ^ salt,
    );
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    let mut attempts = 0;
    while out.len() < count && attempts < count * 20 {
        attempts += 1;
        let args = args_for(&f.params, types, &mut rng);
        let key = serde_json::to_string(&args).unwrap_or_default();
        if seen.insert(key) {
            out.push(Value::Array(args));
        }
    }
    out
}

/// Paths for a `pathlib` parameter: relative and absolute, with no suffix, one and several, a
/// dot file, a trailing slash, `..` and `.` segments, spaces and non-ASCII names, and the empty
/// path (`Path("")` is `.`). None of them has to exist.
const PATHS: &[&str] = &[
    "",
    ".",
    "notes.txt",
    "src/main.py",
    "/tmp/report.tar.gz",
    ".hidden",
    "dir/",
    "a/../b/./c.txt",
    "my docs/ünïcödé 文件.md",
    "/",
];

/// The semantic traps for a value of type `t`: what most often behaves differently once ported
/// (string length and case, signed division and overflow, float printing, map and sort order).
pub(crate) fn trap_values(t: &RType) -> Vec<Value> {
    match t {
        RType::Str => crate::app::STRING_TRAPS
            .iter()
            .chain(
                [
                    "ΣΊΣΥΦΟΣ",
                    "a😀b",
                    "\u{FEFF}bom",
                    "a²b x½ y①",
                    "aⅠb Ⅻ",
                    "a𐐀b 𝐀bc",
                    "कि ٣٤",
                ]
                .iter(),
            )
            .map(|s| json!(s))
            .collect(),
        RType::Int => [
            -7,
            -1,
            0,
            2_147_483_648,
            -2_147_483_649,
            9_007_199_254_740_993,
            i64::MAX,
            i64::MIN,
        ]
        .iter()
        .map(|n| json!(n))
        .collect(),
        RType::F64 => {
            let mut out: Vec<Value> = [
                -7.5,
                0.1,
                0.30000000000000004,
                1e21,
                1e-7,
                5e-324,
                1.797_693_134_862_315_7e308,
                9_007_199_254_740_992.0,
            ]
            .iter()
            .map(|n| json!(n))
            .collect();
            out.push(json!({ "$num": "-0" }));
            out
        }
        RType::Vec(inner) => match inner.as_ref() {
            RType::Str => vec![json!([]), json!(["b", "a", "B", "é", "10", "9", "a"])],
            RType::Int => vec![json!([]), json!([-7, 3, 0, i64::MAX, -1])],
            RType::F64 => vec![json!([]), json!([0.1, 0.2, -0.5, 1e21])],
            _ => vec![json!([])],
        },
        RType::Opt(inner) => {
            let mut out = vec![json!({ "$undefined": true })];
            out.extend(trap_values(inner));
            out
        }
        RType::Json => crate::app::JSON_TRAPS
            .iter()
            .filter_map(|t| serde_json::from_str(t).ok())
            .chain([json!([3, 1, 2]), json!({})])
            .collect(),
        RType::Bytes => vec![
            json!({ "$bytes": [] }),
            json!({ "$bytes": [0] }),
            json!({ "$bytes": [0, 1, 255] }),
            json!({ "$bytes": [104, 101, 108, 108, 111] }),
        ],
        RType::Path => PATHS.iter().map(|p| json!({ "$path": p })).collect(),
        RType::Bool | RType::Unit => Vec::new(),
    }
}

/// Every trap value in every parameter, one at a time, the other arguments as in `base`.
/// Structured parameters (objects with a known shape) are left as generated.
pub fn trap_args(
    params: &[crate::ts::exports::Param],
    base: &[Value],
    regex: bool,
) -> Vec<Vec<Value>> {
    let mut out = Vec::new();
    let params: Vec<&crate::ts::exports::Param> = params
        .iter()
        .filter(|p| !p.ts_type.starts_with("len:"))
        .collect();
    if base.len() < params.iter().filter(|p| !p.rest).count() {
        return out;
    }
    for (i, p) in params.iter().enumerate() {
        if p.rest || i >= base.len() {
            continue;
        }
        if let Some(values) = c_pointer_traps(&p.ts_type) {
            for v in values {
                if base[i] != v {
                    let mut args = base.to_vec();
                    args[i] = v;
                    out.push(args);
                }
            }
            continue;
        }
        let t = param_type(p);
        if let (Some((n, _)), RType::Vec(item), Value::Array(items)) =
            (fixed_array_param(p), &t, &base[i])
            && items.len() == n
        {
            // Each trap of the item type in the first slot, the length kept...
            let mut values: Vec<Value> = if n == 0 || item.contains_json() {
                Vec::new()
            } else {
                trap_values(item)
                    .into_iter()
                    .map(|v| {
                        let mut a = items.clone();
                        a[0] = v;
                        Value::Array(a)
                    })
                    .collect()
            };
            // ...and one list an item too long, which the driver refuses rather than cut.
            let mut long = items.clone();
            long.push(items.first().cloned().unwrap_or(json!(0)));
            values.push(Value::Array(long));
            for v in values {
                if base[i] != v {
                    let mut args = base.to_vec();
                    args[i] = v;
                    out.push(args);
                }
            }
            continue;
        }
        let structured = t.contains_json() && !matches!(t, RType::Json);
        let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
        if structured || (matches!(t, RType::Json) && !any) {
            continue;
        }
        let mut values = trap_values(&t);
        if regex && t == RType::Str {
            values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
        }
        for v in values {
            if base[i] != v {
                let mut args = base.to_vec();
                args[i] = v;
                out.push(args);
            }
        }
    }
    out
}

/// The values a Go integer type holds, where they are fewer than an `i64`'s (`byte` is 0..=255).
/// `uint64` and `uint` are capped at `i64::MAX`, the largest value the generator draws.
fn go_int_range(go: &str) -> Option<(i64, i64)> {
    Some(match go.trim() {
        "int8" => (i64::from(i8::MIN), i64::from(i8::MAX)),
        "int16" => (i64::from(i16::MIN), i64::from(i16::MAX)),
        "int32" | "rune" => (i64::from(i32::MIN), i64::from(i32::MAX)),
        "uint8" | "byte" => (0, i64::from(u8::MAX)),
        "uint16" => (0, i64::from(u16::MAX)),
        "uint32" => (0, i64::from(u32::MAX)),
        "uint64" | "uint" | "uintptr" => (0, i64::MAX),
        _ => return None,
    })
}

/// `v` itself when `range` holds it, else `v` wrapped into `range`, so a draw keeps its spread.
fn fold_into(v: i64, (lo, hi): (i64, i64)) -> i64 {
    if (lo..=hi).contains(&v) {
        return v;
    }
    let span = i128::from(hi) - i128::from(lo) + 1;
    let folded = i128::from(lo) + (i128::from(v) - i128::from(lo)).rem_euclid(span);
    i64::try_from(folded).unwrap_or(lo)
}

/// The length and item type of a parameter whose native type is a Go fixed-size array (`[4]int`).
fn fixed_array_param(p: &crate::ts::exports::Param) -> Option<(usize, &str)> {
    p.native_type
        .as_deref()
        .and_then(crate::codegen_go::fixed_array)
}

/// Edge cases for C pointer parameters: buffers as hex text (`bytes`, `buffer`) or a size of
/// zeroed bytes (`buffer`), the starting value behind an `out` pointer, a `char **` that starts
/// NULL, unwritten or at offset 0 (`outptr`), and structs of zeros, ones, minus ones, minimums
/// and maximums, plus each field zero with the others one (a zero denominator).
fn c_pointer_traps(ts_type: &str) -> Option<Vec<Value>> {
    Some(match ts_type {
        "bytes" => vec![
            json!(""),
            json!("00"),
            json!("ff"),
            json!("616263"),
            json!((0..=255u8).map(|b| format!("{b:02x}")).collect::<String>()),
            json!("ff".repeat(64)),
        ],
        "buffer" => vec![
            json!(0),
            json!(1),
            json!(3),
            json!(64),
            json!("ff".repeat(16)),
        ],
        "out" => vec![json!(0), json!(-1), json!(2_147_483_647)],
        t if t.starts_with("outptr:") => vec![json!(true), Value::Null, json!(0)],
        t => {
            let s = crate::codegen_c::c_struct(t)?;
            let field = |pick: &dyn Fn(&[Value]) -> Value, zero: Option<usize>| {
                let fields = s.fields.iter().enumerate().map(|(i, (ty, name))| {
                    let edges = c_field_edges(ty);
                    let v = if zero == Some(i) {
                        edges[0].clone()
                    } else {
                        pick(&edges)
                    };
                    (name.clone(), v)
                });
                Value::Object(fields.collect())
            };
            let mut out: Vec<Value> = (0..5)
                .map(|k| field(&|e: &[Value]| e[k.min(e.len() - 1)].clone(), None))
                .collect();
            out.extend((0..s.fields.len()).map(|i| field(&|e: &[Value]| e[1].clone(), Some(i))));
            out.dedup();
            out
        }
    })
}

/// Edge values for a C scalar struct field: zero, one, then minus one, the minimum and the
/// maximum where the type has them (non-finite values for floating point).
fn c_field_edges(ty: &str) -> Vec<Value> {
    let ty = ty.trim();
    if ty.contains("float") || ty.contains("double") {
        return vec![
            json!(0.0),
            json!(1.0),
            json!(-1.0),
            json!({ "$num": "NaN" }),
            json!({ "$num": "Infinity" }),
            json!({ "$num": "-Infinity" }),
            json!(0.5),
            json!(1e300),
        ];
    }
    if ty == "bool" || ty == "_Bool" {
        return vec![json!(false), json!(true)];
    }
    let unsigned = ty.starts_with('u') || ty.starts_with("unsigned") || ty == "size_t";
    let bits = if ty.contains('8') || ty.ends_with("char") {
        8
    } else if ty.contains("16") || ty.contains("short") {
        16
    } else if ty.contains("64") || ty.contains("long") || ty.contains("size") || ty.contains("ptr")
    {
        64
    } else {
        32
    };
    if unsigned {
        let max = if bits == 64 {
            u64::MAX
        } else {
            (1u64 << bits) - 1
        };
        vec![json!(0), json!(1), json!(max), json!(max - 1), json!(2)]
    } else {
        let max = i64::MAX >> (64 - bits);
        vec![json!(0), json!(1), json!(-1), json!(-max - 1), json!(max)]
    }
}

/// A random value for a C pointer parameter (see `c_pointer_traps`).
fn c_pointer_value(ts_type: &str, rng: &mut Rng) -> Value {
    const SIZES: [usize; 12] = [0, 1, 2, 3, 4, 5, 8, 16, 17, 64, 100, 1024];
    match ts_type {
        "bytes" => {
            let n = SIZES[rng.below(SIZES.len())];
            let text = rng.below(2) == 0;
            json!(
                (0..n)
                    .map(|_| {
                        let b = if text {
                            0x20 + rng.below(0x5f)
                        } else {
                            rng.below(256)
                        };
                        format!("{b:02x}")
                    })
                    .collect::<String>()
            )
        }
        "buffer" => json!(SIZES[rng.below(SIZES.len())]),
        t if t.starts_with("outptr:") => [json!(true), Value::Null, json!(0)][rng.below(3)].clone(),
        t if let Some(s) = crate::codegen_c::c_struct(t) => Value::Object(
            s.fields
                .iter()
                .map(|(ty, name)| {
                    let edges = c_field_edges(ty);
                    let small: [i32; 14] =
                        [0, 1, -1, 2, 3, 7, 12, 25, 30, 1000, 1001, 90000, -5, -48000];
                    let v = match rng.below(10) {
                        0..=2 => edges[rng.below(edges.len())].clone(),
                        _ if edges.len() == 2 => edges[rng.below(2)].clone(),
                        _ if ty.contains("float") || ty.contains("double") => {
                            json!(f64::from(small[rng.below(small.len())]) / 4.0)
                        }
                        _ if edges[2] != json!(-1) => {
                            json!(small[rng.below(small.len())].unsigned_abs())
                        }
                        _ => json!(small[rng.below(small.len())]),
                    };
                    (name.clone(), v)
                })
                .collect(),
        ),
        _ => json!([0, 1, -1, 7, 1000, 65536][rng.below(6)]),
    }
}

/// One argument list for `params`: values that fit, edge cases, and sometimes omitted optionals.
fn args_for(
    params: &[crate::ts::exports::Param],
    types: &[LocalType],
    rng: &mut Rng,
) -> Vec<Value> {
    let mut args: Vec<Value> = Vec::new();
    // The arguments before this index belong to parameters a call cannot leave out.
    let mut required = 0;
    for p in params {
        match p.ts_type.as_str() {
            t if t.starts_with("len:") => continue,
            t if matches!(t, "bytes" | "buffer" | "out")
                || t.starts_with("outptr:")
                || t.starts_with("struct:") =>
            {
                args.push(c_pointer_value(&p.ts_type, rng));
                required = args.len();
                continue;
            }
            _ => {}
        }
        let t = param_type(p);
        // A Go fixed-size array takes exactly its length of items; the wrong lengths are traps.
        if let (Some((n, native_item)), RType::Vec(item)) = (fixed_array_param(p), &t) {
            let item_ts = p.ts_type.strip_suffix("[]").unwrap_or(&p.ts_type);
            let item_ts = item_ts.trim_start_matches('(').trim_end_matches(')');
            let range = go_int_range(native_item);
            args.push(Value::Array(
                (0..n)
                    .map(|_| {
                        if item.contains_json() {
                            shaped(&shape::parse(item_ts), types, rng, 0)
                        } else if let (Some(range), Some(v)) = (range, value(item, rng).as_i64()) {
                            // One item out of a `byte`'s range would make Go refuse the whole
                            // list, and with 32 of them nearly every list would be refused.
                            json!(fold_into(v, range))
                        } else {
                            value(item, rng)
                        }
                    })
                    .collect(),
            ));
            required = args.len();
            continue;
        }
        // Structured parameters: values that fit the TS type, and now and then a value
        // that does not, so error paths get recorded too.
        let structured = |rng: &mut Rng| {
            if rng.below(100) < 15 {
                value(&RType::Json, rng)
            } else {
                shaped(&shape::parse(&p.ts_type), types, rng, 0)
            }
        };
        if p.rest {
            let inner = match t {
                RType::Vec(inner) => *inner,
                other => other,
            };
            for _ in 0..rng.below(3) {
                args.push(value(&inner, rng));
            }
        } else if t.contains_json() {
            let v = structured(rng);
            args.push(if p.optional && rng.below(5) == 0 {
                json!({ "$undefined": true })
            } else {
                v
            });
        } else {
            args.push(value(&t, rng));
        }
        if !p.optional && !p.rest {
            required = args.len();
        }
    }
    // Search-like functions rarely hit on random text: often derive one string from another.
    let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
    if strings.len() >= 2 && rng.below(10) < 5 {
        let from = strings[rng.below(strings.len())];
        let to = strings[rng.below(strings.len())];
        if from != to {
            let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
            if !source.is_empty() {
                let start = rng.below(source.len());
                let end = start + 1 + rng.below(source.len() - start);
                let mut piece: String = source[start..end].iter().collect();
                if rng.below(4) == 0 {
                    piece = piece.to_uppercase();
                }
                args[to] = Value::String(piece);
            }
        }
    }
    // Trailing optional arguments: sometimes omit them, the way JS callers do. A parameter with
    // no default keeps its argument: `def find(start, stop: Path | None)` cannot be called
    // without `stop`, so leaving it out records a `TypeError` no caller sees.
    while args.len() > required
        && args.last().is_some_and(|a| a.get("$undefined").is_some())
        && rng.below(2) == 0
    {
        args.pop();
    }
    args
}

/// Class scenarios: construct, then call a random sequence of methods.
pub fn scenarios(
    class: &crate::ts::exports::ExportedClass,
    count: usize,
    types: &[LocalType],
) -> Vec<Value> {
    scenarios_salted(class, count, types, 0)
}

/// [`scenarios`] from another seed, as [`generate_salted`].
pub fn scenarios_salted(
    class: &crate::ts::exports::ExportedClass,
    count: usize,
    types: &[LocalType],
    salt: u64,
) -> Vec<Value> {
    let mut rng = Rng::new(
        class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
            (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
        }) ^ salt,
    );
    (0..count)
        .map(|_| {
            let ctor = args_for(&class.constructor, types, &mut rng);
            let steps = if class.methods.is_empty() {
                0
            } else {
                1 + rng.below(12)
            };
            // Stateful classes need calls that meet again (`set(k)` then `get(k)`): string
            // arguments often reuse a string seen earlier in the scenario.
            let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
            let calls: Vec<Value> = (0..steps)
                .map(|_| {
                    let m = &class.methods[rng.below(class.methods.len())];
                    let mut args = args_for(&m.params, types, &mut rng);
                    for arg in &mut args {
                        if arg.is_string() {
                            if !seen.is_empty() && rng.below(2) == 0 {
                                *arg = seen[rng.below(seen.len())].clone();
                            } else {
                                seen.push(arg.clone());
                            }
                        }
                    }
                    json!({ "method": m.name, "args": args })
                })
                .collect();
            json!({ "class": class.name, "ctor": ctor, "calls": calls })
        })
        .collect()
}

/// Property names for generated objects: plain, nested-looking, integer-like (JS orders those
/// first), non-ASCII.
const KEYS: &[&str] = &[
    "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
];

/// A value that fits a TS shape. Named types resolve against `types`; recursion stops at a depth.
fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
    match s {
        Shape::Str => value(&RType::Str, rng),
        Shape::Num => value(&RType::F64, rng),
        Shape::Int => value(&RType::Int, rng),
        Shape::Bool => value(&RType::Bool, rng),
        Shape::Bytes => value(&RType::Bytes, rng),
        Shape::Path => value(&RType::Path, rng),
        Shape::Null => Value::Null,
        Shape::Undefined => json!({ "$undefined": true }),
        Shape::LitStr(text) => Value::String(text.clone()),
        Shape::LitNum(n) => json!(n),
        Shape::LitBool(b) => Value::Bool(*b),
        Shape::Union(items) if !items.is_empty() => {
            shaped(&items[rng.below(items.len())], types, rng, depth)
        }
        Shape::Array(item) if depth < 6 => Value::Array(
            (0..rng.below(4))
                .map(|_| shaped(item, types, rng, depth + 1))
                .collect(),
        ),
        Shape::Tuple(items) => Value::Array(
            items
                .iter()
                .map(|i| shaped(i, types, rng, depth + 1))
                .collect(),
        ),
        Shape::Object(props, index) if depth < 6 => {
            let mut out = serde_json::Map::new();
            for (name, optional, prop) in props {
                if *optional && rng.below(4) == 0 {
                    continue;
                }
                out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
            }
            if let Some(item) = index {
                for _ in 0..rng.below(4) {
                    out.insert(
                        KEYS[rng.below(KEYS.len())].to_string(),
                        shaped(item, types, rng, depth + 1),
                    );
                }
            }
            Value::Object(out)
        }
        Shape::Ref(name, args) if depth < 6 => {
            shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
        }
        Shape::Any => value(&RType::Json, rng),
        // Too deep, or empty: a leaf ends the recursion.
        _ => Value::Null,
    }
}

pub(crate) fn value(t: &RType, rng: &mut Rng) -> Value {
    match t {
        RType::Str => {
            let a = STRINGS[rng.below(STRINGS.len())];
            if rng.below(5) == 0 {
                Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
            } else {
                Value::String(a.into())
            }
        }
        RType::Int => {
            // Small, signed, and the edges of 32 and 64 bits.
            let n: [i64; 12] = [
                0,
                1,
                -1,
                2,
                7,
                42,
                100,
                -100,
                255,
                i64::from(i32::MAX),
                i64::from(i32::MIN),
                i64::MAX,
            ];
            json!(n[rng.below(n.len())])
        }
        RType::F64 => {
            let n = [
                0.0,
                1.0,
                -1.0,
                2.0,
                3.0,
                10.0,
                0.5,
                -2.5,
                42.0,
                100.0,
                1000.0,
                1e6,
                2_147_483_648.0,
                9_007_199_254_740_992.0,
            ];
            match rng.below(n.len() + 4) {
                i if i < n.len() => json!(n[i]),
                i if i == n.len() => json!({ "$num": "-0" }),
                i if i == n.len() + 1 => json!({ "$num": "NaN" }),
                i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
                _ => json!({ "$num": "-Infinity" }),
            }
        }
        RType::Bool => Value::Bool(rng.below(2) == 0),
        RType::Bytes => {
            let len = rng.below(6);
            let bytes: Vec<u64> = (0..len).map(|_| rng.below(256) as u64).collect();
            json!({ "$bytes": bytes })
        }
        RType::Path => json!({ "$path": PATHS[rng.below(PATHS.len())] }),
        RType::Unit => json!({ "$undefined": true }),
        RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
        RType::Opt(inner) => {
            if rng.below(4) == 0 {
                json!({ "$undefined": true })
            } else {
                value(inner, rng)
            }
        }
        RType::Json => {
            let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
            values
                .get(rng.below(values.len().max(1)))
                .cloned()
                .unwrap_or(Value::Null)
        }
    }
}

/// xorshift64*: deterministic, so a recording is reproducible.
pub(crate) struct Rng(u64);

impl Rng {
    pub(crate) fn new(seed: u64) -> Self {
        Self(seed | 1)
    }

    pub(crate) fn below(&mut self, n: usize) -> usize {
        if n == 0 {
            return 0;
        }
        self.0 ^= self.0 >> 12;
        self.0 ^= self.0 << 25;
        self.0 ^= self.0 >> 27;
        let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
        usize::try_from(x >> 33).unwrap_or(0) % n
    }
}

/// How long one recorded case may run before the original is stopped on it:
/// `RUST_ANYTHING_CASE_TIMEOUT` seconds, 10 by default.
pub(crate) fn case_timeout() -> std::time::Duration {
    std::env::var("RUST_ANYTHING_CASE_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<f64>().ok())
        .and_then(crate::process::seconds)
        .unwrap_or(std::time::Duration::from_secs(10))
}

/// Runs a record driver over `cases` with a watchdog. The driver appends the index of each case
/// it starts to `RUST_ANYTHING_PROGRESS` and flushes each recorded line. A case that runs past
/// the time limit (an input that makes the original allocate or loop for ever) stops the driver;
/// the lines recorded so far are kept, that input is left out, and the driver goes on with the
/// rest. An input on which the original ends the process with an error status is left out the
/// same way, and listed as dropped. A new driver first runs again the cases the stopped one ran,
/// without recording them, so the original's state is what `diff` gives the port when it runs
/// the recording in one process. Returns the inputs left out by the time limit. With `sandbox`,
/// the repository kept read-only, the driver runs in a [`crate::process::Sandbox`] that may
/// write only to `work` and its scratch folder.
pub(crate) fn record_cases(
    cases: &[Value],
    work: &Path,
    out: &Path,
    what: &str,
    sandbox: Option<&Path>,
    mut command: impl FnMut(&Path, &Path) -> Result<Command>,
) -> Result<Vec<Value>> {
    use std::process::Stdio;
    use std::time::Instant;
    std::fs::create_dir_all(work)?;
    let timeout = case_timeout();
    let inputs = work.join("record-inputs.json");
    let stderr_path = work.join("record-stderr");
    let mut recorded = String::new();
    let mut timed_out = Vec::new();
    let mut dropped = Vec::new();
    let mut start = 0;
    let mut attempt: usize = 0;
    let mut replay: Vec<Value> = Vec::new();
    let mut last_failure: Option<(String, String)> = None;
    while start < cases.len() {
        if crate::mcp::cancelled() {
            bail!("{what} was stopped: the call was cancelled");
        }
        attempt += 1;
        let run_dir = if sandbox.is_some() {
            let d = crate::app::temp_dir(&format!("record-{attempt}"))?;
            std::fs::create_dir_all(&d)?;
            Some(d)
        } else {
            None
        };
        let io_dir = run_dir.as_deref().unwrap_or(work);
        let part = io_dir.join("record-part.jsonl");
        let progress = io_dir.join("record-progress");
        let skip = replay.len();
        let replayed_lines = recorded.matches('\n').count();
        let rest = &cases[start..];
        let given: Vec<&Value> = replay.iter().chain(rest).collect();
        std::fs::write(&inputs, serde_json::to_string(&given)?)?;
        std::fs::write(&progress, "")?;
        let _ = std::fs::remove_file(&part);
        let mut cmd = command(&inputs, &part)?;
        cmd.env("RUST_ANYTHING_PROGRESS", &progress);
        let scratch = scratch_cwd(&mut cmd)?;
        if let Some(read_only) = sandbox {
            cmd = crate::process::Sandbox {
                read_only,
                scratch: scratch.as_ref().map_or(io_dir, |s| s.0.as_path()),
                writable: &[io_dir],
                loopback: false,
            }
            .wrap(&cmd, true)?;
        }
        cmd.stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(std::fs::File::create(&stderr_path)?);
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt as _;
            cmd.process_group(0);
        }
        let mut child = cmd
            .spawn()
            .map_err(|e| crate::process::spawn_error(&cmd, what, e))?;
        let tracked = crate::mcp::track(child.id());
        let spawned_at = Instant::now();
        let mut current: Option<(usize, Instant)> = None;
        let status = loop {
            if let Some(status) = child.try_wait()? {
                break Some(status);
            }
            let started = std::fs::read_to_string(&progress).ok().and_then(|p| {
                p.lines()
                    .last()
                    .and_then(|l| l.split_whitespace().next())
                    .and_then(|l| l.parse::<usize>().ok())
            });
            match (started, current) {
                (Some(i), Some((j, _))) if i == j => {}
                (Some(i), _) if i < given.len() => {
                    current = Some((i, Instant::now()));
                }
                _ => {}
            }
            let expired = match current {
                Some((_, since)) => since.elapsed() > timeout,
                None => spawned_at.elapsed() > timeout.max(std::time::Duration::from_secs(30)),
            };
            if expired {
                #[cfg(unix)]
                {
                    let _ = Command::new("/bin/kill")
                        .args(["-KILL", "--", &format!("-{}", child.id())])
                        .stderr(Stdio::null())
                        .status();
                }
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        };
        drop(tracked);
        if crate::mcp::cancelled() {
            if let Some(d) = &run_dir {
                let _ = std::fs::remove_dir_all(d);
            }
            bail!("{what} was stopped: the call was cancelled");
        }
        let written = std::fs::read_to_string(&part).unwrap_or_default();
        let complete = written.rfind('\n').map_or("", |end| &written[..=end]);
        let own = after_lines(complete, replayed_lines);
        recorded.push_str(own);
        // A driver writes `N` as it starts input N, and `N invalid` when the arguments do not fit
        // the parameter types the original declares: it cannot be called with them.
        let progress_text = std::fs::read_to_string(&progress).unwrap_or_default();
        if let Some(d) = &run_dir {
            let _ = std::fs::remove_dir_all(d);
        }
        let last_started = progress_text
            .lines()
            .filter_map(|l| l.split_whitespace().next()?.parse::<usize>().ok())
            .max();
        let reached = last_started.map_or(0, |i| (i + 1).saturating_sub(skip));
        let invalid: std::collections::BTreeSet<usize> = progress_text
            .lines()
            .filter_map(|l| {
                let mut words = l.split_whitespace();
                let index = words.next()?.parse::<usize>().ok()?;
                (words.next() == Some("invalid") && index >= skip).then(|| index - skip)
            })
            .collect();
        let stderr_tail = || {
            let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();
            let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
        };
        let ran = |upto: usize| {
            rest[..upto]
                .iter()
                .enumerate()
                .filter(|(k, _)| !invalid.contains(k))
                .map(|(_, c)| c.clone())
                .collect::<Vec<_>>()
        };
        let stopped_at = match status {
            Some(_) => last_started.filter(|i| *i < given.len()),
            None => current.map(|(i, _)| i),
        };
        match (status, stopped_at) {
            (Some(status), _) if status.success() => {
                account_for(rest, own, reached, &invalid, &mut dropped);
                break;
            }
            (_, Some(i)) if i < skip => bail!(
                "{what} stopped on a case it had already recorded when it ran the cases before \
                 input {start} again (that input had stopped it): the original does not do the \
                 same on the same inputs, so its recording could not go on:\n{}",
                stderr_tail()
            ),
            (Some(status), Some(i)) => {
                let i = i - skip;
                let idx = start + i;
                let lines = own.lines().filter(|l| !l.is_empty()).count();
                let skipped = invalid.iter().filter(|k| **k < i).count();
                let failure = stderr_tail();
                if i == 0
                    && lines == 0
                    && !failure.trim().is_empty()
                    && last_failure
                        .as_ref()
                        .is_some_and(|(_, tail)| *tail == failure)
                {
                    bail!("{what} failed ({status}):\n{failure}");
                }
                if lines + skipped > i {
                    account_for(&rest[..=i], own, i + 1, &invalid, &mut dropped);
                    replay.extend(ran(i + 1));
                } else {
                    account_for(&rest[..i], own, i, &invalid, &mut dropped);
                    dropped.push(dropped_case(ENDED, &cases[idx]));
                    replay.extend(ran(i));
                }
                last_failure = Some((status.to_string(), failure));
                start = idx + 1;
            }
            (Some(status), None) => {
                bail!("{what} failed ({status}):\n{}", stderr_tail());
            }
            (None, Some(i)) => {
                let i = i - skip;
                let idx = start + i;
                account_for(&rest[..i], own, i, &invalid, &mut dropped);
                timed_out.push(cases[idx].clone());
                replay.extend(ran(i));
                start = idx + 1;
            }
            (None, None) => bail!("{what} timed out before starting case 0"),
        }
    }
    if let Some((status, failure)) = last_failure.filter(|_| recorded.is_empty()) {
        bail!("{what} failed ({status}):\n{failure}");
    }
    std::fs::write(out, recorded)?;
    std::fs::write(work.join(TIMED_OUT), serde_json::to_string(&timed_out)?)?;
    write_dropped(work, cases.len(), &dropped)?;
    Ok(timed_out)
}

/// `text` after its first `n` lines.
fn after_lines(text: &str, n: usize) -> &str {
    let mut rest = text;
    for _ in 0..n {
        match rest.find('\n') {
            Some(end) => rest = &rest[end + 1..],
            None => return "",
        }
    }
    rest
}

/// Inputs the last `record` could not record, other than by the time limit.
pub(crate) const DROPPED: &str = "dropped.json";

/// An input the generator asked for that the driver did not record: it is not in `cases.jsonl`,
/// so no port is ever checked against it. Inputs are named by function and a hash, never by
/// value, so a listing cannot carry a secret.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DroppedCase {
    /// Why it is missing.
    pub kind: String,
    pub function: String,
    /// FNV-1a of the case's JSON, to find it again in the inputs.
    pub input: String,
}

impl RecordOutcome {
    /// Said when most of the recorded cases threw: the generated inputs probably do not fit the
    /// function (an untyped parameter is given values of every type), so `diff` would mostly check
    /// an error path and a port that gets the normal path wrong could still match.
    pub fn mostly_threw(&self) -> Option<String> {
        mostly_threw(self.cases, self.errors)
    }
}

fn mostly_threw(cases: usize, errors: usize) -> Option<String> {
    (cases >= 5 && errors * 2 > cases).then(|| {
        format!(
            "{errors} of {cases} recorded cases threw: the generated inputs probably do not fit the \
             function's parameters, so the recording mostly checks error paths. Add real inputs \
             with --inputs, annotate the parameter types, or record the original's own tests \
             with --from-tests"
        )
    })
}

pub(crate) const NOT_ENCODED: &str = "not recorded: the driver skipped it (its result could not be encoded as JSON, or the arguments did not decode)";
const NOT_RUN: &str = "not run: the original ended the run early (exit, abort)";
const ENDED: &str =
    "not recorded: the original ended the process with an error status on it (exit, abort)";
/// Arguments that do not fit the parameter types the original declares (a value out of the range
/// of its `int`, a non-finite float inside a slice): the original cannot be called with them, so
/// no behavior is lost. Listed, but not a failure.
pub(crate) const INAPPLICABLE: &str = "not recorded: the arguments do not fit the original's parameter types, so it cannot be called with them";

fn case_name(case: &Value) -> &str {
    case["fn"]
        .as_str()
        .or_else(|| case["class"].as_str())
        .unwrap_or("?")
}

pub(crate) fn dropped_case(kind: &str, case: &Value) -> DroppedCase {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in case.to_string().bytes() {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    DroppedCase {
        kind: kind.to_string(),
        function: case_name(case).to_string(),
        input: format!("{hash:016x}"),
    }
}

/// Whether `line` (a recorded case) is the record of `case`: the same function or class with
/// the same arguments.
fn line_is(case: &Value, line: &Value) -> bool {
    if case_name(case) != case_name(line) {
        return false;
    }
    if case.get("class").is_some() {
        return case["ctor"] == line["ctor"] && case["calls"] == line["calls"];
    }
    case["args"] == line["args"] && case["kwargs"] == line["kwargs"]
}

/// Compares what a driver was given (`cases`, of which it started the first `reached`) with the
/// lines it wrote, and adds each input it neither recorded nor was stopped on to `dropped`.
fn account_for(
    cases: &[Value],
    written: &str,
    reached: usize,
    invalid: &std::collections::BTreeSet<usize>,
    dropped: &mut Vec<DroppedCase>,
) {
    let reached = reached.min(cases.len());
    let lines: Vec<&str> = written.lines().filter(|l| !l.is_empty()).collect();
    for case in &cases[reached..] {
        dropped.push(dropped_case(NOT_RUN, case));
    }
    for index in invalid.iter().filter(|i| **i < reached) {
        dropped.push(dropped_case(INAPPLICABLE, &cases[*index]));
    }
    let skipped = invalid.iter().filter(|i| **i < reached).count();
    // A driver writes one line for each input it starts, except those it marked invalid.
    if lines.len() + skipped >= reached {
        return;
    }
    let parsed: Vec<Value> = lines.iter().filter_map(|l| parse_deep(l).ok()).collect();
    let mut found = Vec::new();
    let mut at = 0;
    for (k, case) in cases[..reached].iter().enumerate() {
        if invalid.contains(&k) {
            continue;
        }
        let Some(line) = parsed.get(at) else {
            found.push(dropped_case(NOT_ENCODED, case));
            continue;
        };
        let later = cases[k + 1..reached.min(k + 257)]
            .iter()
            .enumerate()
            .any(|(n, c)| !invalid.contains(&(k + 1 + n)) && line_is(c, line));
        if line_is(case, line) || (!later && case_name(case) == case_name(line)) {
            at += 1;
        } else {
            found.push(dropped_case(NOT_ENCODED, case));
        }
    }
    // The alignment is exact only when the lines echo their inputs; the count is always right.
    let missing = reached - skipped - lines.len();
    found.truncate(missing);
    while found.len() < missing {
        found.push(DroppedCase {
            kind: NOT_ENCODED.to_string(),
            function: "?".to_string(),
            input: String::new(),
        });
    }
    dropped.extend(found);
}

pub(crate) fn write_dropped(work: &Path, generated: usize, dropped: &[DroppedCase]) -> Result<()> {
    std::fs::write(
        work.join(DROPPED),
        serde_json::to_string(&serde_json::json!({ "generated": generated, "dropped": dropped }))?,
    )?;
    Ok(())
}

/// How many inputs the last driver run could not record (not counting arguments that do not fit
/// the parameter types).
pub(crate) fn last_dropped(crate_dir: &Path) -> usize {
    read_dropped(&crate_dir.join(WORK_DIR)).map_or(0, |(_, dropped)| {
        dropped.iter().filter(|d| d.kind != INAPPLICABLE).count()
    })
}

/// `(generated, dropped)` as the last record driver run wrote them; `None` when it wrote nothing.
fn read_dropped(work: &Path) -> Option<(usize, Vec<DroppedCase>)> {
    let saved: Value =
        serde_json::from_str(&std::fs::read_to_string(work.join(DROPPED)).ok()?).ok()?;
    Some((
        usize::try_from(saved["generated"].as_u64()?).ok()?,
        serde_json::from_value(saved["dropped"].clone()).ok()?,
    ))
}

/// Inputs the last `record` left out because the original ran past the time limit on them.
pub(crate) const TIMED_OUT: &str = "timed-out.json";

/// Where one driver run writes its result: a path no earlier run used (it carries a nonce), with
/// every older result of that kind removed. A port or an original that ends the process with
/// exit status 0 before the driver writes its verdict then leaves no file, instead of leaving the
/// previous green one to be read as this run's.
pub(crate) fn fresh_result(crate_dir: &Path, stem: &str) -> Result<PathBuf> {
    static RUN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let work = crate_dir.join(WORK_DIR);
    std::fs::create_dir_all(&work)?;
    let own = format!("{stem}.json");
    let prefix = format!("{stem}-");
    if let Ok(entries) = std::fs::read_dir(&work) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            // Only results from earlier runs go: another diff may be running in this crate now,
            // and its file is not ours to delete.
            let old = entry
                .metadata()
                .and_then(|m| m.modified())
                .ok()
                .and_then(|t| t.elapsed().ok())
                .is_some_and(|age| age > std::time::Duration::from_secs(600));
            if name == own || (old && name.starts_with(&prefix) && name.ends_with(".json")) {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let count = RUN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    Ok(work.join(format!(
        "{stem}-{:x}-{:x}-{count}.json",
        std::process::id(),
        nanos
    )))
}

/// Reads the verdict a driver wrote to the [`fresh_result`] path `out`, and checks it counts the
/// recorded cases: a missing file, or a verdict that does not add up to the recording, is an
/// error and never a pass.
pub(crate) fn read_result(crate_dir: &Path, out: &Path, what: &str) -> Result<DiffOutcome> {
    let text = std::fs::read_to_string(out).map_err(|_| {
        anyhow::anyhow!(
            "{what} wrote no result this run, so nothing was compared. The port or the original \
             probably ended the process (exit, abort) before the driver finished; run \
             `rust-anything diff {}` again after fixing it",
            crate::app::cli_path(crate_dir)
        )
    })?;
    let _ = std::fs::remove_file(out);
    let outcome: DiffOutcome = serde_json::from_str(&text)
        .with_context(|| format!("reading the result of {what} ({})", out.display()))?;
    check_counts(crate_dir, &outcome, what)?;
    Ok(outcome)
}

/// The driver must have counted every recorded case, each once.
pub(crate) fn check_counts(crate_dir: &Path, outcome: &DiffOutcome, what: &str) -> Result<()> {
    let Ok(text) = std::fs::read_to_string(crate_dir.join(CASES)) else {
        return Ok(());
    };
    let lines = text.lines().filter(|l| !l.trim().is_empty()).count();
    anyhow::ensure!(
        outcome.total == lines && outcome.passed + outcome.failed == outcome.total,
        "{what} counted {} passed and {} failed of {} cases, but {CASES} holds {lines}; the \
         verdict is not trusted. Run `rust-anything diff {}` again",
        outcome.passed,
        outcome.failed,
        outcome.total,
        crate::app::cli_path(crate_dir)
    );
    Ok(())
}

pub(crate) struct Scratch(pub(crate) PathBuf);

impl Scratch {
    pub(crate) fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

pub(crate) fn scratch_cwd(cmd: &mut Command) -> Result<Option<Scratch>> {
    if cmd.get_current_dir().is_some() {
        return Ok(None);
    }
    let dir = crate::app::temp_dir("unit")?;
    cmd.current_dir(&dir);
    Ok(Some(Scratch(dir)))
}

fn run(cmd: &mut Command, what: &str) -> Result<()> {
    let _scratch = scratch_cwd(cmd)?;
    let output = crate::process::output(cmd, std::time::Duration::MAX)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
        bail!(
            "{what} failed ({}):\n{}",
            output.status,
            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
        );
    }
    Ok(())
}

/// napi-rs's build script panics with this when a build for a `windows-gnu` target finds no
/// `libnode.dll` to link (in `LIBNODE_PATH`, `LIBPATH` or `PATH`). Only MSYS2's Node ships one,
/// not the Node.js installer, and builds for `windows-msvc` need none.
const NO_LIBNODE: &str = "libnode.dll not found";

/// A napi build that failed for want of `libnode.dll` gets the way out added, since napi-rs's
/// panic names only the file.
fn explain_libnode(err: anyhow::Error) -> anyhow::Error {
    explain_libnode_with(err, std::env::var("RUSTUP_TOOLCHAIN").ok().as_deref())
}

/// [`explain_libnode`] with the `RUSTUP_TOOLCHAIN` the build ran under: one that names a GNU
/// toolchain overrides `rustup default`, so the fix says to change it too.
fn explain_libnode_with(err: anyhow::Error, rustup_toolchain: Option<&str>) -> anyhow::Error {
    if !err.to_string().contains(NO_LIBNODE) {
        return err;
    }
    let build_tools = crate::doctor::install_command("cc")
        .map(|fix| format!("{fix}\n"))
        .unwrap_or_default();
    let toolchain = rustup_toolchain
        .filter(|t| t.contains("gnu"))
        .map(|t| {
            format!(
                "\nRUSTUP_TOOLCHAIN is set to `{t}`, which overrides the default: unset it, or set \
                 it to stable-msvc"
            )
        })
        .unwrap_or_default();
    anyhow::anyhow!(
        "{err}\n\nnapi-rs links a build for a `windows-gnu` Rust target against libnode.dll, which \
         only MSYS2's Node ships, not the Node.js installer. Build with the MSVC toolchain \
         instead, or bridge a new crate with `--kind wasm --name <name>` and record it again.\n\
         fix: {build_tools}rustup default stable-msvc{toolchain}"
    )
}

/// The names of a unit's exports, sorted and without repeats.
fn export_names(manifest: &Manifest) -> Vec<&str> {
    let mut names: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
    names.sort_unstable();
    names.dedup();
    names
}

/// Why an `--inputs` line names a function the unit cannot record: it stays in the original, or
/// it is not there, with what the unit does have (exports, classes), and never an empty list.
/// A function stays in the original when `bridge --keep` named it or when `bridge` found a
/// blocker itself, and the manifest does not record which, so the message gives the reason and
/// not the source.
fn unknown_function(manifest: &Manifest, name: &str) -> String {
    if let Some(kept) = manifest.js_only.iter().find(|k| k.name == name) {
        let why = if kept.reason.is_empty() {
            String::new()
        } else {
            format!(" ({})", kept.reason)
        };
        return format!("`{name}` stays in the original{why}, so it is not recorded");
    }
    let exports = export_names(manifest);
    let classes: Vec<&str> = manifest.classes.iter().map(|c| c.name.as_str()).collect();
    let mut has = Vec::new();
    if !exports.is_empty() {
        has.push(format!("exports: {}", exports.join(", ")));
    }
    if !classes.is_empty() {
        has.push(format!(
            "classes: {}; a class goes in as {{\"class\": name, \"ctor\": [..], \"calls\": [..]}}",
            classes.join(", ")
        ));
    }
    if has.is_empty() {
        format!("`{name}` is not an export of this unit, which has no exports or ported classes")
    } else {
        format!(
            "`{name}` is not an export of this unit ({})",
            has.join("; ")
        )
    }
}

/// Why an `--inputs` line names a class the unit has not ported, with the classes it has.
fn unknown_class(manifest: &Manifest, class: &str) -> String {
    let mut known: Vec<&str> = manifest.classes.iter().map(|c| c.name.as_str()).collect();
    known.sort_unstable();
    known.dedup();
    if known.is_empty() {
        format!("`{class}` is not a ported class of this unit, which has no ported classes")
    } else {
        format!(
            "`{class}` is not a ported class of this unit (classes: {})",
            known.join(", ")
        )
    }
}

/// Integral float arguments of `number` parameters, as ints.
fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
    let Some(items) = args.as_array_mut() else {
        return;
    };
    for (p, v) in params.iter().zip(items.iter_mut()) {
        if p.ts_type == "number"
            && let Some(x) = v.as_f64()
            && x.fract() == 0.0
            && x.abs() < 1e15
            && !(x == 0.0 && x.is_sign_negative())
        {
            *v = json!(x as i64);
        }
    }
}

/// Python keyword-only parameters (after `*`) are passed by name: they move from `args` into
/// `kwargs`, and an omitted (`undefined`) one is left out.
fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
    if !params.iter().any(|p| p.keyword_only) {
        return;
    }
    let Some(args) = case["args"].as_array().cloned() else {
        return;
    };
    let mut positional = Vec::new();
    let mut kwargs = serde_json::Map::new();
    for (i, value) in args.into_iter().enumerate() {
        match params.get(i) {
            Some(p) if p.keyword_only => {
                if value.get("$undefined").is_none() {
                    kwargs.insert(p.name.clone(), value);
                }
            }
            _ => positional.push(value),
        }
    }
    case["args"] = Value::Array(positional);
    case["kwargs"] = Value::Object(kwargs);
}

/// Workspace packages as `{ name: absolute source folder }` for the resolve hook: a monorepo
/// imports its own packages by name, and their build output may not exist.
fn workspace_env(manifest: &Manifest) -> String {
    let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
        .map(|ws| {
            ws.packages
                .into_iter()
                .filter(|p| !p.dir.is_empty())
                .map(|p| {
                    let dir = manifest.root.join(&p.dir);
                    let src = if dir.join("src").is_dir() {
                        dir.join("src")
                    } else {
                        dir
                    };
                    (p.name, src.to_string_lossy().into_owned())
                })
                .collect()
        })
        .unwrap_or_default();
    serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
}

/// The tsconfig `paths` of the unit's files, as JSON for the resolve hook: `[[pattern, [absolute targets]]]`.
fn alias_env(manifest: &Manifest) -> String {
    let mut entries: Vec<(String, Vec<String>)> = Vec::new();
    let files = manifest
        .exports
        .iter()
        .map(|f| &f.file)
        .chain(manifest.classes.iter().map(|c| &c.file));
    for file in files {
        let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
        for (pattern, targets) in
            crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
        {
            if entries.iter().all(|(p, _)| *p != pattern) {
                let absolute = targets
                    .iter()
                    .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
                    .collect();
                entries.push((pattern, absolute));
            }
        }
    }
    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
}

fn file_url(path: &Path) -> String {
    use std::fmt::Write as _;

    let text = path.to_string_lossy();
    #[cfg(windows)]
    let text = text.replace('\\', "/");
    let mut url = if text.starts_with('/') {
        String::from("file://")
    } else {
        String::from("file:///")
    };
    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'_' | b'.' | b'~') {
            url.push(char::from(byte));
        } else {
            let _ = write!(url, "%{byte:02X}");
        }
    }
    url
}

const REGISTER_JS: &str =
    "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";

/// Node resolve hook: bundler-style relative imports, and npm packages from
/// `RUST_ANYTHING_RESOLVE_FROM` when the source tree has none installed.
const RESOLVE_JS: &str = r#"
import { existsSync, statSync } from 'node:fs'
import { fileURLToPath, pathToFileURL } from 'node:url'

const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
// tsconfig `paths`: exact keys first, then wildcard keys by longest prefix.
const aliasPriority = pattern => pattern.includes('*') ? pattern.indexOf('*') : Number.POSITIVE_INFINITY
const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
  .sort(([a], [b]) => aliasPriority(b) - aliasPriority(a))
// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
const workspaceTargets = (specifier) => {
  for (const [name, src] of Object.entries(workspace)) {
    if (specifier === name)
      return [`${src}/index`]
    if (specifier.startsWith(`${name}/`))
      return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
  }
  return []
}
const aliasTargets = (specifier) => {
  for (const [pattern, targets] of aliases) {
    const [prefix, suffix = ''] = pattern.split('*')
    const exact = !pattern.includes('*')
    if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
      const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
      return targets.map(t => t.replace('*', () => star))
    }
  }
  return []
}
const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
const sourceCandidates = path => {
  const exact = path.match(/\.(mjs|cjs|jsx)$/)
  if (exact) {
    const replacement = { mjs: 'mts', cjs: 'cts', jsx: 'tsx' }[exact[1]]
    return [path, path.slice(0, -exact[1].length) + replacement]
  }
  const stem = path.replace(/\.js$/, '')
  return [stem, ...suffixes.map(suffix => stem + suffix)]
}
const isFile = p => existsSync(p) && statSync(p).isFile()

export async function resolve(specifier, context, next) {
  // Aliases first: `@/x` is not even a valid package name for Node.
  for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
    for (const candidate of sourceCandidates(target)) {
      if (isFile(candidate))
        return next(pathToFileURL(candidate).href, context)
    }
  }
  try {
    return await next(specifier, context)
  }
  catch (error) {
    const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
    if (!missing || !context.parentURL)
      throw error
    if (specifier.startsWith('.') || specifier.startsWith('/')) {
      const path = fileURLToPath(new URL(specifier, context.parentURL))
      for (const candidate of sourceCandidates(path)) {
        if (isFile(candidate))
          return next(pathToFileURL(candidate).href, context)
      }
    }
    else if (extra) {
      return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
    }
    throw error
  }
}
"#;

/// Encoding shared by the record, diff and shadow scripts. Lossless for what a JS caller
/// can observe: `undefined`, `NaN`, `-0`, BigInt, Map/Set order, key order, lone surrogates.
pub const CODEC_JS: &str = r#"
const enc = (v, stack = []) => {
  if (v === undefined) return { $undefined: true }
  if (typeof v === 'number') {
    if (Number.isNaN(v)) return { $num: 'NaN' }
    if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
    if (Object.is(v, -0)) return { $num: '-0' }
    return v
  }
  // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
  if (typeof v === 'bigint') return { $bigint: String(v) }
  if (typeof v === 'function') return { $function: v.name }
  if (typeof v === 'symbol') return { $symbol: String(v.description) }
  if (v === null || typeof v !== 'object') return v
  if (stack.includes(v)) return { $cycle: true }
  const next = [...stack, v]
  if (Array.isArray(v)) return v.map(x => enc(x, next))
  if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: [...v] }
  if (v instanceof Uint8Array) return { $bytes: [...v] }
  if (ArrayBuffer.isView(v) && !(v instanceof DataView)) return { $typed: { kind: v.constructor.name, values: [...v].map(x => enc(x, next)) } }
  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
  if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
  if (v instanceof RegExp) return { $regexp: String(v) }
  if (v instanceof Error) return { $error: v.message }
  const plain = Object.fromEntries(Object.keys(v).map(k => [k, enc(v[k], next)]))
  return looksLikeMarker(plain) ? { $object: plain } : plain
}
const MARKERS = ['$undefined', '$num', '$bigint', '$utf16', '$map', '$set', '$date', '$bytes', '$buffer', '$typed', '$object']
const looksLikeMarker = (v) => {
  const keys = Object.keys(v)
  return keys.length === 1 && MARKERS.includes(keys[0])
}
const dec = (v) => {
  if (Array.isArray(v)) return v.map(dec)
  if (v === null || typeof v !== 'object') return v
  if (!looksLikeMarker(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dec(x)]))
  if ('$object' in v) return Object.fromEntries(Object.entries(v.$object).map(([k, x]) => [k, dec(x)]))
  if ('$undefined' in v) return undefined
  if ('$num' in v) return Number(v.$num)
  if ('$bigint' in v) return BigInt(v.$bigint)
  if ('$utf16' in v) {
    let text = ''
    for (let i = 0; i < v.$utf16.length; i += 8192)
      text += String.fromCharCode(...v.$utf16.slice(i, i + 8192))
    return text
  }
  if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
  if ('$set' in v) return new Set(v.$set.map(dec))
  if ('$date' in v) return new Date(v.$date)
  if ('$bytes' in v) return Uint8Array.from(v.$bytes)
  if ('$typed' in v) return globalThis[v.$typed.kind].from(v.$typed.values.map(dec))
  return Buffer.from(v.$buffer)
}
const canon = (v, sort) => {
  if (Array.isArray(v)) return v.map(x => canon(x, sort))
  if (v === null || typeof v !== 'object') return v
  const keys = Object.keys(v)
  if (sort) keys.sort()
  return Object.fromEntries(keys.map(k => [k, canon(v[k], sort)]))
}
const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
"#;

/// How a thrown error is named and told from a Rust panic, for the record and diff scripts.
/// A recording keeps the class of each error the original threw (`error_type`); `diff` requires
/// the port's error to be that class where the port can raise it (the built-in ones: the glue turns
/// `Err("RangeError: ...")` into a `RangeError`), and a plain `Error` for a class of the original's
/// own, which the port cannot create. A throw of anything but an `Error` counts as `Error`.
const ERROR_JS: &str = r#"
const errorType = (e) => {
  if (!(e instanceof Error)) return 'Error'
  const name = e.constructor?.name
  return name && name !== 'Error' ? name : (typeof e.name === 'string' && e.name ? e.name : 'Error')
}
const BUILT_IN_ERRORS = ['Error', 'TypeError', 'RangeError', 'SyntaxError', 'ReferenceError', 'URIError', 'EvalError', 'AggregateError']
// A WebAssembly trap is how a Rust panic reaches JS under wasm32 (panic=abort).
const isPanic = (e) => e?.code === 'RUST_PANIC' || (typeof WebAssembly !== 'undefined' && e instanceof WebAssembly.RuntimeError) || String(e?.message ?? '').startsWith('Rust panic:')
const portThrown = (e) => {
  const message = String(e?.message ?? e)
  return { error: isPanic(e) && !message.startsWith('Rust panic:') ? `Rust panic: ${message}` : message, error_type: e instanceof Error && e.name ? e.name : 'Error' }
}
// Whether the port's error class `got` agrees with the recorded `want` (absent in old recordings).
const errorTypeOk = (want, got) => want === undefined || (BUILT_IN_ERRORS.includes(want) ? got === want : got === 'Error' || got === want)
"#;

/// What a call did besides returning, for the record and diff scripts: its arguments after it
/// (serialised with `enc`, compared with how they were serialised before) and what it wrote to
/// `process.stdout`. A function that prints through `console.log` is caught here because the
/// console writes to `process.stdout`; a write straight to file descriptor 1 is not.
const POST_JS: &str = r#"
const captureStdout = () => {
  const stream = process.stdout
  const original = stream.write
  let text = ''
  stream.write = function (chunk, encoding, callback) {
    text += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding : 'utf8')
    const done = typeof encoding === 'function' ? encoding : callback
    if (typeof done === 'function') done()
    return true
  }
  return () => { stream.write = original; return text }
}
const encodeArgs = (args) => args.map(a => enc(a))
// The encoded arguments after the call when they are not what they were before it.
const changedArgs = (before, args) => {
  const after = encodeArgs(args)
  return JSON.stringify(after) === before ? undefined : after
}
"#;

const RECORD_JS: &str = r#"
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'

const [inputsPath, outPath] = process.argv.slice(2)
const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
const modules = new Map()
const progress = process.env.RUST_ANYTHING_PROGRESS
writeFileSync(outPath, '')
const lines = { push: line => appendFileSync(outPath, `${line}\n`) }
// A class scenario: construct, then call each method in turn; every step's result is recorded.
const runScenario = async (Class, c) => {
  const results = []
  let instance
  try {
    instance = new Class(...c.ctor.map(dec))
    results.push({ ok: true })
  }
  catch (error) {
    results.push({ error: String(error?.message ?? error), error_type: errorType(error) })
    return results
  }
  for (const call of c.calls) {
    try {
      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
    }
    catch (error) {
      results.push({ error: String(error?.message ?? error), error_type: errorType(error) })
    }
  }
  return results
}
for (const [index, c] of inputs.entries()) {
  if (progress) appendFileSync(progress, `${index}\n`)
  let mod = modules.get(c.module)
  if (!mod) {
    mod = await import(pathToFileURL(c.module).href)
    modules.set(c.module, mod)
  }
  if (c.class) {
    const Class = mod[c.class] ?? mod.default?.[c.class]
    if (typeof Class !== 'function') {
      console.error(`${c.class} is not a class exported by ${c.module}`)
      process.exit(2)
    }
    pinCase(index)
    lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
    continue
  }
  const fn = mod[c.fn] ?? mod.default?.[c.fn]
  if (typeof fn !== 'function') {
    console.error(`${c.fn} is not a function exported by ${c.module}`)
    process.exit(2)
  }
  pinCase(index)
  const args = c.args.map(dec)
  const before = JSON.stringify(encodeArgs(args))
  const stop = captureStdout()
  let result
  try {
    result = { ok: enc(await fn(...args)) }
  }
  catch (error) {
    result = { error: String(error?.message ?? error), error_type: errorType(error) }
  }
  const printed = stop()
  const after = changedArgs(before, args)
  // `post`: this line holds what the call changed and printed (`args_after` when an argument
  // changed, `stdout` when it printed), so the port is compared on both.
  lines.push(JSON.stringify({ fn: c.fn, args: c.args, ...result, post: true, ...(after ? { args_after: after } : {}), ...(printed ? { stdout: printed } : {}) }))
}
"#;

const BENCH_JS: &str = r#"
import { readFileSync, writeFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'

const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
const { functions: modules, classes: classModules, asyncFunctions } = JSON.parse(readFileSync(modulesPath, 'utf8'))
const loaded = await import(pathToFileURL(nativePath).href)
const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
const byFn = new Map()
const scenarios = new Map()
for (const c of cases.filter(c => c.class)) {
  if (!scenarios.has(c.class)) scenarios.set(c.class, [])
  scenarios.get(c.class).push(c)
}
for (const c of cases.filter(c => !c.class)) {
  if (!byFn.has(c.fn)) byFn.set(c.fn, [])
  byFn.get(c.fn).push(c.args.map(dec))
}
// Time whole passes over the cases until `minMs` has passed; errors count as calls.
const time = (fn, argsList) => {
  const pass = () => {
    for (const args of argsList) {
      try { fn(...args) } catch {}
    }
  }
  pass()
  let passes = 0
  const start = performance.now()
  do { pass(); passes++ } while (performance.now() - start < Number(minMs))
  return (performance.now() - start) * 1e6 / (passes * argsList.length)
}
const timeAsync = async (fn, argsList) => {
  const pass = async () => {
    for (const args of argsList) {
      try { await fn(...args) } catch {}
    }
  }
  await pass()
  let passes = 0
  const start = performance.now()
  do { await pass(); passes++ } while (performance.now() - start < Number(minMs))
  return (performance.now() - start) * 1e6 / (passes * argsList.length)
}
const rows = []
for (const [name, argsList] of byFn) {
  const original = (await import(pathToFileURL(modules[name]).href))[name]
  const rust = native[name]
  if (typeof original !== 'function' || typeof rust !== 'function') continue
  const timer = asyncFunctions.includes(name) ? timeAsync : time
  const originalNs = await timer(original, argsList)
  const rustNs = await timer(rust, argsList)
  rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
}
// Classes: time whole scenarios (construct, then every call).
const play = (Class, list) => () => {
  for (const c of list) {
    try {
      const instance = new Class(...c.ctor.map(dec))
      for (const call of c.calls) {
        try { instance[call.method](...call.args.map(dec)) } catch {}
      }
    } catch {}
  }
}
for (const [name, list] of scenarios) {
  const original = (await import(pathToFileURL(classModules[name]).href))[name]
  const rust = native[name]
  if (typeof original !== 'function' || typeof rust !== 'function') continue
  const timeAll = (fn) => {
    fn()
    let passes = 0
    const start = performance.now()
    do { fn(); passes++ } while (performance.now() - start < Number(minMs))
    return (performance.now() - start) * 1e6 / (passes * list.length)
  }
  const originalNs = timeAll(play(original, list))
  const rustNs = timeAll(play(rust, list))
  rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
}
writeFileSync(outPath, JSON.stringify(rows))
"#;

const DIFF_JS: &str = r#"
import { readFileSync, writeFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'

const [modulePath, casesPath, outPath, keyOrder, errorText] = process.argv.slice(2)
const loaded = await import(pathToFileURL(modulePath).href)
const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [], untyped_errors: 0, legacy_cases: 0 }
const scenario = async (Class, c) => {
  const results = []
  let instance
  try {
    instance = new Class(...c.ctor.map(dec))
    results.push({ ok: true })
  }
  catch (error) {
    results.push(portThrown(error))
    return results
  }
  for (const call of c.calls) {
    try {
      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
    }
    catch (error) {
      results.push(portThrown(error))
    }
  }
  return results
}
// A recorded error without a class (a recording from before classes were kept) agrees with any
// non-panic error; those cases are counted, so the verdict can say so. With `record --messages`
// the message must be the recorded one too.
const errorsAgree = (want, got) => {
  if (want.error_type === undefined) summary.untyped_errors++
  return !got.error.startsWith('Rust panic:') && errorTypeOk(want.error_type, got.error_type) && (errorText !== 'messages' || got.error === want.error)
}
const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
  ('error' in w && 'error' in got[i] && errorsAgree(w, got[i])) || ('ok' in w && 'ok' in got[i] && same(w.ok, got[i].ok, keyOrder === 'sort')))
for (const [index, c] of cases.entries()) {
  pinCase(index)
  if (c.class) {
    const Class = mod[c.class]
    if (typeof Class !== 'function') {
      if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
      summary.failed++
      continue
    }
    const got = await scenario(Class, c)
    if (stepsMatch(c.results, got)) {
      summary.passed++
    }
    else {
      summary.failed++
      summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
    }
    continue
  }
  const fn = mod[c.fn]
  let actual
  if (typeof fn !== 'function') {
    if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
    actual = { missing: true }
  }
  else {
    const args = c.args.map(dec)
    const before = JSON.stringify(encodeArgs(args))
    const stop = captureStdout()
    try {
      actual = { ok: enc(await fn(...args)) }
    }
    catch (error) {
      actual = portThrown(error)
    }
    const printed = stop()
    // A recording from before post-call state was kept (no `post`) is compared by result only.
    if (c.post) {
      const after = changedArgs(before, args)
      // A mismatch shows the arguments as they are after the call, changed or not.
      if (after || 'args_after' in c) actual.args_after = after ?? encodeArgs(args)
      if (printed || 'stdout' in c) actual.stdout = printed
    }
    else {
      summary.legacy_cases++
    }
  }
  const expected = 'error' in c ? { error: c.error, ...('error_type' in c ? { error_type: c.error_type } : {}) } : { ok: c.ok }
  if (c.post) {
    if ('args_after' in c) expected.args_after = c.args_after
    if ('stdout' in c) expected.stdout = c.stdout
  }
  // Both sides throwing counts as agreement when the error classes agree (and the messages, under
  // `record --messages`); a Rust panic is never an agreeing error. A call must also leave its arguments
  // and its output as the original did, whether it returned or threw.
  const sameEffects = !c.post || actual.missing || (same(expected.args_after ?? null, actual.args_after ?? null, keyOrder === 'sort') && (expected.stdout ?? '') === (actual.stdout ?? ''))
  const pass = sameEffects && (('error' in expected && 'error' in actual && errorsAgree(expected, actual)) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort')))
  if (pass) {
    summary.passed++
  }
  else {
    summary.failed++
    summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
  }
}
writeFileSync(outPath, JSON.stringify(summary, null, 2))
"#;

#[cfg(test)]
mod tests {
    #[test]
    fn a_go_fixed_size_array_gets_its_length_and_one_wrong_length_trap() {
        let f = crate::ts::exports::ExportedFn {
            name: "Rev".into(),
            params: vec![crate::ts::exports::Param {
                name: "a".into(),
                ts_type: "int[]".into(),
                native_type: Some("[4]int".into()),
                ..Default::default()
            }],
            returns: "int[]".into(),
            ..Default::default()
        };
        let cases = super::generate(&f, 50, &[]);
        assert!(!cases.is_empty());
        for case in &cases {
            assert_eq!(case[0].as_array().map(Vec::len), Some(4), "{case}");
        }
        let base = cases[0].as_array().unwrap().clone();
        let traps = super::trap_args(&f.params, &base, false);
        let lengths: Vec<usize> = traps
            .iter()
            .map(|args| args[0].as_array().map_or(0, Vec::len))
            .collect();
        // Every integer trap in the first slot with the length kept, then one list too long.
        assert_eq!(
            lengths.iter().filter(|&&n| n == 5).count(),
            1,
            "{lengths:?}"
        );
        assert!(
            lengths.iter().filter(|&&n| n == 4).count() >= 5,
            "{lengths:?}"
        );
        assert!(lengths.iter().all(|&n| n == 4 || n == 5), "{lengths:?}");
        assert!(traps.iter().any(|args| args[0][0] == i64::MAX));
    }

    #[test]
    fn a_go_fixed_size_array_of_bytes_gets_items_a_byte_holds() {
        let f = crate::ts::exports::ExportedFn {
            name: "Sum".into(),
            params: vec![crate::ts::exports::Param {
                name: "b".into(),
                ts_type: "int[]".into(),
                native_type: Some("[32]byte".into()),
                ..Default::default()
            }],
            returns: "int".into(),
            ..Default::default()
        };
        let cases = super::generate(&f, 50, &[]);
        assert!(cases.len() >= 40, "{}", cases.len());
        let items: Vec<i64> = cases
            .iter()
            .flat_map(|case| case[0].as_array().unwrap().clone())
            .map(|v| v.as_i64().unwrap())
            .collect();
        assert_eq!(items.len(), cases.len() * 32);
        assert!(items.iter().all(|n| (0..=255).contains(n)), "{items:?}");
        // Spread over the range, not pinned to one value.
        assert!(items.contains(&0) && items.iter().any(|&n| n > 100));
    }

    #[test]
    fn a_draw_outside_a_narrow_go_integer_is_folded_into_it() {
        assert_eq!(super::fold_into(42, (0, 255)), 42);
        assert_eq!(super::fold_into(-1, (0, 255)), 255);
        assert_eq!(super::fold_into(256, (0, 255)), 0);
        assert_eq!(super::fold_into(i64::MAX, (-128, 127)), -1);
        assert_eq!(super::fold_into(i64::MIN, (0, i64::MAX)), 0);
        assert_eq!(super::go_int_range("byte"), Some((0, 255)));
        assert_eq!(super::go_int_range("int"), None);
    }

    #[test]
    fn an_installed_library_is_dated_now_not_like_the_file_it_was_copied_from() {
        let dir = crate::app::temp_dir("install-dated").unwrap();
        let built = dir.join("built.node");
        std::fs::write(&built, b"library").unwrap();
        // A library from an earlier build, as a shared cache hands it out.
        let old = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(86_400);
        std::fs::File::options()
            .write(true)
            .open(&built)
            .unwrap()
            .set_modified(old)
            .unwrap();
        let dest = dir.join("out.node");
        install(&built, &dest).unwrap();
        let installed = std::fs::metadata(&dest).unwrap().modified().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            installed > old + std::time::Duration::from_secs(86_400 * 365),
            "installed library carries its source's old date: {installed:?}"
        );
    }

    #[test]
    fn a_recording_that_mostly_threw_says_so() {
        let warning = super::mostly_threw(12, 11).expect("11 of 12 threw");
        assert!(
            warning.starts_with("11 of 12 recorded cases threw"),
            "{warning}"
        );
        assert!(warning.contains("--inputs"), "{warning}");
        // Half or fewer, or too few cases to say anything, stay quiet.
        assert_eq!(super::mostly_threw(12, 6), None);
        assert_eq!(super::mostly_threw(4, 4), None);
        assert_eq!(super::mostly_threw(0, 0), None);
    }

    #[test]
    fn inputs_a_driver_did_not_record_are_named_by_function_and_hash_only() {
        let case = |n: i64| serde_json::json!({ "fn": "f", "args": [n, "secret-value"] });
        let cases: Vec<_> = (1..=5).map(case).collect();
        let line = |n: i64| {
            format!(
                "{}\n",
                serde_json::json!({ "fn": "f", "args": [n, "secret-value"], "ok": n })
            )
        };
        // Inputs 2 and 4 got no line, input 3 was marked as not fitting the parameter types, and
        // the driver stopped after starting 5 of the 6 it was given (the sixth was never run).
        let mut cases = cases;
        cases.push(case(6));
        let written = format!("{}{}", line(1), line(5));
        let mut dropped = Vec::new();
        let invalid = std::collections::BTreeSet::from([2]);
        super::account_for(&cases, &written, 5, &invalid, &mut dropped);
        let by_kind = |kind: &str| -> Vec<&super::DroppedCase> {
            dropped.iter().filter(|d| d.kind == kind).collect()
        };
        assert_eq!(by_kind(super::NOT_RUN).len(), 1, "{dropped:?}");
        assert_eq!(by_kind(super::INAPPLICABLE).len(), 1, "{dropped:?}");
        let lost = by_kind(super::NOT_ENCODED);
        assert_eq!(lost.len(), 2, "{dropped:?}");
        assert!(
            lost.iter()
                .all(|d| d.function == "f" && d.input.len() == 16)
        );
        // The listing carries no argument value.
        assert!(!format!("{dropped:?}").contains("secret-value"));
        // Which inputs they were: 2 and 4 (the hash is of the case's JSON).
        let hashes: Vec<&str> = lost.iter().map(|d| d.input.as_str()).collect();
        assert_eq!(hashes[0], super::dropped_case("", &case(2)).input);
        assert_eq!(hashes[1], super::dropped_case("", &case(4)).input);
    }

    #[test]
    fn a_driver_that_recorded_every_input_drops_nothing() {
        let cases: Vec<_> = (1..=3)
            .map(|n| serde_json::json!({ "fn": "f", "args": [n] }))
            .collect();
        let written: String = (1..=3)
            .map(|n| {
                format!(
                    "{}\n",
                    serde_json::json!({ "fn": "f", "args": [n], "ok": n })
                )
            })
            .collect();
        let mut dropped = Vec::new();
        super::account_for(&cases, &written, 3, &Default::default(), &mut dropped);
        assert!(dropped.is_empty(), "{dropped:?}");
    }

    #[test]
    fn a_recorded_secret_is_found_by_the_variable_that_holds_it() {
        let canary = ["EXAMPLE", "0000", "fake"].join("-");
        let cases = format!(
            "{{\"fn\": \"setting\", \"args\": [\"A\"], \"ok\": \"{canary}\"}}\n\
             {{\"fn\": \"other\", \"args\": [], \"ok\": \"fine\"}}\n\
             {{\"fn\": \"quoted\", \"args\": [], \"ok\": \"has \\\"quote\\\" and tab\\t\"}}\n"
        );
        let cases = cases.as_str();
        let vars = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
            pairs
                .iter()
                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                .collect()
        };
        // A secret-looking name whose value is in the recording is reported, value unnamed.
        let found = super::recorded_secrets(cases, vars(&[("MY_API_TOKEN", &canary)]));
        assert_eq!(
            found,
            [("MY_API_TOKEN".to_string(), vec!["setting".to_string()])]
        );
        // The value as JSON escapes it is found too.
        let found =
            super::recorded_secrets(cases, vars(&[("DB_PASSWORD", "has \"quote\" and tab\t")]));
        assert_eq!(
            found,
            [("DB_PASSWORD".to_string(), vec!["quoted".to_string()])]
        );
        // Not reported: a name that is not secret-looking, a short value, a value that is absent.
        let quiet = vars(&[
            ("EDITOR_NAME", &canary),
            ("API_TOKEN", "fine"),
            ("GITHUB_TOKEN", "not-in-the-cases"),
            ("GIT_AUTHOR_NAME", &canary),
        ]);
        assert!(super::recorded_secrets(cases, quiet).is_empty());
    }

    #[test]
    fn a_secret_is_found_whichever_way_the_driver_escaped_it() {
        // Go's `json.Marshal` writes `<` as `\u003c`; the value is the same once decoded.
        let cases = "{\"fn\": \"setting\", \"args\": [], \"ok\": \"pre\\u003cfix-example\"}\n\
                     {\"fn\": \"nested\", \"args\": [], \"ok\": {\"k\": [\"x pre<fix-example y\"]}}\n\
                     not json pre<fix-example\n";
        let vars = vec![("MY_SECRET".to_string(), "pre<fix-example".to_string())];
        let found = super::recorded_secrets(cases, vars);
        assert_eq!(
            found,
            [(
                "MY_SECRET".to_string(),
                vec!["setting".to_string(), "nested".to_string(), "?".to_string()]
            )]
        );
    }

    /// A driver in `sh` for `record_cases`: input `n` records `{"fn":"f","args":[n],"ok":c}`
    /// where `c` counts the calls this process made (state the original keeps between calls),
    /// and a negative `n` ends the process with status 3.
    #[cfg(unix)]
    fn counting_driver(
        inputs: &std::path::Path,
        part: &std::path::Path,
    ) -> anyhow::Result<std::process::Command> {
        let script = r#"i=0; c=0
for n in $(grep -o '"args":\[[-0-9]*\]' "$1" | sed 's/.*\[//; s/\]//'); do
  echo $i >> "$RUST_ANYTHING_PROGRESS"
  if [ "$n" -lt 0 ]; then echo "ended on $n" >&2; exit 3; fi
  c=$((c+1))
  echo "{\"fn\":\"f\",\"args\":[$n],\"ok\":$c}" >> "$2"
  i=$((i+1))
done"#;
        let mut cmd = std::process::Command::new("sh");
        cmd.arg("-c").arg(script).arg("sh").arg(inputs).arg(part);
        Ok(cmd)
    }

    #[cfg(unix)]
    #[test]
    fn an_input_that_ends_the_process_is_left_out_and_the_rest_replay_in_one_process() {
        let work = crate::app::temp_dir("record-ended").unwrap();
        let out = work.join("cases.jsonl");
        let cases: Vec<_> = [1, -1, 2, 3]
            .iter()
            .map(|n| serde_json::json!({ "fn": "f", "args": [n] }))
            .collect();
        let timed_out =
            super::record_cases(&cases, &work, &out, "sh", None, counting_driver).unwrap();
        let recorded = std::fs::read_to_string(&out).unwrap();
        let dropped = super::read_dropped(&work).unwrap();
        std::fs::remove_dir_all(&work).unwrap();
        assert!(timed_out.is_empty());
        assert_eq!(
            recorded,
            "{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n\
             {\"fn\":\"f\",\"args\":[2],\"ok\":2}\n\
             {\"fn\":\"f\",\"args\":[3],\"ok\":3}\n",
            "the cases after the restart see the state of the cases before it, as one process \
             running the recording in order does"
        );
        assert_eq!(dropped.1.len(), 1, "{dropped:?}");
        assert_eq!(dropped.1[0].kind, super::ENDED);
        assert_eq!(dropped.1[0].input, super::dropped_case("", &cases[1]).input);
    }

    #[cfg(unix)]
    #[test]
    fn a_driver_that_ends_on_every_input_fails_with_its_error() {
        let work = crate::app::temp_dir("record-ended-all").unwrap();
        let out = work.join("cases.jsonl");
        let cases: Vec<_> = [-1, -2, -3]
            .iter()
            .map(|n| serde_json::json!({ "fn": "f", "args": [n] }))
            .collect();
        let err = super::record_cases(&cases, &work, &out, "sh", None, counting_driver)
            .unwrap_err()
            .to_string();
        let one = [serde_json::json!({ "fn": "f", "args": [-1] })];
        let alone = super::record_cases(&one, &work, &out, "sh", None, counting_driver)
            .unwrap_err()
            .to_string();
        std::fs::remove_dir_all(&work).unwrap();
        assert!(
            err.contains("sh failed") && err.contains("ended on"),
            "{err}"
        );
        assert!(
            alone.contains("sh failed") && alone.contains("ended on -1"),
            "{alone}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_cancelled_call_stops_the_record_driver_and_writes_nothing() {
        let work = crate::app::temp_dir("record-cancelled").unwrap();
        let out = work.join("cases.jsonl");
        let started = work.join("started");
        let cases = [serde_json::json!({ "fn": "f", "args": [1] })];
        let call = crate::mcp::as_call();
        let cancel = call.canceller();
        let watched = started.clone();
        let canceller = std::thread::spawn(move || {
            while !watched.exists() {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            cancel();
        });
        let begun = std::time::Instant::now();
        let err = super::record_cases(&cases, &work, &out, "sh", None, |_, _| {
            let mut cmd = std::process::Command::new("sh");
            cmd.arg("-c")
                .arg(format!("touch '{}'; sleep 30", started.display()));
            Ok(cmd)
        })
        .unwrap_err()
        .to_string();
        canceller.join().unwrap();
        drop(call);
        let written = out.exists();
        std::fs::remove_dir_all(&work).unwrap();
        assert!(err.contains("cancelled"), "{err}");
        assert!(
            begun.elapsed() < std::time::Duration::from_secs(10),
            "{:?}",
            begun.elapsed()
        );
        assert!(!written);
    }

    #[test]
    fn a_recording_with_a_secret_puts_the_previous_one_back() {
        let dir = crate::app::temp_dir("record-secret-back").unwrap();
        let cases = dir.join("cases.jsonl");
        let secret = ["EXAMPLE", "1111", "fake"].join("-");
        let env = || vec![("MY_API_TOKEN".to_string(), secret.clone())];
        std::fs::write(
            &cases,
            format!("{{\"fn\":\"f\",\"args\":[],\"ok\":\"{secret}\"}}\n"),
        )
        .unwrap();
        let previous = b"{\"fn\":\"f\",\"args\":[],\"ok\":\"old\"}\n".to_vec();
        let err = super::refuse_recorded_secrets(&cases, Some(previous.clone()), env())
            .unwrap_err()
            .to_string();
        let kept = std::fs::read(&cases).unwrap();
        std::fs::write(
            &cases,
            format!("{{\"fn\":\"f\",\"args\":[],\"ok\":\"{secret}\"}}\n"),
        )
        .unwrap();
        let none = super::refuse_recorded_secrets(&cases, None, env());
        let gone = !cases.exists();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(err.contains("previous recording put back"), "{err}");
        assert_eq!(kept, previous);
        assert!(
            none.is_err() && gone,
            "with no previous recording the new one is removed"
        );
    }

    #[test]
    fn a_library_is_dated_when_its_build_started() {
        let dir = crate::app::temp_dir("install-dated").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();
        std::fs::write(dir.join("built.so"), b"lib").unwrap();
        let started = std::time::SystemTime::now();
        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(dir.join("src/port.rs"), "pub fn f() {}\n").unwrap();
        let dest = dir.join("x.node");
        super::install_dated(&dir.join("built.so"), &dest, &dir, started).unwrap();
        let newer = super::sources_newer_than(&dir, &dest);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            newer,
            "a source saved while cargo built is newer than the library it built"
        );
    }

    /// On a file system that keeps whole seconds, the library is dated on the second; a
    /// `Cargo.lock` written earlier in that second, with a fraction, is not newer, while a source
    /// saved in a later second is. A library with a fraction is compared exactly.
    #[test]
    fn a_library_dated_on_a_whole_second_is_compared_by_seconds() {
        let dir = crate::app::temp_dir("whole-second").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]
name = \"x\"
",
        )
        .unwrap();
        std::fs::write(dir.join("Cargo.lock"), "").unwrap();
        std::fs::write(
            dir.join("src/port.rs"),
            "pub fn f() {}
",
        )
        .unwrap();
        std::fs::write(dir.join("built.so"), b"lib").unwrap();
        let second = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000);
        let at = |path: &str, millis: u64| {
            std::fs::File::options()
                .write(true)
                .open(dir.join(path))
                .unwrap()
                .set_modified(second + std::time::Duration::from_millis(millis))
                .unwrap();
        };
        let built = dir.join("built.so");
        at("Cargo.toml", 0);
        at("src/port.rs", 0);
        at("built.so", 0);
        at("Cargo.lock", 353);
        let same_second = super::sources_newer_than(&dir, &built);
        at("src/port.rs", 1_200);
        let next_second = super::sources_newer_than(&dir, &built);
        at("src/port.rs", 0);
        at("built.so", 200);
        let fraction = super::sources_newer_than(&dir, &built);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(!same_second, "Cargo.lock in the library's own second");
        assert!(next_second, "a source saved a second later");
        assert!(fraction, "a library with a fraction is compared exactly");
    }

    #[test]
    fn a_diff_is_stamped_with_the_port_it_started_on() {
        let dir = crate::app::temp_dir("diff-stamp-start").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/port.rs"), "pub fn f() {}\n").unwrap();
        let checked = crate::state::port_version(&dir);
        std::fs::write(dir.join("src/port.rs"), "pub fn f() { todo!() }\n").unwrap();
        let mut outcome = super::DiffOutcome::default();
        super::keep_last(&dir, &mut outcome, checked.clone());
        let saved: serde_json::Value = crate::state::load(&dir, crate::state::LAST_DIFF).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(saved["port"], serde_json::json!(checked));
        assert_eq!(outcome.port.as_deref(), Some(checked.as_str()));
    }

    #[cfg(unix)]
    #[test]
    fn a_recording_that_cannot_be_removed_is_emptied() {
        use std::os::unix::fs::PermissionsExt;
        let dir =
            std::env::temp_dir().join(format!("rust-anything-discard-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("cases.jsonl");
        std::fs::write(&file, "secret\n").unwrap();
        // A folder that does not allow removing files, with a file that can be written.
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();
        let done = super::discard_recording(&file);
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
        // Running as root removes it anyway; either way nothing readable is left.
        assert!(matches!(done, Ok("emptied" | "removed")));
        assert!(std::fs::read_to_string(&file).map_or(true, |text| text.is_empty()));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_class_bench_row_is_failing_when_its_cases_do_not_match() {
        let outcome = DiffOutcome {
            missing: vec!["Gone".into()],
            ..Default::default()
        };
        let counts = BTreeMap::from([("Counter".to_string(), (1, 2)), ("add".to_string(), (2, 2))]);
        assert!(super::failing("class Counter", &outcome, &counts));
        assert!(super::failing("class Gone", &outcome, &counts));
        assert!(!super::failing("add", &outcome, &counts));
    }

    use super::*;
    use crate::ts::exports::{ExportedFn, Param};

    #[test]
    fn a_saved_key_order_choice_is_read_by_diffs_without_the_flag() {
        // `record --ignore-key-order` writes it; `gate`, `enable`, `report` and `go` have no flag of
        // their own, so they inherit it from here.
        let dir = std::env::temp_dir().join(format!("ra-key-order-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let opts = |flag: bool| DiffOptions {
            crate_dir: &dir,
            module: None,
            ignore_key_order: flag,
            node_args: &[],
            float_tolerance: None,
        };
        // No crate at all: the flag alone decides, and nothing panics.
        assert!(!ignores_key_order(&opts(false)));
        assert!(ignores_key_order(&opts(true)));
        // What `record` saves is what `gate`, `enable` and `report` read without the flag.
        let manifest: Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": ".",
            "unit": "src/util.ts",
            "kind": "napi",
            "crate_name": "util-rs",
            "exports": [],
        }))
        .unwrap();
        manifest.save(&dir).unwrap();
        assert!(!ignores_key_order(&opts(false)));
        let mut saved = Manifest::load(&dir).unwrap();
        saved.ignore_key_order = true;
        saved.save(&dir).unwrap();
        assert!(ignores_key_order(&opts(false)));
        saved.ignore_key_order = false;
        saved.save(&dir).unwrap();
        assert!(!ignores_key_order(&opts(false)));
        assert!(ignores_key_order(&opts(true)));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn node_gets_the_strip_types_flag_only_where_it_needs_it() {
        use crate::doctor::Version;
        for (major, minor, patch) in [(22, 6, 0), (22, 14, 0), (22, 17, 1), (23, 0, 0), (23, 5, 9)]
        {
            assert!(
                needs_strip_types_flag(Version(major, minor, patch)),
                "{major}.{minor}.{patch}"
            );
        }
        // Before 22.6 the flag does not exist (doctor asks for 22.6); from 22.18 and 23.6 Node
        // strips types by default.
        for (major, minor, patch) in [
            (22, 5, 9),
            (22, 18, 0),
            (22, 20, 0),
            (23, 6, 0),
            (24, 13, 1),
            (25, 0, 0),
        ] {
            assert!(
                !needs_strip_types_flag(Version(major, minor, patch)),
                "{major}.{minor}.{patch}"
            );
        }
    }

    #[test]
    fn the_js_codec_keeps_marker_shaped_data_and_typed_arrays() {
        let script = format!(
            "{CODEC_JS}\n{}",
            r#"
const assert = (ok, what) => { if (!ok) { console.error(what); process.exit(1) } }
const round = v => dec(JSON.parse(JSON.stringify(enc(v))))
const plain = [{ $date: '2024-01-01T00:00:00.000Z' }, { $undefined: true }, { $bigint: '7' }, { $map: [['a', 1]] }, { $set: [1, 2] }, { $object: 1 }]
for (const v of plain) assert(JSON.stringify(round(v)) === JSON.stringify(v), 'plain ' + JSON.stringify(v))
const wide = dec({ $date: '2024-01-01T00:00:00.000Z', tz: 'UTC' })
assert(wide.tz === 'UTC' && typeof wide.$date === 'string', 'sibling keys are data')
assert(round(new Date(0)) instanceof Date, 'dates still decode')
for (const T of [Float64Array, Float32Array, Int32Array, Uint8ClampedArray, BigInt64Array]) {
  const v = T === BigInt64Array ? new T([1n, -2n]) : new T([1, 2])
  const back = round(v)
  assert(back instanceof T && back.length === 2 && back[1] === v[1], 'typed ' + T.name)
}
assert(JSON.stringify(enc(new Float64Array([1, 2]))) !== JSON.stringify(enc(new Int32Array([1, 2]))), 'kinds differ')
assert(round(new Uint8Array([1])) instanceof Uint8Array, 'bytes stay bytes')
"#
        );
        let Ok(out) = Command::new("node")
            .args(["--input-type=module", "-e", &script])
            .output()
        else {
            return;
        };
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn f(params: &[(&str, &str)]) -> ExportedFn {
        ExportedFn {
            name: "f".into(),
            file: "a.ts".into(),
            line: 1,
            params: params
                .iter()
                .map(|(n, t)| Param {
                    name: (*n).into(),
                    ts_type: (*t).into(),
                    optional: false,
                    rest: false,
                    ..Default::default()
                })
                .collect(),
            returns: "number".into(),
            is_async: false,
            is_generator: false,
            type_params: Vec::new(),
            uses_instanceof: false,
            ..Default::default()
        }
    }

    #[test]
    fn reads_case_lines_deeper_than_128() {
        let deep = format!("{}1{}", "[".repeat(300), "]".repeat(300));
        assert!(serde_json::from_str::<Value>(&deep).is_err());
        assert!(parse_deep(&deep).is_ok());
        assert!(parse_deep("[1] x").is_err());
    }

    #[test]
    fn generates_deterministic_distinct_inputs() {
        let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
        let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
        assert_eq!(a, b);
        assert_eq!(a.len(), 50);
        let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
        assert_eq!(unique.len(), 50);
        assert!(
            a.iter()
                .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
        );
    }

    #[test]
    fn generates_values_that_fit_object_types() {
        let types = crate::ts::exports::local_types(
            "m.ts",
            "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
        );
        let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
        let fitting = cases
            .iter()
            .filter_map(|args| args[0].as_array())
            .flatten()
            .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
            .count();
        assert!(fitting > 20, "{fitting}");
    }

    #[test]
    fn covers_number_edge_cases() {
        let cases = generate(&f(&[("n", "number")]), 18, &[]);
        let text = serde_json::to_string(&cases).unwrap();
        assert!(text.contains("NaN") && text.contains("-0"));
    }

    #[test]
    fn an_android_diff_waits_for_the_recording() {
        let dir = crate::app::temp_dir("harness-android-lock").unwrap();
        std::fs::write(
            dir.join(crate::bridge::MANIFEST),
            r#"{"schema": "rust-anything/bridge@1", "root": ".", "unit": "src/X.java", "language": "java", "kind": "ffi", "crate_name": "x-rs", "exports": []}"#,
        )
        .unwrap();
        let held = crate::fuzz::RecordingLock::take(&dir).unwrap();
        let d = dir.clone();
        let diff = std::thread::spawn(move || {
            let opts = DiffOptions {
                crate_dir: &d,
                module: None,
                ignore_key_order: false,
                node_args: &[],
                float_tolerance: None,
            };
            let _ = diff_android(&opts, Some("no-such-device"), None);
        });
        std::thread::sleep(std::time::Duration::from_millis(150));
        let waited = !diff.is_finished();
        drop(held);
        diff.join().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(waited, "the diff read the recording while a record held it");
    }

    #[cfg(unix)]
    #[test]
    fn a_cancelled_call_stops_the_driver_it_runs() {
        let dir = crate::app::temp_dir("harness-run-cancel").unwrap();
        let started = dir.join("started");
        let call = crate::mcp::as_call();
        let cancel = call.canceller();
        let watched = started.clone();
        let canceller = std::thread::spawn(move || {
            while !watched.exists() {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            cancel();
        });
        let start = std::time::Instant::now();
        let sh = format!("touch '{}'; sleep 30", started.display());
        let err = run(Command::new("sh").args(["-c", &sh]), "node").unwrap_err();
        canceller.join().unwrap();
        drop(call);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            start.elapsed() < std::time::Duration::from_secs(10),
            "{:?}",
            start.elapsed()
        );
        assert!(format!("{err:#}").contains("node failed"), "{err:#}");
    }

    #[test]
    fn run_reports_missing_program_clearly() {
        let program = "rust-anything-nonexistent-build-tool-498";
        let err = run(&mut Command::new(program), "cargo build").unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains(&format!("`{program}` not found on PATH")),
            "{msg}"
        );
        assert!(msg.contains("rust-anything doctor"), "{msg}");
        assert!(!msg.contains("os error"), "{msg}");
    }

    fn param(name: &str, ts_type: &str, keyword_only: bool) -> crate::ts::exports::Param {
        crate::ts::exports::Param {
            name: name.into(),
            ts_type: ts_type.into(),
            keyword_only,
            ..Default::default()
        }
    }

    fn number_params(n: usize) -> Vec<crate::ts::exports::Param> {
        (0..n)
            .map(|i| param(&format!("p{i}"), "number", false))
            .collect()
    }

    #[test]
    fn intify_turns_integral_floats_into_ints() {
        let mut args = serde_json::json!([3.0, -4.0, 0.0, 12345.0]);
        super::intify(&number_params(4), &mut args);
        assert_eq!(args.to_string(), "[3,-4,0,12345]");
    }

    #[test]
    fn intify_keeps_fractions_negative_zero_and_huge_values() {
        let mut args = serde_json::json!([2.5, -0.0, 1e15, -1e15, 999999999999999.0]);
        super::intify(&number_params(5), &mut args);
        let items = args.as_array().unwrap();
        for item in &items[..4] {
            assert!(item.is_f64(), "{item} should stay a float");
        }
        assert_eq!(items[0].as_f64(), Some(2.5));
        assert!(items[1].as_f64().unwrap().is_sign_negative());
        assert_eq!(items[2].as_f64(), Some(1e15));
        assert_eq!(items[3].as_f64(), Some(-1e15));
        assert!(items[4].is_i64());
    }

    #[test]
    fn intify_leaves_other_types_and_non_arrays_alone() {
        let params = vec![
            param("s", "string", false),
            param("n", "number", false),
            param("u", "unknown", false),
        ];
        let mut args = serde_json::json!([3.0, 4.0, 5.0]);
        super::intify(&params, &mut args);
        assert_eq!(args.to_string(), "[3.0,4,5.0]");
        let mut extra = serde_json::json!([1.0, 2.0]);
        super::intify(&number_params(1), &mut extra);
        assert_eq!(extra.to_string(), "[1,2.0]");
        let mut not_array = serde_json::json!({"a": 1.0});
        super::intify(&number_params(1), &mut not_array);
        assert_eq!(not_array, serde_json::json!({"a": 1.0}));
        let mut strings = serde_json::json!(["3.0"]);
        super::intify(&number_params(1), &mut strings);
        assert_eq!(strings, serde_json::json!(["3.0"]));
    }

    #[test]
    fn split_keyword_only_moves_named_arguments_into_kwargs() {
        let params = vec![
            param("a", "number", false),
            param("sep", "string", true),
            param("b", "number", false),
            param("end", "string", true),
        ];
        let mut case = serde_json::json!({"args": [1, "-", 2, "!"]});
        super::split_keyword_only(&params, &mut case);
        assert_eq!(
            case,
            serde_json::json!({"args": [1, 2], "kwargs": {"sep": "-", "end": "!"}})
        );
    }

    #[test]
    fn split_keyword_only_leaves_out_an_undefined_keyword_argument() {
        let params = vec![param("a", "number", false), param("sep", "string", true)];
        let mut case = serde_json::json!({"args": [1, {"$undefined": true}]});
        super::split_keyword_only(&params, &mut case);
        assert_eq!(case, serde_json::json!({"args": [1], "kwargs": {}}));
    }

    #[test]
    fn split_keyword_only_changes_nothing_without_keyword_only_params() {
        let params = vec![param("a", "number", false), param("b", "number", false)];
        let mut case = serde_json::json!({"args": [1, 2]});
        super::split_keyword_only(&params, &mut case);
        assert_eq!(case, serde_json::json!({"args": [1, 2]}));
    }

    #[test]
    fn split_keyword_only_keeps_extra_arguments_and_skips_a_case_without_args() {
        let params = vec![param("sep", "string", true)];
        let mut case = serde_json::json!({"args": ["-", 9]});
        super::split_keyword_only(&params, &mut case);
        assert_eq!(
            case,
            serde_json::json!({"args": [9], "kwargs": {"sep": "-"}})
        );
        let mut no_args = serde_json::json!({"name": "f"});
        super::split_keyword_only(&params, &mut no_args);
        assert_eq!(no_args, serde_json::json!({"name": "f"}));
    }
}

#[cfg(test)]
mod unknown_name_tests {
    use super::*;

    fn unit(exports: &[&str], classes: &[&str], kept: &[(&str, &str)]) -> Manifest {
        let export = |name: &str| {
            serde_json::json!({ "name": name, "file": "a.ts", "line": 1, "params": [],
                "returns": "number", "is_async": false, "is_generator": false,
                "type_params": [], "uses_instanceof": false })
        };
        let class = |name: &str| {
            serde_json::json!({ "name": name, "file": "a.ts", "line": 1, "constructor": [],
                "methods": [], "blocker": null })
        };
        let kept_entry = |(name, reason): &(&str, &str)| serde_json::json!({ "name": name, "file": "a.ts", "line": 1, "reason": reason });
        serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": ".",
            "unit": "a.ts",
            "kind": "napi",
            "crate_name": "a-rs",
            "exports": exports.iter().map(|n| export(n)).collect::<Vec<_>>(),
            "classes": classes.iter().map(|n| class(n)).collect::<Vec<_>>(),
            "js_only": kept.iter().map(kept_entry).collect::<Vec<_>>(),
        }))
        .unwrap()
    }

    #[test]
    fn a_function_that_stays_in_the_original_is_said_to_stay_there_whoever_kept_it() {
        // `--keep` and `bridge`'s own blockers both land in `js_only`; neither is blamed on a flag.
        let m = unit(&["shout"], &[], &[("whisper", "uses locale")]);
        let said = unknown_function(&m, "whisper");
        assert_eq!(
            said,
            "`whisper` stays in the original (uses locale), so it is not recorded"
        );
        assert!(!said.contains("--keep"), "{said}");
        // Without a reason there is no empty `()`.
        let m = unit(&["shout"], &[], &[("whisper", "")]);
        assert_eq!(
            unknown_function(&m, "whisper"),
            "`whisper` stays in the original, so it is not recorded"
        );
    }

    #[test]
    fn an_unknown_function_names_what_the_unit_has_and_never_an_empty_list() {
        // Exports only: the message is what it was.
        assert_eq!(
            unknown_function(&unit(&["scale", "add"], &[], &[]), "nope"),
            "`nope` is not an export of this unit (exports: add, scale)"
        );
        // A class-only unit used to print `(exports: )`.
        let class_only = unknown_function(&unit(&[], &["Counter"], &[]), "inc");
        assert!(class_only.contains("classes: Counter"), "{class_only}");
        assert!(class_only.contains("\"class\": name"), "{class_only}");
        assert!(!class_only.contains("exports:"), "{class_only}");
        // Both are named; neither list is empty.
        let both = unknown_function(&unit(&["add"], &["Counter"], &[]), "nope");
        assert!(both.contains("exports: add; classes: Counter"), "{both}");
        // Nothing at all: a sentence, not `()`.
        assert_eq!(
            unknown_function(&unit(&[], &[], &[]), "nope"),
            "`nope` is not an export of this unit, which has no exports or ported classes"
        );
    }

    #[test]
    fn an_unknown_class_lists_the_ported_classes() {
        assert_eq!(
            unknown_class(&unit(&[], &["Stack", "Counter", "Stack"], &[]), "Cnt"),
            "`Cnt` is not a ported class of this unit (classes: Counter, Stack)"
        );
        assert_eq!(
            unknown_class(&unit(&["add"], &[], &[]), "Cnt"),
            "`Cnt` is not a ported class of this unit, which has no ported classes"
        );
    }
}

#[cfg(test)]
mod libnode_tests {
    use super::*;

    #[test]
    fn a_napi_build_without_libnode_gets_the_way_out() {
        // What napi-rs 3's build script prints on `x86_64-pc-windows-gnu`, as `run` reports it.
        let failed = anyhow::anyhow!(
            "cargo build failed (exit code: 101):\n  thread 'main' panicked at napi-3.16.3\\build.rs:45:5:\n  \
             libnode.dll not found in any search path\nwarning: build failed, waiting for other jobs to finish..."
        );
        let explained = explain_libnode_with(failed, None).to_string();
        assert!(
            explained.starts_with("cargo build failed (exit code: 101):"),
            "{explained}"
        );
        assert!(
            explained.contains("--kind wasm --name <name>"),
            "{explained}"
        );
        // The Build Tools first, then the switch: following the `fix:` lines in order works.
        let build_tools = crate::doctor::install_command("cc").unwrap();
        assert!(
            explained.ends_with(&format!("\nfix: {build_tools}\nrustup default stable-msvc")),
            "{explained}"
        );
    }

    #[test]
    fn napi_s_other_libnode_panic_is_explained_too() {
        let failed = anyhow::anyhow!(
            "cargo build failed (exit code: 101):\n  libnode.dll not found in C:\\node"
        );
        assert!(
            explain_libnode_with(failed, None)
                .to_string()
                .contains("rustup default stable-msvc")
        );
    }

    #[test]
    fn other_napi_build_failures_are_left_alone() {
        let failed = anyhow::anyhow!("cargo build failed (exit code: 101):\nerror[E0308]");
        assert_eq!(
            explain_libnode_with(failed, None).to_string(),
            "cargo build failed (exit code: 101):\nerror[E0308]"
        );
    }

    #[test]
    fn a_gnu_rustup_toolchain_override_is_named_in_the_fix() {
        let failed = || anyhow::anyhow!("libnode.dll not found in any search path");
        let gnu = explain_libnode_with(failed(), Some("stable-x86_64-pc-windows-gnu")).to_string();
        assert!(
            gnu.ends_with(
                "\nrustup default stable-msvc\nRUSTUP_TOOLCHAIN is set to \
                 `stable-x86_64-pc-windows-gnu`, which overrides the default: unset it, or set it \
                 to stable-msvc"
            ),
            "{gnu}"
        );
        let msvc = explain_libnode_with(failed(), Some("stable-msvc")).to_string();
        assert!(msvc.ends_with("\nrustup default stable-msvc"), "{msvc}");
    }
}

#[cfg(test)]
mod verdict_tests {
    use super::*;

    fn row(name: &str, speedup: f64) -> BenchRow {
        BenchRow {
            name: name.into(),
            cases: 1,
            original_ns: speedup,
            rust_ns: 1.0,
            speedup,
            failing: false,
        }
    }

    #[test]
    fn functions_that_do_not_match_are_left_out_of_the_verdict() {
        // The numbers in #341: `count` is ported, `rangeOf` and `words` still panic.
        let failing = |name, speedup| BenchRow {
            failing: true,
            ..row(name, speedup)
        };
        let cd = std::path::Path::new("rust/unit-rs");
        let v = verdict(
            &[
                failing("rangeOf", 0.0012),
                failing("words", 0.0058),
                row("count", 0.11),
            ],
            crate::lang::Lang::Ts,
            cd,
        );
        assert_eq!(v.left_out, ["rangeOf", "words"]);
        assert!((v.speedup - 0.11).abs() < 1e-9, "{v:?}");
        assert_eq!(v.slower, ["count"]);

        let none = verdict(&[failing("words", 0.0058)], crate::lang::Lang::Ts, cd);
        assert!(
            none.advice
                .contains("Run `rust-anything diff rust/unit-rs`"),
            "{}",
            none.advice
        );
        assert!((none.speedup - 1.0).abs() < 1e-9);
    }

    #[test]
    fn advice_follows_the_numbers() {
        let ts = crate::lang::Lang::Ts;
        let cd = std::path::Path::new("rust/unit-rs");
        assert!(
            verdict(&[row("a", 3.0), row("b", 2.0)], ts, cd)
                .advice
                .starts_with("Ship it: every")
        );
        assert!(
            verdict(&[row("a", 3.0), row("b", 1.0)], ts, cd)
                .advice
                .starts_with("Ship it: no function")
        );
        let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts, cd);
        assert!(
            mixed.advice.contains("Keep the slower one")
                && mixed
                    .advice
                    .contains("`rust-anything enable rust/unit-rs --only a`")
                && !mixed.advice.contains("bridge --keep")
                && mixed.advice.ends_with("b."),
            "{}",
            mixed.advice
        );
        let mixed_many = verdict(&[row("a", 10.0), row("b", 0.5), row("c", 0.5)], ts, cd);
        assert!(
            mixed_many.advice.contains("Keep the slower ones")
                && mixed_many
                    .advice
                    .contains("`rust-anything enable rust/unit-rs --only a`")
                && mixed_many.advice.ends_with("c."),
            "{}",
            mixed_many.advice
        );
        let ps_mixed = verdict(
            &[row("a", 4.0), row("b", 0.5)],
            crate::lang::Lang::Powershell,
            cd,
        );
        assert!(
            ps_mixed.advice.contains("Keep calling the original")
                && !ps_mixed.advice.contains("enable"),
            "{}",
            ps_mixed.advice
        );
        let go_mixed = verdict(&[row("a", 4.0), row("b", 0.5)], crate::lang::Lang::Go, cd);
        assert!(
            go_mixed.advice.contains("Keep calling the original")
                && !go_mixed.advice.contains("enable")
                && !go_mixed.advice.contains("bridge --keep")
                && go_mixed.advice.ends_with("b."),
            "{}",
            go_mixed.advice
        );
        assert!(
            verdict(&[row("a", 0.2), row("b", 0.3)], ts, cd)
                .advice
                .starts_with("Do not ship")
        );
        assert!(
            verdict(&[row("a", 0.5)], crate::lang::Lang::C, cd)
                .advice
                .starts_with("No call overhead")
        );
    }

    #[test]
    fn advice_singular_for_one_slower_or_tied_function() {
        let ts = crate::lang::Lang::Ts;
        let cd = std::path::Path::new("rust/unit-rs");
        // One slower function in C: names it, not "these"/"them".
        let c_one = verdict(&[row("add", 0.5)], crate::lang::Lang::C, cd);
        assert_eq!(
            c_one.advice,
            "No call overhead in C: add is slower as Rust code. Profile and optimize it, or keep it in C."
        );
        let c_many = verdict(
            &[row("add", 0.5), row("sub", 0.5)],
            crate::lang::Lang::C,
            cd,
        );
        assert!(
            c_many.advice.starts_with(
                "No call overhead in C: these are slower as Rust code. Profile and optimize them"
            ),
            "{}",
            c_many.advice
        );

        // One slower function mixed with a faster one: "the slower one" and "its callers".
        let mixed_one = verdict(&[row("a", 4.0), row("b", 0.5)], ts, cd);
        assert!(
            mixed_one.advice.contains("the slower one") && mixed_one.advice.contains("its callers"),
            "{}",
            mixed_one.advice
        );

        // A single function that only ties (no slower, not all faster) does not say "some".
        let tie_one = verdict(&[row("twice", 1.0)], ts, cd);
        assert_eq!(
            tie_one.advice,
            "Ship it: the function is not slower in Rust; it ties."
        );
        let tie_many = verdict(&[row("a", 3.0), row("b", 1.0)], ts, cd);
        assert_eq!(
            tie_many.advice,
            "Ship it: no function is slower in Rust; some only tie."
        );
    }

    #[test]
    fn advice_for_one_function_says_this_function() {
        let v = verdict(
            &[row("twice", 0.38)],
            crate::lang::Lang::Ts,
            std::path::Path::new("rust/unit-rs"),
        );
        assert!(
            v.advice.contains("this function together with its callers"),
            "{}",
            v.advice
        );
        assert!(!v.advice.contains("these functions"), "{}", v.advice);
    }

    #[test]
    fn speed_phrase_formats_faster_and_slower() {
        assert_eq!(speed_phrase(31.42), "31.4x faster");
        assert_eq!(speed_phrase(1.2), "1.2x faster");
        assert_eq!(speed_phrase(1.04), "1.04x faster");
        assert_eq!(speed_phrase(0.97), "1.03x slower");
        assert_eq!(speed_phrase(0.96), "1.04x slower");
        assert_eq!(speed_phrase(0.9), "1.1x slower");
        assert_eq!(speed_phrase(0.5), "2.0x slower");
        assert_eq!(speed_phrase(0.15), "6.7x slower");
        assert_eq!(speed_phrase(0.12), "8.3x slower");
    }
}

/// Parses one case line: recorded values (a pretty-printer's document trees) nest deeper than
/// serde_json's default limit of 128.
pub(crate) fn parse_deep(text: &str) -> serde_json::Result<Value> {
    let mut de = serde_json::Deserializer::from_str(text);
    de.disable_recursion_limit();
    let value = Value::deserialize(&mut de)?;
    de.end()?;
    Ok(value)
}