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.

191 KB
Raw Blame
//! Step 5: the definition of done for one port.
//!
//! fmt, clippy (warnings are errors), cargo tests, no unexplained `unsafe`, every function
//! ported, the built module exposes the original API, and the recorded behavior replays cleanly.

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

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::bridge::Manifest;
use crate::harness::{self, CASES, DiffOptions};
use crate::walk::Canonical;

#[derive(Debug, Serialize)]
pub struct Check {
    pub name: &'static str,
    pub passed: bool,
    pub detail: String,
    /// The next command or edit that clears a failed check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fix: Option<String>,
}

/// Recovery guidance when an outside tool failed to start (structured `SpawnError`).
fn spawn_fix(err: &anyhow::Error) -> Option<String> {
    let spawn = err.downcast_ref::<crate::process::SpawnError>()?;
    Some(if spawn.missing {
        match crate::doctor::missing_command(&spawn.program) {
            Some(install) if !install.contains('\n') => {
                format!(
                    "install `{}` with `{install}`, or run `rust-anything doctor`",
                    spawn.program
                )
            }
            _ => format!(
                "run `rust-anything doctor` for how to install `{}`",
                spawn.program
            ),
        }
    } else {
        "run `rust-anything doctor` and check that the build tool can run".into()
    })
}

/// The fix for a failed `batch` check, distinguishing execution errors from mismatches.
fn batch_fix(batches: &[crate::batch_check::BatchDiff], crate_dir: &Path) -> Option<String> {
    let failed: Vec<_> = batches.iter().filter(|b| !b.ok()).collect();
    if failed.is_empty() {
        return None;
    }
    let c = crate_dir.display();
    let q = crate::app::cli_path(crate_dir);
    let has_error = failed.iter().any(|b| b.error.is_some());
    let has_mismatch = failed
        .iter()
        .any(|b| b.error.is_none() && (b.failed > 0 || b.rank_failed > 0));
    let has_collision = failed.iter().any(|b| {
        b.error
            .as_deref()
            .is_some_and(|e| e.contains("not generated by rust-anything"))
    });
    Some(match (has_error, has_mismatch) {
        (true, false) if has_collision => format!(
            "move or rename {c}/{} so custom batch index checks can run, then `rust-anything gate {q}` again",
            crate::batch_check::TEST_FILE
        ),
        (true, false) => {
            format!("resolve the batch check error above, then `rust-anything gate {q}` again")
        }
        (true, true) => format!(
            "resolve the batch check error above and run `rust-anything diff {q}` to see each batch index mismatch"
        ),
        (false, _) => format!(
            "rust-anything diff {q} to see each batch index mismatch; fix the `Index` in src/port.rs"
        ),
    })
}

/// The fix for a failed check, by its name.
fn fix_for(check: &Check, crate_dir: &Path) -> Option<String> {
    let c = crate_dir.display();
    let q = crate::app::cli_path(crate_dir);
    let manifest = format!(
        "--manifest-path {}",
        crate::app::cli_path(format!("{c}/Cargo.toml"))
    );
    Some(match check.name {
        "fmt" => format!("cargo fmt {manifest}"),
        "clippy" => {
            format!("cargo clippy --all-targets {manifest} -- -D warnings, then fix each warning")
        }
        "cargo test" => format!("cargo test {manifest}"),
        "unsafe" => "add a `// SAFETY:` comment above each listed `unsafe`, or remove it".into(),
        "ported" => format!(
            "port the functions still stubbed in {c}/src/port.rs, then `rust-anything gate {q}` again"
        ),
        "size" => "use the crates `rust-anything analyze` lists and fold repeated code".into(),
        "literals" => "compute these values the way the original does; a constant the original \
                       takes from a library can stay with a `// recorded-literal: <reason>` \
                       comment (at most two, and gate prints that it was used)"
            .into(),
        "runtime" => {
            "compute the results in Rust: a port that starts the original, loads its code \
                      or reads the recording only repeats what it was shown"
                .into()
        }
        "accepted diffs" => format!(
            "read each entry of {c}/{}; if they are meant, run `rust-anything gate {q} \
             --accept-known-diffs <how many>` (entries added since the last passing gate, or, when \
             the entries accept more than a tenth of the cases, the number of cases they accept)",
            crate::recording::KNOWN_DIFFS
        ),
        "tests" => format!(
            "restore the removed tests or assertions; if the change is intended, delete \
             `{c}/{TESTS_BASELINE}` and run gate again"
        ),
        "build" => format!("fix the compile error above, then `rust-anything build {q}`"),
        "recording" => format!("rust-anything record {q}"),
        "behavior" if check.detail.contains("no recorded cases") => {
            format!("rust-anything record {q}")
        }
        "behavior" => format!(
            "rust-anything diff {q} to see each mismatch; fix the port, or list an intended difference in {}",
            crate::recording::KNOWN_DIFFS
        ),
        "batch" if check.detail.contains("not generated by rust-anything") => format!(
            "move or rename {c}/{} so custom batch index checks can run, then `rust-anything gate {q}` again",
            crate::batch_check::TEST_FILE
        ),
        "batch"
            if check.detail.contains("failed to run:")
                || check.detail.contains("Batch check failed:") =>
        {
            format!("resolve the batch check error above, then `rust-anything gate {q}` again")
        }
        "batch" => format!(
            "rust-anything diff {q} to see each batch index mismatch; fix the `Index` in src/port.rs"
        ),
        "known diffs" => format!(
            "remove the entries that no longer happen from {c}/{}",
            crate::recording::KNOWN_DIFFS
        ),
        "api" => {
            format!("export the missing functions from src/port.rs, then `rust-anything build {q}`")
        }
        "coverage" => format!(
            "rust-anything record {c} with an input for each export listed, or, from the repository, `rust-anything obligations waive <id>... --reason \"<why>\"` for one that needs no case"
        ),
        "error cases" | "panics" => {
            format!("rust-anything diff {q} to see the cases where the port's errors differ")
        }
        _ => return None,
    })
}

/// Bindings `bridge` writes into `src/`; everything else there is the port.
const GENERATED: [&str; 8] = [
    "lib.rs",
    "js.rs",
    "pinned.rs",
    "pyconv.rs",
    "pynum.rs",
    "rbconv.rs",
    "utf16.rs",
    "wire.rs",
];

/// How many times the source's lines the port may take before `gate` calls it bloated, plus a
/// fixed allowance for the imports and signatures every port has.
pub const MAX_GROWTH: f64 = 3.0;
const ALLOWANCE: f64 = 50.0;

fn files_under(path: &Path, extensions: &[&str]) -> Vec<std::path::PathBuf> {
    if path.is_file() {
        return vec![path.to_path_buf()];
    }
    crate::walk::builder(path)
        .build()
        .flatten()
        .map(ignore::DirEntry::into_path)
        .filter(|p| {
            p.extension()
                .is_some_and(|e| extensions.contains(&e.to_string_lossy().as_ref()))
        })
        .collect()
}

/// Lines of Rust in the port against lines of the source unit: a port several times larger
/// usually re-implements what a crate already does.
/// The unit's files and the repository files they import, directly or not: a port stands in
/// for all of them.
pub(crate) fn with_local_imports(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
    const TRIES: &[&str] = &[
        "",
        ".ts",
        ".tsx",
        ".mts",
        ".cts",
        ".js",
        ".mjs",
        ".cjs",
        "/index.ts",
        "/index.tsx",
        "/index.js",
        "/index.mjs",
    ];
    let resolve = |from: &Path, spec: &str| -> Option<PathBuf> {
        let base = from.parent()?.join(spec);
        let stem = base.with_extension("");
        let js_to_ts = matches!(
            base.extension().and_then(|e| e.to_str()),
            Some("js" | "mjs" | "cjs")
        );
        TRIES
            .iter()
            .map(|t| PathBuf::from(format!("{}{t}", base.display())))
            .chain(js_to_ts.then(|| stem.with_extension("ts")))
            .find(|p| p.is_file())
    };
    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 import in crate::ts::scan::scan(&file.to_string_lossy(), &text).imports {
            if !import.specifier.starts_with('.') || import.type_only {
                continue;
            }
            if let Some(found) = resolve(&file, &import.specifier)
                && found.starts_with(root)
                && !found.components().any(|c| c.as_os_str() == "node_modules")
                && seen.insert(found.clone())
            {
                todo.push(found);
            }
        }
    }
    seen.into_iter().collect()
}

/// The original's files a port stands for: the unit, plus what it imports (TS) or calls (C).
fn source_files(manifest: &Manifest) -> Vec<PathBuf> {
    let mut files = files_under(
        &manifest.root.join(&manifest.unit),
        manifest.language.extensions(),
    );
    if manifest.language == crate::lang::Lang::Ts {
        files = with_local_imports(&manifest.root, files);
    }
    if manifest.language == crate::lang::Lang::C {
        let ported: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
        files.extend(crate::lang::c::called_implementations(
            &manifest.root,
            &manifest.unit,
            &ported,
        ));
    }
    files
}

/// Every Rust file under `dir`, hidden folders and ignored files included (`src/.ignore` and
/// `.gitignore` do not hide a file from cargo, so they must not hide one from the guard), without
/// `target/` and version-control folders.
fn walk_rs(dir: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                if !matches!(
                    entry.file_name().to_str(),
                    Some("target" | ".git" | "node_modules")
                ) {
                    stack.push(path);
                }
            } else if path.extension().is_some_and(|e| e == "rs") {
                found.push(path);
            }
        }
    }
    found.sort();
    found
}

fn is_generated(crate_dir: &Path, path: &Path) -> bool {
    let Ok(rel) = path.strip_prefix(crate_dir.join("src")) else {
        return false;
    };
    let rel = rel.to_string_lossy().replace('\\', "/");
    rel == "port/pinned.rs" || (!rel.contains('/') && GENERATED.contains(&rel.as_str()))
}

/// The port's own Rust files under `src/`: everything but the generated bindings at their
/// exact generated locations.
fn port_files(crate_dir: &Path) -> Vec<PathBuf> {
    let mut files = walk_rs(&crate_dir.join("src"));
    files.retain(|p| !is_generated(crate_dir, p));
    files
}

/// Where compiled Rust other than tests can live: `src/`, a stray file next to `Cargo.toml`
/// (`#[path]` can include it) and `build.rs`; not `tests/`, `benches/` and `examples/`.
fn source_rs(crate_dir: &Path) -> Vec<PathBuf> {
    let mut files = walk_rs(crate_dir);
    files.retain(|p| {
        let rel = p.strip_prefix(crate_dir).unwrap_or(p);
        rel.components().count() == 1
            || !matches!(
                rel.components().next().and_then(|c| c.as_os_str().to_str()),
                Some("tests" | "benches" | "examples")
            )
    });
    files
}

fn size_check(crate_dir: &Path, manifest: &Manifest, notes: &mut Vec<String>) -> Option<Check> {
    let source: usize = source_files(manifest)
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .map(|t| crate::lang::syntax::loc(&t, manifest.language))
        .sum();
    if source == 0 {
        return None;
    }
    let rust: usize = port_files(crate_dir)
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .map(|t| crate::lang::syntax::code_lines(&t, &["//"]))
        .sum();
    let growth = rust as f64 / source as f64;
    let fits = |max: f64| rust as f64 <= max * source as f64 + ALLOWANCE;
    let head = format!(
        "{} of Rust for {} of {} ({growth:.1}x)",
        crate::report::count(rust, "line"),
        crate::report::count(source, "line"),
        manifest.language.name(),
    );
    let check = |passed: bool, detail: String| {
        Some(Check {
            fix: None,
            name: "size",
            passed,
            detail,
        })
    };
    if fits(MAX_GROWTH) {
        return check(true, head);
    }
    match crate::obligations::standing::size_allowance(&manifest.root, &manifest.unit) {
        Err(e) => check(
            false,
            format!("{head}; the size decisions could not be read: {e:#}"),
        ),
        Ok(Some(allowed)) if fits(allowed.max) => {
            notes.push(format!(
                "`size` passed at {growth:.1}x on {} of {}, which allows up to {}x: {}",
                allowed.adr,
                crate::obligations::standing::ADR_FILE,
                allowed.max,
                allowed.reason
            ));
            check(
                true,
                format!(
                    "{head}; allowed up to {}x by {}: {}",
                    allowed.max, allowed.adr, allowed.reason
                ),
            )
        }
        Ok(Some(allowed)) => check(
            false,
            format!(
                "{head}; over the {}x that {} allows",
                allowed.max, allowed.adr
            ),
        ),
        Ok(None) => check(
            false,
            format!(
                "{head}; over {MAX_GROWTH}x usually means code a crate already provides, or a \
                 case handled one by one"
            ),
        ),
    }
}

/// Files a port must never read: what it is checked against.
const RECORDING_FILES: [&str; 3] = [
    CASES,
    crate::recording::KNOWN_DIFFS,
    crate::recording::RECORDED_FROM,
];
/// Shorter strings (`"error"`, `"none"`) are too common to say anything.
const MIN_STRING: usize = 8;
/// Numbers with fewer significant digits are too common to say anything.
const MIN_DIGITS: usize = 5;
/// Recorded values hard-coded in the port before `literals` fails.
const LITERALS_FAIL: usize = 3;
/// Where `gate` keeps the test counts of the last passing run.
const TESTS_BASELINE: &str = ".rust-anything/tests.json";

/// Rust source without comments, string literals emptied, with the literals it holds.
#[derive(Default)]
struct Scan {
    code: String,
    strings: Vec<(usize, String)>,
    numbers: Vec<(usize, String)>,
    /// Lines with a `// recorded-literal: <reason>` comment.
    marked: BTreeSet<usize>,
    /// Lines with a `// recorded-literal:` comment that gives no reason: it exempts nothing.
    bare_marks: BTreeSet<usize>,
    /// Lines with a `// INFALLIBLE: <reason>` comment (a real comment, not text in a string).
    infallible: BTreeSet<usize>,
    /// `// INFALLIBLE:` comments with no reason, which excuse nothing.
    bare_infallible: BTreeSet<usize>,
}

/// Whether the text after a marker says why: some letters or digits, not an empty comment.
fn has_reason(text: &str) -> bool {
    text.chars().filter(|c| c.is_alphanumeric()).count() >= 3
}

fn starts(chars: &[char], i: usize, s: &str) -> bool {
    s.chars()
        .enumerate()
        .all(|(k, c)| chars.get(i + k) == Some(&c))
}

/// Splits Rust source into code, string literals (unescaped) and number literals (without `_`
/// or a type suffix, a leading `-` kept, hex, octal and binary read as their decimal value).
/// Lines in `code` are the source's own. With `skip_tests`, the items under `#[cfg(test)]` and
/// `#[test]` are left out of everything: they are not part of the port that runs. Only that item
/// is left out, never the rest of the file after it.
fn scan_rust(text: &str, skip_tests: bool) -> Scan {
    let mut scan = scan_all(text);
    if skip_tests {
        let ranges = test_ranges(&scan.code);
        if !ranges.is_empty() {
            let inside = |line: usize| ranges.iter().any(|(a, b)| (*a..=*b).contains(&line));
            scan.strings.retain(|(l, _)| !inside(*l));
            scan.numbers.retain(|(l, _)| !inside(*l));
            for set in [
                &mut scan.marked,
                &mut scan.bare_marks,
                &mut scan.infallible,
                &mut scan.bare_infallible,
            ] {
                set.retain(|l| !inside(*l));
            }
            scan.code = scan
                .code
                .split('\n')
                .enumerate()
                .map(|(i, l)| if inside(i + 1) { "" } else { l })
                .collect::<Vec<_>>()
                .join("\n");
        }
    }
    scan
}

/// The 1-based, inclusive line ranges of the items marked `#[cfg(test)]` or `#[test]` in `code`
/// (comments and strings already taken out): the attribute through the item's closing brace, or
/// its `;` for `use x;` and `mod tests;`.
fn test_ranges(code: &str) -> Vec<(usize, usize)> {
    let Ok(attr) = regex::Regex::new(r"#\s*\[\s*(?:cfg\s*\(\s*test\s*\)|test)\s*\]") else {
        return Vec::new();
    };
    let bytes = code.as_bytes();
    let line_of = |at: usize| 1 + bytes[..at].iter().filter(|b| **b == b'\n').count();
    let mut out: Vec<(usize, usize)> = Vec::new();
    for m in attr.find_iter(code) {
        if out
            .last()
            .is_some_and(|(_, end)| line_of(m.start()) <= *end)
        {
            continue;
        }
        let mut at = m.end();
        // More attributes may sit between this one and the item.
        loop {
            while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
                at += 1;
            }
            if bytes.get(at) == Some(&b'#') && bytes.get(at + 1) == Some(&b'[') {
                let mut depth = 0usize;
                while at < bytes.len() {
                    match bytes[at] {
                        b'[' => depth += 1,
                        b']' => {
                            depth = depth.saturating_sub(1);
                            if depth == 0 {
                                at += 1;
                                break;
                            }
                        }
                        _ => {}
                    }
                    at += 1;
                }
            } else {
                break;
            }
        }
        let (mut round, mut brace) = (0i32, 0i32);
        let mut end = bytes.len();
        for (k, b) in bytes.iter().enumerate().skip(at) {
            match b {
                b'(' | b'[' => round += 1,
                b')' | b']' => round -= 1,
                b'{' => brace += 1,
                b'}' => {
                    brace -= 1;
                    if brace == 0 && round <= 0 {
                        end = k;
                        break;
                    }
                }
                b';' if brace == 0 && round <= 0 => {
                    end = k;
                    break;
                }
                _ => {}
            }
        }
        out.push((
            line_of(m.start()),
            line_of(end.min(bytes.len().saturating_sub(1))),
        ));
    }
    out
}

fn scan_all(text: &str) -> Scan {
    let chars: Vec<char> = text.chars().collect();
    let ident = |c: char| c.is_alphanumeric() || c == '_';
    let digits = |chars: &[char], mut i: usize| {
        while chars
            .get(i)
            .is_some_and(|c| c.is_ascii_digit() || *c == '_')
        {
            i += 1;
        }
        i
    };
    let mut scan = Scan::default();
    let mut line = 1;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        let free = i == 0 || !ident(chars[i - 1]);
        if starts(&chars, i, "//") {
            let end = chars[i..]
                .iter()
                .position(|&c| c == '\n')
                .map_or(chars.len(), |p| i + p);
            let comment: String = chars[i..end].iter().collect();
            if let Some(at) = comment.find("recorded-literal:") {
                if has_reason(&comment[at + "recorded-literal:".len()..]) {
                    scan.marked.insert(line);
                } else {
                    scan.bare_marks.insert(line);
                }
            }
            if let Some(at) = comment.find(crate::error_paths::INFALLIBLE) {
                if has_reason(&comment[at + crate::error_paths::INFALLIBLE.len()..]) {
                    scan.infallible.insert(line);
                } else {
                    scan.bare_infallible.insert(line);
                }
            }
            i = end;
            continue;
        }
        if starts(&chars, i, "/*") {
            scan.code.push(' ');
            let mut depth = 0usize;
            while i < chars.len() {
                if starts(&chars, i, "/*") {
                    depth += 1;
                    i += 2;
                } else if starts(&chars, i, "*/") {
                    depth -= 1;
                    i += 2;
                    if depth == 0 {
                        break;
                    }
                } else {
                    if chars[i] == '\n' {
                        line += 1;
                        scan.code.push('\n');
                    }
                    i += 1;
                }
            }
            continue;
        }
        let raw = match c {
            'r' if free => Some(i + 1),
            'b' | 'c' if free && chars.get(i + 1) == Some(&'r') => Some(i + 2),
            _ => None,
        }
        .and_then(|j| {
            let hashes = chars[j..].iter().take_while(|&&h| h == '#').count();
            (chars.get(j + hashes) == Some(&'"')).then_some((j + hashes + 1, hashes))
        });
        if let Some((start, hashes)) = raw {
            let close = format!("\"{}", "#".repeat(hashes));
            let end = (start..chars.len())
                .find(|&k| starts(&chars, k, &close))
                .unwrap_or(chars.len());
            let value: String = chars[start..end].iter().collect();
            scan.strings.push((line, value.clone()));
            let lines = value.matches('\n').count();
            line += lines;
            scan.code.push_str("\"\"");
            scan.code.extend(std::iter::repeat_n('\n', lines));
            i = end + close.len();
            continue;
        }
        let quoted = if c == '"' {
            Some(i + 1)
        } else if free && matches!(c, 'b' | 'c') && chars.get(i + 1) == Some(&'"') {
            Some(i + 2)
        } else {
            None
        };
        if let Some(mut j) = quoted {
            let at = line;
            let mut value = String::new();
            while j < chars.len() && chars[j] != '"' {
                if chars[j] != '\\' {
                    if chars[j] == '\n' {
                        line += 1;
                    }
                    value.push(chars[j]);
                    j += 1;
                    continue;
                }
                let escaped = chars.get(j + 1).copied().unwrap_or('\\');
                j += 2;
                match escaped {
                    'n' => value.push('\n'),
                    't' => value.push('\t'),
                    'r' => value.push('\r'),
                    '0' => value.push('\0'),
                    'x' => {
                        let hex: String = chars[j..(j + 2).min(chars.len())].iter().collect();
                        value.extend(u8::from_str_radix(&hex, 16).ok().map(char::from));
                        j += 2;
                    }
                    'u' if chars.get(j) == Some(&'{') => {
                        let end = (j..chars.len())
                            .find(|&k| chars[k] == '}')
                            .unwrap_or(chars.len());
                        let hex: String = chars[j + 1..end].iter().filter(|c| **c != '_').collect();
                        value.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));
                        j = end + 1;
                    }
                    '\n' => {
                        line += 1;
                        while j < chars.len() && chars[j].is_whitespace() {
                            if chars[j] == '\n' {
                                line += 1;
                            }
                            j += 1;
                        }
                    }
                    other => value.push(other),
                }
            }
            scan.strings.push((at, value));
            scan.code.push_str("\"\"");
            scan.code.extend(std::iter::repeat_n('\n', line - at));
            i = j + 1;
            continue;
        }
        if c == '\'' {
            let end = if chars.get(i + 1) == Some(&'\\') {
                (i + 3..chars.len()).find(|&k| chars[k] == '\'')
            } else {
                (chars.get(i + 2) == Some(&'\'')).then_some(i + 2)
            };
            if let Some(end) = end {
                scan.code.push_str("' '");
                i = end + 1;
                continue;
            }
        }
        let after_range = i >= 2 && chars[i - 1] == '.' && chars[i - 2] == '.';
        if c.is_ascii_digit() && free && (i == 0 || chars[i - 1] != '.' || after_range) {
            let start = i;
            // `-5` is a negative literal, `a - 5` and `a-5` are subtractions: the minus belongs
            // to the number when what is before it cannot end an operand.
            let negative = {
                let mut k = start;
                while k > 0 && chars[k - 1] == ' ' {
                    k -= 1;
                }
                k > 0 && chars[k - 1] == '-' && {
                    let mut b = k - 1;
                    while b > 0 && chars[b - 1].is_whitespace() {
                        b -= 1;
                    }
                    b == 0
                        || !(ident(chars[b - 1]) || matches!(chars[b - 1], ')' | ']' | '"' | '\''))
                }
            };
            let sign = if negative { "-" } else { "" };
            if c == '0' && matches!(chars.get(i + 1), Some('x' | 'o' | 'b')) {
                let radix = match chars[i + 1] {
                    'x' => 16,
                    'o' => 8,
                    _ => 2,
                };
                while i < chars.len() && ident(chars[i]) {
                    i += 1;
                }
                scan.code.extend(&chars[start..i]);
                let digits: String = chars[start + 2..i]
                    .iter()
                    .filter(|c| **c != '_')
                    .take_while(|c| c.is_digit(radix))
                    .collect();
                if let Ok(v) = u128::from_str_radix(&digits, radix) {
                    scan.numbers.push((line, format!("{sign}{v}")));
                }
                continue;
            }
            i = digits(&chars, i);
            if chars.get(i) == Some(&'.') && chars.get(i + 1).is_some_and(char::is_ascii_digit) {
                i = digits(&chars, i + 1);
            }
            if matches!(chars.get(i), Some('e' | 'E')) {
                let sign = usize::from(matches!(chars.get(i + 1), Some('+' | '-')));
                if chars.get(i + 1 + sign).is_some_and(char::is_ascii_digit) {
                    i = digits(&chars, i + 1 + sign);
                }
            }
            let number: String = chars[start..i].iter().filter(|c| **c != '_').collect();
            while i < chars.len() && ident(chars[i]) {
                i += 1;
            }
            scan.code.extend(&chars[start..i]);
            scan.numbers.push((line, format!("{sign}{number}")));
            continue;
        }
        if c == '\n' {
            line += 1;
        }
        scan.code.push(c);
        i += 1;
    }
    scan
}

/// Digits of a number literal that carry information: no leading or trailing zeros.
fn significant_digits(number: &str) -> usize {
    let mantissa = number.split(['e', 'E']).next().unwrap_or(number);
    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
    digits.trim_start_matches('0').trim_end_matches('0').len()
}

/// Numbers any program may spell out: powers of two (and one off them), powers of ten, and the
/// float limits.
fn well_known(number: &str) -> bool {
    let number = number.strip_prefix('-').unwrap_or(number);
    if number.chars().all(|c| c.is_ascii_digit()) {
        let Ok(n) = number.parse::<u128>() else {
            return false;
        };
        let mut ten = n;
        while ten >= 10 && ten % 10 == 0 {
            ten /= 10;
        }
        return ten == 1
            || n == u128::MAX
            || [Some(n), n.checked_add(1), n.checked_sub(1)]
                .into_iter()
                .flatten()
                .any(u128::is_power_of_two);
    }
    let Ok(v) = number.parse::<f64>() else {
        return false;
    };
    [
        f64::MAX,
        f64::MIN_POSITIVE,
        f64::EPSILON,
        f64::from(f32::MAX),
        f64::from(f32::MIN_POSITIVE),
        f64::from(f32::EPSILON),
    ]
    .iter()
    .any(|k| ((v - k) / k).abs() < 1e-6)
}

/// Strings and numbers the recording holds, arguments and results alike.
#[derive(Default)]
struct Recorded {
    strings: HashSet<String>,
    numbers: HashSet<u64>,
}

impl Recorded {
    fn add(&mut self, value: &serde_json::Value) {
        match value {
            serde_json::Value::String(s) if s.chars().count() >= MIN_STRING => {
                self.strings.insert(s.clone());
            }
            serde_json::Value::Number(n) => {
                if let Some(f) = n.as_f64() {
                    self.numbers.insert((f + 0.0).to_bits());
                }
            }
            serde_json::Value::Array(items) => items.iter().for_each(|v| self.add(v)),
            serde_json::Value::Object(o) => o
                .iter()
                .filter(|(k, _)| !matches!(k.as_str(), "error" | "error_type"))
                .for_each(|(_, v)| self.add(v)),
            _ => {}
        }
    }
}

impl Recorded {
    /// How many distinct recorded numbers `text` spells out, leaving out short and well-known
    /// ones as `literals` does: a data file included into the port can be a table of results.
    fn numbers_in(&self, text: &str) -> usize {
        let Ok(re) = regex::Regex::new(r"-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?") else {
            return 0;
        };
        re.find_iter(text)
            .map(|m| m.as_str())
            .filter(|n| significant_digits(n) >= MIN_DIGITS && !well_known(n))
            .filter_map(|n| n.parse::<f64>().ok())
            .map(|v| (v + 0.0).to_bits())
            .filter(|bits| self.numbers.contains(bits))
            .collect::<HashSet<u64>>()
            .len()
    }
}

fn recorded_values(crate_dir: &Path) -> Option<Recorded> {
    let text = std::fs::read_to_string(crate_dir.join(CASES)).ok()?;
    let mut recorded = Recorded::default();
    for line in text.lines().filter(|l| !l.trim().is_empty()) {
        let Ok(serde_json::Value::Object(case)) = harness::parse_deep(line) else {
            continue;
        };
        for (key, value) in &case {
            if !matches!(
                key.as_str(),
                "fn" | "class" | "module" | "error" | "error_type"
            ) {
                recorded.add(value);
            }
        }
    }
    Some(recorded)
}

/// Strings of the recording that a run of string literals spells out together: `["hello", " world"]
/// .concat()`, `"a".to_owned() + "b"`, `concat!(..)`. Literals count as one run when only
/// separators and string conversions sit between them.
fn joined_runs(scan: &Scan) -> Vec<(usize, String)> {
    let Ok(glue) = regex::Regex::new(
        r"\.\s*(?:to_owned|to_string|into|concat|to_vec)\s*\(\s*\)|String\s*::\s*from\s*\(|concat\s*!|vec\s*!|[&+,\[\](){}\s]",
    ) else {
        return Vec::new();
    };
    let at: Vec<usize> = scan.code.match_indices("\"\"").map(|(i, _)| i).collect();
    if at.len() != scan.strings.len() {
        return Vec::new();
    }
    let linked = |k: usize| {
        let gap = &scan.code[at[k] + 2..at[k + 1]];
        glue.replace_all(gap, "").is_empty()
    };
    let mut out = Vec::new();
    let mut k = 0;
    while k + 1 < at.len() {
        if !linked(k) {
            k += 1;
            continue;
        }
        let mut end = k + 1;
        while end + 1 < at.len() && linked(end) {
            end += 1;
        }
        // Windows of up to six literals: a table of thousands never costs more than six joins each.
        for from in k..=end {
            let mut joined = scan.strings[from].1.clone();
            for to in from + 1..=end.min(from + 5) {
                joined.push_str(&scan.strings[to].1);
                out.push((scan.strings[from].0, joined.clone()));
            }
        }
        k = end + 1;
    }
    out
}

/// A format string as a pattern its output matches: `hello {}` and `hello {name:>5}` become
/// `^hello .*$`. `None` when it has no placeholder or too little fixed text to say anything.
fn format_pattern(s: &str) -> Option<(regex::Regex, String)> {
    if !s.contains('{') || s.len() > 400 {
        return None;
    }
    let mut pattern = String::from("^");
    let mut longest = String::new();
    let mut piece = String::new();
    let mut chars = s.chars().peekable();
    let mut holes = 0;
    while let Some(c) = chars.next() {
        match c {
            '{' if chars.peek() == Some(&'{') => {
                chars.next();
                piece.push('{');
            }
            '}' if chars.peek() == Some(&'}') => {
                chars.next();
                piece.push('}');
            }
            '{' => {
                for c in chars.by_ref() {
                    if c == '}' {
                        break;
                    }
                }
                pattern.push_str(&regex::escape(&piece));
                pattern.push_str("(?s:.*)");
                if piece.chars().count() > longest.chars().count() {
                    longest.clone_from(&piece);
                }
                piece.clear();
                holes += 1;
            }
            c => piece.push(c),
        }
    }
    pattern.push_str(&regex::escape(&piece));
    pattern.push('$');
    if piece.chars().count() > longest.chars().count() {
        longest = piece;
    }
    (holes > 0 && longest.chars().count() >= MIN_STRING)
        .then(|| regex::Regex::new(&pattern).ok().map(|re| (re, longest)))
        .flatten()
}

/// Recorded values written into the port as literals although the original never spells them
/// out: a port that answers the recorded cases from a table passes `diff` without porting
/// anything. Fails on `LITERALS_FAIL` or more, or on any read of the recording itself; fewer
/// pass with their names. A literal on a line with `// recorded-literal: <reason>` is left out,
/// but no more than `LITERALS_FAIL - 1` of them: a marker is an exception, not a way to a table.
/// Recorded error text is left out too: the runtime often writes it (`division by zero`), and the
/// port has to reproduce it. Negative and hex numbers, strings split over several literals and a
/// format string a recorded string matches count like the plain spellings; every file of the
/// crate is read, also the hidden and ignored ones, and everything but the `#[cfg(test)]` items.
pub fn literals_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
    let recorded = recorded_values(crate_dir)?;
    let original: String = source_files(manifest)
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let in_original = |text: &str| {
        original.contains(text)
            || serde_json::to_string(text)
                .is_ok_and(|j| original.contains(&j[1..j.len().saturating_sub(1)]))
    };
    let mut found: Vec<(String, String, String)> = Vec::new();
    let mut exempted: Vec<String> = Vec::new();
    let mut bare = 0usize;
    let mut reads = Vec::new();
    let mut templates = 0usize;
    for file in source_rs(crate_dir) {
        if is_generated(crate_dir, &file) {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let scan = scan_rust(&text, true);
        bare += scan.bare_marks.len();
        let name = file
            .strip_prefix(crate_dir)
            .unwrap_or(&file)
            .to_string_lossy()
            .replace('\\', "/");
        let mut note = |key: String, shown: String, line: usize| {
            if scan.marked.contains(&line) {
                if !exempted.contains(&key) {
                    exempted.push(key);
                }
            } else if !found.iter().any(|(k, _, _)| *k == key) {
                found.push((key, shown, format!("{name}:{line}")));
            }
        };
        let show = |s: &str| -> String {
            let shown: String = if s.chars().count() > 40 {
                s.chars().take(37).chain("...".chars()).collect()
            } else {
                s.to_string()
            };
            serde_json::to_string(&shown).unwrap_or_default()
        };
        for (line, s) in &scan.strings {
            if RECORDING_FILES.iter().any(|f| s.contains(f)) {
                reads.push(format!("{name}:{line}"));
            }
            if recorded.strings.contains(s) && !in_original(s) {
                note(format!("s{s}"), show(s), *line);
            }
            // One long literal that holds several recorded strings is a table parsed at run time.
            if s.chars().count() >= 60 {
                for r in recorded
                    .strings
                    .iter()
                    .filter(|r| r.len() < s.len() && s.contains(*r))
                {
                    if !in_original(r) {
                        note(format!("s{r}"), show(r), *line);
                    }
                }
            }
            // A format string a recorded string matches: `format!("hello {}", name)`.
            if templates < 2000
                && let Some((re, fixed)) = format_pattern(s)
            {
                templates += 1;
                if !in_original(&fixed)
                    && let Some(hit) = recorded
                        .strings
                        .iter()
                        .filter(|r| r.contains(&fixed) && re.is_match(r))
                        .min()
                {
                    note(format!("s{hit}"), show(hit), *line);
                }
            }
        }
        for (line, joined) in joined_runs(&scan) {
            if recorded.strings.contains(&joined) && !in_original(&joined) {
                note(format!("s{joined}"), show(&joined), line);
            }
        }
        for (line, n) in &scan.numbers {
            if significant_digits(n) < MIN_DIGITS || well_known(n) {
                continue;
            }
            let Ok(v) = n.parse::<f64>() else {
                continue;
            };
            let bits = (v + 0.0).to_bits();
            let unsigned = n.strip_prefix('-').unwrap_or(n);
            if recorded.numbers.contains(&bits) && !original.contains(unsigned) {
                note(format!("n{bits}"), n.clone(), *line);
            }
        }
    }
    let listed = found
        .iter()
        .take(5)
        .map(|(_, shown, at)| format!("{shown} ({at})"))
        .chain((found.len() > 5).then(|| format!("{} more", found.len() - 5)))
        .collect::<Vec<_>>()
        .join(", ");
    let exempt_note = if exempted.is_empty() {
        String::new()
    } else {
        format!(
            "; {} exempted by `// recorded-literal:` (the marker excuses at most {})",
            crate::report::count(exempted.len(), "value"),
            LITERALS_FAIL - 1
        )
    };
    let bare_note = if bare == 0 {
        String::new()
    } else {
        format!(
            "; {} of `// recorded-literal:` without a reason excuses nothing",
            crate::report::count(bare, "marker")
        )
    };
    let (passed, mut detail) = if !reads.is_empty() {
        (
            false,
            format!(
                "the port names the recording ({}) at {}: compute results, never look them up",
                RECORDING_FILES.join(", "),
                reads.join(", ")
            ),
        )
    } else if found.len() >= LITERALS_FAIL {
        (
            false,
            format!(
                "{} recorded values are written into the port, and the original spells out none \
                 of them: {listed}",
                found.len()
            ),
        )
    } else if exempted.len() >= LITERALS_FAIL {
        (
            false,
            format!(
                "{} recorded values are written into the port under `// recorded-literal:` \
                 markers, and the original spells out none of them: a marker excuses a constant \
                 the original takes from a library, not a table of results",
                exempted.len()
            ),
        )
    } else if !found.is_empty() {
        (
            true,
            format!(
                "{} written into the port that the original never spells out: {listed}; compute \
                 {} unless the original takes {} from a library (then mark the line \
                 `// recorded-literal: <reason>`)",
                crate::report::count(found.len(), "recorded value"),
                if found.len() == 1 { "it" } else { "them" },
                if found.len() == 1 { "it" } else { "them" },
            ),
        )
    } else {
        (true, "no recorded values written into the port".into())
    };
    detail.push_str(&exempt_note);
    detail.push_str(&bare_note);
    Some(Check {
        fix: None,
        name: "literals",
        passed,
        detail,
    })
}

/// Marks a line that starts a process because the original does: `// SPAWNS: <why>`.
pub const SPAWNS: &str = "SPAWNS:";

/// What in the original's source says it starts other programs. A port may start one only where
/// the original does, so the mark means nothing next to an original with none of these.
const ORIGINAL_SPAWNS: [&str; 18] = [
    "child_process",
    "execSync",
    "execFile",
    "subprocess",
    "os.system",
    "os.popen",
    "os.spawn",
    "os/exec",
    "exec.Command",
    "ProcessBuilder",
    "getRuntime().exec",
    "IO.popen",
    "Open3",
    "shell_exec",
    "proc_open",
    "Process.Start",
    "Start-Process",
    "popen(",
];

/// Where a port's code starts another program, as `(line, what)`: a `Command`, a shell helper
/// crate or libc's `system`, `fork` and `exec`. Comments, strings and `#[cfg(test)]` code are not
/// looked at.
fn spawn_sites(text: &str) -> Vec<(usize, &'static str)> {
    const PATTERNS: [(&str, &str); 7] = [
        (r"\bprocess\s*::\s*Command\b", "std::process::Command"),
        (
            r"\bprocess\s*::\s*\{[^}]*\bCommand\b",
            "std::process::Command",
        ),
        (r"\bCommand\s*::\s*new\s*\(", "Command::new"),
        (
            r"\b(?:tokio|async_std|smol)\s*::\s*process\b|\basync_process\b",
            "an async process crate",
        ),
        (
            r"\b(?:duct|xshell|cmd_lib|subprocess)\s*::",
            "a shell helper crate",
        ),
        (r"\bcmd!\s*\(", "a shell helper macro"),
        (
            r"\blibc\s*::\s*(?:system|fork|exec\w*|posix_spawn\w*)\b",
            "libc",
        ),
    ];
    let regexes: Vec<(regex::Regex, &str)> = PATTERNS
        .iter()
        .filter_map(|(re, what)| regex::Regex::new(re).ok().map(|re| (re, *what)))
        .collect();
    let raw: Vec<&str> = text.lines().collect();
    let scan = scan_rust(text, true);
    let mut out = Vec::new();
    for (i, code) in scan.code.lines().enumerate() {
        let Some((_, what)) = regexes.iter().find(|(re, _)| re.is_match(code)) else {
            continue;
        };
        let marked = raw.get(i).is_some_and(|l| l.contains(SPAWNS))
            || raw[..i.min(raw.len())]
                .iter()
                .rev()
                .take_while(|l| l.trim_start().starts_with("//"))
                .any(|l| l.contains(SPAWNS));
        if !marked {
            out.push((i + 1, *what));
        }
    }
    out
}

/// The places `text` starts a process that nothing excuses: a `// SPAWNS:` mark excuses a line
/// only where the original starts processes too.
fn unexcused_spawns(text: &str, original_spawns: bool) -> Vec<(usize, &'static str)> {
    if original_spawns {
        spawn_sites(text)
    } else {
        spawn_sites(&text.replace(SPAWNS, "marked:"))
    }
}

/// `spawns`: the port does not start other programs. A port that runs the original for its
/// answer passes every recorded case, and `diff` cannot tell: the answers are right. Starting a
/// process where the original does stays possible, marked `// SPAWNS: <why>`, and only counts
/// when the original's source starts processes too.
pub fn spawns_check(crate_dir: &Path, manifest: &Manifest) -> Check {
    let original: String = source_files(manifest)
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let original_spawns = ORIGINAL_SPAWNS.iter().any(|t| original.contains(t));
    let mut found = Vec::new();
    for file in port_files(crate_dir) {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let name = file
            .strip_prefix(crate_dir)
            .unwrap_or(&file)
            .to_string_lossy()
            .replace('\\', "/");
        let sites = unexcused_spawns(&text, original_spawns);
        found.extend(
            sites
                .into_iter()
                .map(|(line, what)| format!("{what} ({name}:{line})")),
        );
    }
    Check {
        fix: None,
        name: "spawns",
        passed: found.is_empty(),
        detail: if found.is_empty() {
            "the port starts no other program".into()
        } else {
            format!(
                "the port starts another program: {}. A port that runs the original for its \
                 answer is not a port. Where the original starts that process too, mark the \
                 line `// {SPAWNS} <why>`; that counts only when the original's source starts \
                 processes",
                found.join(", ")
            )
        },
    }
}

/// Tests and assertions in the crate (`src/` without the bindings, and `tests/`).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestCounts {
    #[serde(default)]
    pub tests: usize,
    #[serde(default)]
    pub asserts: usize,
    #[serde(default)]
    pub ignored: usize,
    #[serde(default)]
    pub should_panic: usize,
    /// Entries of `known-diffs.jsonl`; `None` in a baseline saved before they were counted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_diffs: Option<usize>,
    /// Recorded cases in `cases.jsonl` at the last passing gate: a recording may not shrink.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recorded_cases: Option<usize>,
    /// How many known differences someone accepted by name (`--accept-known-diffs`), so a
    /// recording that is mostly known differences passes again until it grows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_diffs_accepted: Option<usize>,
    /// How many dropped cases the last passing gate accepted (`--accept-dropped`), so `map`
    /// trusts the recording that gate passed on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dropped_accepted: Option<u64>,
}

pub fn test_counts(crate_dir: &Path) -> TestCounts {
    let patterns = [
        r"#\[\s*(?:\w+::)*test\s*\]",
        r"\b(?:debug_)?assert(?:_\w+)?!",
        r"#\[\s*ignore\b",
        r"#\[\s*should_panic\b",
    ]
    .map(|p| regex::Regex::new(p).ok());
    let tests = crate_dir.join("tests");
    let mut files = port_files(crate_dir);
    if tests.is_dir() {
        files.extend(
            walk_rs(&tests)
                .into_iter()
                .filter(|p| !crate::batch_check::is_generated_test(crate_dir, p)),
        );
    }
    let mut n = [0usize; 4];
    for file in files {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let code = scan_rust(&text, false).code;
        for (count, re) in n.iter_mut().zip(&patterns) {
            *count += re.as_ref().map_or(0, |re| re.find_iter(&code).count());
        }
    }
    let [tests, asserts, ignored, should_panic] = n;
    TestCounts {
        tests,
        asserts,
        ignored,
        should_panic,
        known_diffs: Some(known_diff_entries(crate_dir)),
        recorded_cases: {
            // `fuzz` and the held-out check put their own cases into `cases.jsonl` for a while
            // and put the recording back; count it when they are not in the middle of that.
            let _lock = crate_dir
                .join(CASES)
                .exists()
                .then(|| crate::fuzz::RecordingLock::take(crate_dir).ok())
                .flatten();
            std::fs::read_to_string(crate_dir.join(CASES))
                .ok()
                .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
        },
        known_diffs_accepted: None,
        dropped_accepted: None,
    }
}

fn known_diff_entries(crate_dir: &Path) -> usize {
    crate::recording::known_diffs(crate_dir).map_or(0, |e| e.len())
}

pub(crate) fn tests_baseline(crate_dir: &Path) -> Option<TestCounts> {
    std::fs::read_to_string(crate_dir.join(TESTS_BASELINE))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
}

/// Entries added to `known-diffs.jsonl` since the last passing gate: each one is a behavior
/// change, which reviewers can only tell from a regression when it lands apart from the port.
/// Without a baseline (a fresh clone: `.rust-anything/` is not committed) every entry counts as
/// added, so a list nobody has looked at cannot pass.
fn known_diffs_added(crate_dir: &Path) -> usize {
    let before = tests_baseline(crate_dir)
        .and_then(|b| b.known_diffs)
        .unwrap_or(0);
    known_diff_entries(crate_dir).saturating_sub(before)
}

/// What gate says about the cases a recording accepts through `known-diffs.jsonl`. The numbers
/// are cases the port answers differently from the original; each is a judgement a person made.
fn behavior_detail(passed: usize, total: usize, accepted: usize) -> String {
    if accepted == 0 {
        format!("{passed}/{total} recorded cases match")
    } else {
        format!(
            "{}/{total} recorded cases match exactly, {accepted} more accepted as known \
             differences ({})",
            passed - accepted.min(passed),
            crate::recording::KNOWN_DIFFS
        )
    }
}

/// The check that makes accepting known differences a decision: entries added since the last
/// passing gate, or more than a tenth of the cases, fail until someone names the number with
/// `--accept-known-diffs`.
fn accepted_diffs_check(
    crate_dir: &Path,
    accepted: usize,
    total: usize,
    opts: &GateOptions,
) -> Option<Check> {
    let entries = known_diff_entries(crate_dir);
    if entries == 0 {
        return None;
    }
    let baseline = tests_baseline(crate_dir);
    let added = known_diffs_added(crate_dir);
    let said = opts.accept_known_diffs.unwrap_or(0);
    let before = baseline
        .as_ref()
        .and_then(|b| b.known_diffs_accepted)
        .unwrap_or(0);
    let added_fails = added > said;
    let share_fails = accepted * 10 > total && accepted > said.max(before);
    let mut problems = Vec::new();
    if added_fails {
        problems.push(format!(
            "{} {} added to {} since the last passing gate{}: each one makes a case that differs \
             count as a match",
            added,
            if added == 1 {
                "entry was"
            } else {
                "entries were"
            },
            crate::recording::KNOWN_DIFFS,
            if baseline.is_none() {
                " (there is no baseline, so every entry counts)"
            } else {
                ""
            },
        ));
    }
    if share_fails {
        problems.push(format!(
            "{accepted} of {total} recorded cases ({}%) are accepted as known differences, more than a \
             tenth: that is a different port, not an intended change",
            accepted * 100 / total.max(1),
        ));
    }
    if !problems.is_empty() {
        let needed = match (added_fails, share_fails) {
            (true, true) => entries.max(accepted),
            (true, false) => entries,
            (false, true) => accepted,
            (false, false) => 0,
        };
        if let Some(last) = problems.last_mut() {
            last.push_str(&format!(
                "; read them, and if they are meant, run `rust-anything gate {} --accept-known-diffs {needed}`",
                crate::app::cli_path(crate_dir)
            ));
        }
    }
    let said_note = if said > 0 {
        format!("; {said} named by --accept-known-diffs")
    } else {
        String::new()
    };
    Some(Check {
        fix: None,
        name: "accepted diffs",
        passed: problems.is_empty(),
        detail: if problems.is_empty() {
            format!(
                "{accepted} of {total} cases accepted as known differences, {entries} {} in {}{said_note}",
                if entries == 1 { "entry" } else { "entries" },
                crate::recording::KNOWN_DIFFS
            )
        } else {
            problems.join("\n")
        },
    })
}

/// Saves the crate's test counts as the baseline the next `tests` check compares with.
pub fn save_tests_baseline(crate_dir: &Path) -> Result<()> {
    save_baseline(crate_dir, None, None)
}

/// The baseline with the number of known differences someone has accepted by name, and of
/// cases `record` dropped that the passing gate accepted (`--accept-dropped`).
fn save_baseline(
    crate_dir: &Path,
    accepted: Option<usize>,
    accepted_dropped: Option<u64>,
) -> Result<()> {
    let path = crate_dir.join(TESTS_BASELINE);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let mut counts = test_counts(crate_dir);
    counts.known_diffs_accepted = accepted.filter(|n| *n > 0);
    counts.dropped_accepted = accepted_dropped.filter(|n| *n > 0);
    std::fs::write(&path, serde_json::to_string_pretty(&counts)? + "\n")?;
    Ok(())
}

/// Fails when tests or assertions were removed, or tests ignored, since the last passing gate:
/// weakening the tests is not a way to pass.
pub fn tests_check(crate_dir: &Path) -> Check {
    let now = test_counts(crate_dir);
    let counts = format!(
        "{}, {}",
        crate::report::count(now.tests, "test"),
        crate::report::count(now.asserts, "assertion")
    );
    let Some(before) = tests_baseline(crate_dir) else {
        return Check {
            fix: None,
            name: "tests",
            passed: true,
            detail: format!("{counts}; saved as the baseline once gate passes"),
        };
    };
    let mut worse = Vec::new();
    if now.tests < before.tests {
        worse.push(format!("tests {} -> {}", before.tests, now.tests));
    }
    if now.asserts < before.asserts {
        worse.push(format!("assertions {} -> {}", before.asserts, now.asserts));
    }
    if now.ignored > before.ignored {
        worse.push(format!("ignored {} -> {}", before.ignored, now.ignored));
    }
    Check {
        fix: None,
        name: "tests",
        passed: worse.is_empty(),
        detail: if worse.is_empty() {
            format!("{counts}, none removed since the last passing gate")
        } else {
            format!("{} since the last passing gate", worse.join(", "))
        },
    }
}

#[derive(Debug, Default, Serialize)]
pub struct GateOutcome {
    #[serde(flatten)]
    pub stamp: crate::state::Stamp,
    pub passed: bool,
    /// The names of the checks that failed; a check's `name` is its stable id.
    pub failed: Vec<&'static str>,
    /// Recorded cases the behavior check matched, as numbers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub behavior: Option<crate::audit::Count>,
    pub checks: Vec<Check>,
    /// Recorded cases the behavior check matched, for the audit log.
    #[serde(skip)]
    pub cases: Option<(usize, usize)>,
    /// What the recorded cases were compared under: a float tolerance, key order ignored, known
    /// differences. Printed first in `text`, so a green gate never hides a loosened comparison.
    pub comparison: crate::recording::Loosening,
    /// What the verdict leaned on besides the checks: a legacy recording, an `--accept-*` flag,
    /// the `// recorded-literal:` and `// INFALLIBLE:` marks in the code. Also in the audit log.
    pub notes: Vec<String>,
}

/// What a caller says out loud to get past a check that fails closed. Each is printed in the
/// verdict and written to the audit log.
#[derive(Debug, Clone)]
pub struct GateOptions {
    /// `--accept-known-diffs N`: the caller has read the entries of `known-diffs.jsonl` (N of them).
    pub accept_known_diffs: Option<usize>,
    /// `--accept-smaller-recording`: the recording has fewer cases than at the last passing gate.
    pub accept_smaller_recording: bool,
    /// `--accept-dropped N`: `record` could not record N generated cases and the caller knows.
    pub accept_dropped: Option<u64>,
    /// Fresh inputs per function, and as many perturbed ones, the `held-out` check runs after
    /// `behavior` passes (`0` turns it off).
    pub held_out_cases: usize,
    /// `--held-out-seed N`: draw the held-out inputs from this seed, to replay a failure; the
    /// clock otherwise, on every run.
    pub held_out_seed: Option<u64>,
}

impl Default for GateOptions {
    fn default() -> Self {
        Self {
            accept_known_diffs: None,
            accept_smaller_recording: false,
            accept_dropped: None,
            held_out_cases: HELD_OUT_CASES,
            held_out_seed: None,
        }
    }
}

/// Format the text output for a `GateOutcome`. Every check's detail begins in the same
/// column by padding check names to the longest check name. The comparison settings and the
/// notes come first.
pub fn text(outcome: &GateOutcome) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(out, "{}", outcome.comparison.line());
    if let Some(line) = outcome.comparison.messages_line() {
        let _ = writeln!(out, "{line}");
    }
    for note in &outcome.notes {
        let _ = writeln!(out, "note: {note}");
    }
    let width = outcome
        .checks
        .iter()
        .map(|c| c.name.len())
        .max()
        .unwrap_or(0);
    for check in &outcome.checks {
        let mark = if check.passed { "pass" } else { "FAIL" };
        let first = check.detail.lines().next().unwrap_or_default();
        let _ = writeln!(out, "{mark}  {:<width$} {first}", check.name);
        if !check.passed {
            // Continuation lines start in the detail's column: the mark, two spaces, the
            // padded name and one space.
            let indent = " ".repeat(mark.len() + 2 + width + 1);
            for line in check.detail.lines().skip(1) {
                let _ = writeln!(out, "{indent}{line}");
            }
            if let Some(fix) = &check.fix {
                let _ = writeln!(out, "{indent}fix: {fix}");
            }
        }
    }
    let _ = writeln!(
        out,
        "{}",
        if outcome.passed {
            "Gate passed."
        } else {
            "Gate failed."
        }
    );
    out
}

/// Runs every check and appends the result to the repository's audit log.
static EVENTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// `gate --json-events`: print each check as one JSON line on stdout as soon as it is known,
/// so a long gate shows progress, then the whole result as a last `result` line.
pub fn set_events(on: bool) {
    EVENTS.store(on, std::sync::atomic::Ordering::Relaxed);
}

fn emit(crate_dir: &Path, checks: &[Check], sent: &mut usize) {
    if !EVENTS.load(std::sync::atomic::Ordering::Relaxed) {
        return;
    }
    let repo = crate::rules::repo_of(crate_dir);
    for c in checks.iter().skip(*sent) {
        let line = serde_json::json!({
            "event": "check",
            "name": c.name,
            "passed": c.passed,
            "detail": crate::state::relative_to_repo(&c.detail, &repo),
        });
        println!("{line}");
    }
    *sent = checks.len();
}

/// How many held-out inputs per function `gate` tries when nothing says otherwise.
pub const HELD_OUT_CASES: usize = 50;

pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
    gate_with(crate_dir, node_args, &GateOptions::default())
}

/// `gate` with what the caller accepts by name.
pub fn gate_with(
    crate_dir: &Path,
    node_args: &[String],
    opts: &GateOptions,
) -> Result<GateOutcome> {
    // A seed replays held-out inputs that `--held-out-cases 0` turns off: refuse the pair before
    // any check runs, so a seed left in a script never passes for a replay that did not happen.
    anyhow::ensure!(
        !(opts.held_out_cases == 0 && opts.held_out_seed.is_some()),
        "--held-out-seed replays held-out inputs, and --held-out-cases 0 turns them off: drop one"
    );
    let stamp = crate::state::Stamp::new(crate_dir, "gate");
    let mut outcome = run(crate_dir, node_args, opts)?;
    let repo = crate::rules::repo_of(crate_dir);
    for c in &mut outcome.checks {
        c.detail = crate::state::relative_to_repo(&c.detail, &repo);
        if let Some(fix) = &mut c.fix {
            *fix = crate::state::relative_to_repo(fix, &repo);
        }
    }
    outcome.failed = outcome
        .checks
        .iter()
        .filter(|c| !c.passed)
        .map(|c| c.name)
        .collect();
    outcome.behavior = outcome
        .cases
        .map(|(matched, total)| crate::audit::Count { matched, total });
    outcome.stamp = stamp;
    crate::audit::gate(crate_dir, &outcome);
    crate::state::save(crate_dir, crate::state::LAST_GATE, &outcome);
    Ok(outcome)
}

/// The app a unit crate was lifted into, when `app lift` has made `rust/app` pure Rust.
fn lifted_into(crate_dir: &Path) -> Option<String> {
    let repo = crate_dir.parent()?.parent()?;
    let state = crate::front_door::State::load(repo).ok()?;
    let name = crate_dir.file_name()?.to_str()?;
    (state.lifted && state.units.iter().any(|unit| unit.crate_name == name)).then_some(state.name)
}

/// The advice for each failed check that has none yet: the fix line `text` prints once. A gate
/// that returns without it leaves a failed check with no instruction at all.
fn add_fixes(checks: &mut [Check], crate_dir: &Path) {
    for check in checks.iter_mut().filter(|c| !c.passed && c.fix.is_none()) {
        check.fix = fix_for(check, crate_dir);
    }
}

/// What `app lift` leaves behind, read again: the flag in `rust/app/rust-anything.json` is a file
/// anyone can edit, so it is believed only while the app really has no way back to the original.
fn lifted_problems(crate_dir: &Path) -> Vec<String> {
    let Some(repo) = crate_dir.parent().and_then(Path::parent) else {
        return Vec::new();
    };
    let app = repo.join(crate::front_door::APP_DIR);
    let mut problems = Vec::new();
    if app.join("src/original.rs").exists() {
        problems.push(format!(
            "{}/src/original.rs still exists, so the app can still run the original: it is not lifted",
            crate::front_door::APP_DIR
        ));
    }
    if let Ok(units) = std::fs::read_dir(app.join("src/units")) {
        for e in units.flatten() {
            if std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")) {
                problems.push(format!(
                    "{} still hands cases to the original (`original::`): it is not lifted",
                    e.path().strip_prefix(repo).unwrap_or(&e.path()).display()
                ));
            }
        }
    }
    problems
}

/// The checks that read the port's source and the recording, with no build: they run for a
/// lifted unit too.
fn static_checks(
    crate_dir: &Path,
    manifest: &Manifest,
    checks: &mut Vec<Check>,
    notes: &mut Vec<String>,
) {
    checks.extend(size_check(crate_dir, manifest, notes));
    checks.extend(literals_check(crate_dir, manifest));
    checks.push(runtime_check(crate_dir, manifest));
    checks.push(spawns_check(crate_dir, manifest));
    checks.push(tests_check(crate_dir));
    let mut error_paths = crate::error_paths::checks(crate_dir, manifest);
    error_paths.retain(|c| c.name != "panics");
    checks.extend(error_paths);
    checks.push(panics_check(crate_dir, manifest));
    if tests_baseline(crate_dir).is_none() && passed_before(crate_dir, &manifest.crate_name) {
        notes.push(
            "the tests baseline is missing although this crate passed gate before: tests or \
             assertions removed since then are not noticed"
                .into(),
        );
    }
    let (literals, infallible) = marker_counts(crate_dir);
    if literals + infallible > 0 {
        notes.push(format!(
            "escape hatches in the code: {} of `// recorded-literal:`, {} of `// INFALLIBLE:`",
            literals, infallible
        ));
    }
}

/// Whether the audit log has a passing gate of this crate.
fn passed_before(crate_dir: &Path, crate_name: &str) -> bool {
    crate::audit::read(crate_dir).is_ok_and(|log| {
        log.entries.iter().any(|e| {
            e.change == "gate"
                && e.crate_name.as_deref() == Some(crate_name)
                && e.gate.as_ref().is_some_and(|g| g.passed)
        })
    })
}

/// What `enable` checks before it edits a source file: the checks of `gate` that need no build
/// and that a port can be made to pass by cheating, not by porting. `problems` stop a switch
/// (with `--force` they are printed and logged instead).
#[derive(Debug, Default, Clone, Serialize)]
pub struct Preflight {
    pub problems: Vec<String>,
    pub notes: Vec<String>,
}

/// `whole`: every export is going on, so every export needs a recorded case; with `--partial` or
/// `--only` the functions without one stay in the original (`select_matching` says which).
pub fn enable_preflight(crate_dir: &Path, manifest: &Manifest, whole: bool) -> Preflight {
    let mut pre = Preflight::default();
    if crate_dir.join(CASES).exists() {
        let verified = crate::recording::verify(
            crate_dir,
            manifest,
            crate::recording::VerifyOptions {
                per_export: whole,
                accept_dropped: None,
            },
        );
        pre.problems.extend(verified.problems);
        pre.notes.extend(verified.notes);
        if let Some(before) = tests_baseline(crate_dir).and_then(|b| b.recorded_cases)
            && verified.cases < before
        {
            pre.problems.push(format!(
                "the recording shrank: {before} cases at the last passing gate, {} now: run \
                 `rust-anything gate {}` (with --accept-smaller-recording if that is meant)",
                verified.cases,
                crate::app::cli_path(crate_dir)
            ));
        }
    }
    for check in [
        literals_check(crate_dir, manifest),
        Some(runtime_check(crate_dir, manifest)),
        Some(panics_check(crate_dir, manifest)),
    ]
    .into_iter()
    .flatten()
    {
        if !check.passed {
            pre.problems
                .push(format!("{}: {}", check.name, check.detail));
        }
    }
    let (literals, infallible) = marker_counts(crate_dir);
    if literals + infallible > 0 {
        pre.notes.push(format!(
            "escape hatches in the code: {literals} of `// recorded-literal:`, {infallible} of `// INFALLIBLE:`"
        ));
    }
    pre
}

/// Why the cases a diff accepted through `known-diffs.jsonl` stop a switch-on: more than a tenth
/// of the recorded cases, or not accepted by name at a gate yet.
pub fn known_diffs_problem(crate_dir: &Path, accepted: usize, total: usize) -> Option<String> {
    accepted_diffs_check(crate_dir, accepted, total, &GateOptions::default())
        .filter(|c| !c.passed)
        .map(|c| c.detail)
}

/// The recording's own check: it can be trusted (`recording::verify`), and it did not shrink
/// since the last passing gate.
fn recording_check(
    crate_dir: &Path,
    manifest: &Manifest,
    opts: &GateOptions,
    notes: &mut Vec<String>,
) -> Option<Check> {
    if !crate_dir.join(CASES).exists() {
        return None;
    }
    let verified = crate::recording::verify(
        crate_dir,
        manifest,
        crate::recording::VerifyOptions {
            per_export: true,
            accept_dropped: opts.accept_dropped,
        },
    );
    let mut problems = verified.problems.clone();
    if let Some(before) = tests_baseline(crate_dir).and_then(|b| b.recorded_cases)
        && verified.cases < before
    {
        if opts.accept_smaller_recording {
            notes.push(format!(
                "the recording has {} cases, {before} at the last passing gate: accepted with \
                 --accept-smaller-recording",
                verified.cases
            ));
        } else {
            problems.push(format!(
                "the recording shrank: {before} cases at the last passing gate, {} now. A port \
                 passes more easily against fewer cases; if the original really lost behavior, \
                 `rust-anything gate {} --accept-smaller-recording` says so in the verdict",
                verified.cases,
                crate::app::cli_path(crate_dir)
            ));
        }
    }
    if let Some(n) = verified.dropped.filter(|n| *n > 0 && problems.is_empty()) {
        notes.push(format!(
            "record could not record {n} generated cases: accepted with --accept-dropped"
        ));
    }
    notes.extend(verified.notes.iter().cloned());
    let how = match (verified.generated, verified.dropped) {
        (Some(g), Some(d)) => format!("; record generated {g} and dropped {d}"),
        _ => "; this recording does not say how many cases record dropped".to_string(),
    };
    Some(Check {
        fix: None,
        name: "recording",
        passed: problems.is_empty(),
        detail: if problems.is_empty() {
            format!(
                "{} recorded, unchanged since `record` wrote it, from an original that has not changed{}{how}",
                crate::report::count(verified.cases, "case"),
                if verified.legacy {
                    " (legacy recording: not verified)"
                } else {
                    ""
                }
            )
        } else {
            problems.join("\n")
        },
    })
}

fn lifted_checks(crate_dir: &Path, app: &str) -> Result<GateOutcome> {
    let target = crate::cache::target_for(crate_dir)?.dir;
    let mut checks =
        crate::batch_check::without_generated_test(crate_dir, || rust_checks(crate_dir, &target));
    checks.extend(lockfile_check(crate_dir));
    checks.extend(advisories_check(crate_dir));
    checks.push(ported_check(crate_dir));
    let mut notes = Vec::new();
    let mut ran = vec!["fmt", "clippy", "cargo test", "unsafe", "ported"];
    if let Ok(manifest) = Manifest::load(crate_dir) {
        static_checks(crate_dir, &manifest, &mut checks, &mut notes);
        ran.extend([
            "size",
            "literals",
            "runtime",
            "spawns",
            "tests",
            "error cases",
            "panics",
        ]);
        if let Some(c) = recording_check(crate_dir, &manifest, &GateOptions::default(), &mut notes)
        {
            ran.push("recording");
            checks.push(c);
        }
    }
    let problems = lifted_problems(crate_dir);
    checks.push(Check {
        fix: None,
        name: "lifted",
        passed: problems.is_empty(),
        detail: if problems.is_empty() {
            format!(
                "lifted into rust/app ({app}): its bindings are gone, so `build`, `api` and \
                 `behavior` did not run here. Ran: {}. What it does is checked by `rust-anything \
                 app replay` on the app's recorded cases, which gate does not run",
                ran.join(", ")
            )
        } else {
            problems.join("\n")
        },
    });
    add_fixes(&mut checks, crate_dir);
    let passed = checks.iter().all(|c| c.passed);
    if passed {
        save_tests_baseline(crate_dir)?;
    }
    Ok(GateOutcome {
        passed,
        checks,
        cases: None,
        comparison: crate::recording::Loosening::read(crate_dir),
        notes,
        ..GateOutcome::default()
    })
}

fn run(crate_dir: &Path, node_args: &[String], opts: &GateOptions) -> Result<GateOutcome> {
    let _lock = crate::fuzz::RecordingLock::take_recovered(crate_dir)?;
    if let Some(app) = lifted_into(crate_dir) {
        return lifted_checks(crate_dir, &app);
    }
    let manifest = Manifest::load(crate_dir)?;
    let lockfile = lockfile_check(crate_dir);
    let mut cases = None;
    let mut notes = Vec::new();
    let target = crate::cache::target_for(crate_dir)?.dir;
    let mut checks =
        crate::batch_check::without_generated_test(crate_dir, || rust_checks(crate_dir, &target));
    checks.extend(lockfile);
    checks.extend(advisories_check(crate_dir));
    checks.push(ported_check(crate_dir));
    let mut sent = 0;
    emit(crate_dir, &checks, &mut sent);

    static_checks(crate_dir, &manifest, &mut checks, &mut notes);
    emit(crate_dir, &checks, &mut sent);
    let built = harness::build(crate_dir);
    let built_ok = built.is_ok();
    let (build_detail, build_fix) = match built {
        Ok(path) => (format!("built {}", path.display()), None),
        Err(e) => (last_lines(&format!("{e:#}"), 15), spawn_fix(&e)),
    };
    checks.push(Check {
        fix: build_fix,
        name: "build",
        passed: built_ok,
        detail: build_detail,
    });
    emit(crate_dir, &checks, &mut sent);

    checks.extend(recording_check(crate_dir, &manifest, opts, &mut notes));

    checks.push(coverage_check(crate_dir, &manifest));

    let mut accepted_known = None;
    if !crate_dir.join(CASES).exists() {
        checks.push(Check {
            fix: None,
            name: "behavior",
            passed: false,
            detail: "no recorded cases: run `rust-anything record` first".into(),
        });
    } else if built_ok {
        match harness::diff(&DiffOptions {
            crate_dir,
            module: None,
            ignore_key_order: false,
            float_tolerance: None,
            node_args,
        }) {
            Ok(mut d) => {
                cases = Some((d.passed, d.total));
                checks.push(Check {
                    fix: None,
                    name: "api",
                    passed: d.missing.is_empty(),
                    detail: if d.missing.is_empty() {
                        format!(
                            "exports {}",
                            manifest
                                .exports
                                .iter()
                                .map(|f| f.name.clone())
                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
                                .collect::<Vec<_>>()
                                .join(", ")
                        )
                    } else {
                        format!("missing exports: {}", d.missing.join(", "))
                    },
                });
                checks.push(Check {
                    fix: None,
                    name: "behavior",
                    passed: d.failed == 0,
                    detail: behavior_detail(d.passed, d.total, d.accepted),
                });
                if !d.batches.is_empty() {
                    let passed = d.batches.iter().all(crate::batch_check::BatchDiff::ok);
                    checks.push(Check {
                        fix: (!passed)
                            .then(|| batch_fix(&d.batches, crate_dir))
                            .flatten(),
                        name: "batch",
                        passed,
                        detail: crate::batch_check::gate_detail(&d.batches),
                    });
                }
                if let Some(c) = accepted_diffs_check(crate_dir, d.accepted, d.total, opts) {
                    accepted_known = Some(
                        opts.accept_known_diffs.unwrap_or(0).max(
                            tests_baseline(crate_dir)
                                .and_then(|b| b.known_diffs_accepted)
                                .unwrap_or(0),
                        ),
                    );
                    if let Some(n) = opts.accept_known_diffs.filter(|_| c.passed) {
                        notes.push(format!(
                            "{n} known differences accepted with --accept-known-diffs"
                        ));
                    }
                    checks.push(c);
                }
                if d.failed == 0
                    && d.missing.is_empty()
                    && d.batches.iter().all(crate::batch_check::BatchDiff::ok)
                {
                    // The held-out check takes a while: show what is known first.
                    emit(crate_dir, &checks, &mut sent);
                    let mut used = Vec::new();
                    checks.push(held_out_check(
                        crate_dir,
                        &manifest,
                        opts.held_out_cases,
                        opts.held_out_seed,
                        node_args,
                        &mut used,
                    ));
                    d.stale_known.retain(|e| !used.contains(e));
                }
                if !d.stale_known.is_empty() {
                    checks.push(Check {
                        fix: None,
                        name: "known diffs",
                        passed: false,
                        detail: format!(
                            "{} entr{} of {} no longer differ{}: remove {}",
                            d.stale_known.len(),
                            if d.stale_known.len() == 1 { "y" } else { "ies" },
                            crate::recording::KNOWN_DIFFS,
                            if d.stale_known.len() == 1 { "s" } else { "" },
                            d.stale_known
                                .iter()
                                .map(crate::recording::entry_label)
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                    });
                }
            }
            Err(e) => checks.push(Check {
                fix: None,
                name: "behavior",
                passed: false,
                detail: format!("{e:#}"),
            }),
        }
    }

    add_fixes(&mut checks, crate_dir);
    emit(crate_dir, &checks, &mut sent);
    let passed = checks.iter().all(|c| c.passed);
    if passed {
        save_baseline(crate_dir, accepted_known, opts.accept_dropped)?;
    }
    Ok(GateOutcome {
        passed,
        checks,
        cases,
        comparison: crate::recording::Loosening::read(crate_dir),
        notes,
        ..GateOutcome::default()
    })
}

/// Inputs the recording does not hold: fresh ones from a seed taken from the clock (not saved)
/// and recorded arguments with one change each, run through the original and the port. `diff`
/// replays recorded cases, which a port can match by memorising them; this is what it cannot.
/// Skipped, with the reason as the detail, when it is off (`cases` is 0) or `fuzz` has not been
/// tested for the unit's language. The `known-diffs.jsonl` entries that explained a held-out
/// input go in `used_known`.
fn held_out_check(
    crate_dir: &Path,
    manifest: &Manifest,
    cases: usize,
    seed: Option<u64>,
    node_args: &[String],
    used_known: &mut Vec<serde_json::Value>,
) -> Check {
    let name = "held-out";
    let skipped = |detail: String| Check {
        fix: None,
        name,
        passed: true,
        detail,
    };
    if cases == 0 {
        return skipped(
            "off (--held-out-cases 0): only the recorded cases were checked, and a port that \
             matches them but not other inputs passes"
                .into(),
        );
    }
    if let Some(why) = crate::fuzz::unsupported(manifest.language, manifest.kind) {
        return skipped(format!("skipped: {why}"));
    }
    let started = std::time::Instant::now();
    let outcome = crate::fuzz::held_out(&crate::fuzz::HeldOutOptions {
        crate_dir,
        cases,
        seed,
        node_args,
    });
    let secs = started.elapsed().as_secs_f64();
    let outcome = match outcome {
        Ok(mut o) => {
            *used_known = std::mem::take(&mut o.used_known);
            o
        }
        Err(e) => {
            return Check {
                fix: None,
                name,
                passed: false,
                detail: format!("{} ({secs:.1}s)", last_lines(&format!("{e:#}"), 15)),
            };
        }
    };
    let (total, failed) = (outcome.total(), outcome.failed());
    // Calls outside the signature (a non-array for an array parameter) are not held-out inputs:
    // say how many were left out, so the verdict does not read as covering them.
    let left_out = if outcome.ill_typed == 0 {
        String::new()
    } else {
        format!(
            "; {} generated input{} outside the declared parameter types left out",
            outcome.ill_typed,
            if outcome.ill_typed == 1 { "" } else { "s" }
        )
    };
    if total == 0 {
        return skipped(format!(
            "nothing new to try ({secs:.1}s): every input it generated is already in the \
             recording, so only the recorded cases were checked{left_out}"
        ));
    }
    let explained = if outcome.accepted == 0 {
        String::new()
    } else {
        format!(
            ", {} accepted as known differences in {}",
            outcome.accepted,
            crate::recording::KNOWN_DIFFS
        )
    };
    if failed == 0 && outcome.missing.is_empty() {
        let matched = total - outcome.accepted.min(total);
        return skipped(if outcome.accepted == 0 {
            format!(
                "{} fresh and {} perturbed inputs match the original (seed {}, {secs:.1}s){left_out}",
                outcome.fresh, outcome.perturbed, outcome.seed
            )
        } else {
            format!(
                "{} fresh and {} perturbed inputs, {matched} match the original{explained} (seed {}, {secs:.1}s){left_out}",
                outcome.fresh, outcome.perturbed, outcome.seed
            )
        });
    }
    let show = |m: &serde_json::Value| {
        let args = m["args"]
            .as_array()
            .map(|a| {
                a.iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default();
        format!(
            "{}({args}): expected {}, got {}",
            m["fn"].as_str().unwrap_or_default(),
            m["expected"],
            m["actual"]
        )
    };
    let mut detail = match outcome.mismatches.first() {
        Some(m) => format!(
            "{failed} of {total} inputs the recording does not hold differ from the original; \
             shortest: {}",
            show(m)
        ),
        None => format!(
            "missing exports: {} ({secs:.1}s)",
            outcome.missing.join(", ")
        ),
    };
    detail.push_str(&format!(
        "\n{} of {} fresh and {} of {} perturbed inputs differ{explained} (seed {}, {secs:.1}s){left_out}",
        outcome.fresh_failed,
        outcome.fresh,
        outcome.perturbed_failed,
        outcome.perturbed,
        outcome.seed
    ));
    for m in outcome.mismatches.iter().skip(1).take(4) {
        detail.push_str(&format!("\nalso: {}", show(m)));
    }
    Check {
        fix: Some(format!(
            "make the port compute what the original computes: it matches the recorded cases and \
             not these inputs, which are drawn again on every gate. Replay this draw with \
             `rust-anything gate {dir} --held-out-seed {seed} --held-out-cases {cases}{node}`; \
             `rust-anything fuzz {dir} --seed {seed} --cases {cases} --keep{node}` adds the fresh \
             failures to the recording",
            dir = crate::app::quoted_cli_path(crate_dir),
            seed = outcome.seed,
            node = node_args
                .iter()
                .map(|a| format!(" {}", crate::app::shell_quote(&format!("--node-arg={a}"))))
                .collect::<String>(),
        )),
        name,
        passed: false,
        detail,
    }
}

/// How many lines carry a `// recorded-literal:` and a `// INFALLIBLE:` comment in the crate, for
/// the verdict: each is a place the guard was told to look away.
fn marker_counts(crate_dir: &Path) -> (usize, usize) {
    let (mut literals, mut infallible) = (0, 0);
    for file in source_rs(crate_dir) {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let scan = scan_rust(&text, true);
        literals += scan.marked.len();
        infallible += scan.infallible.len();
    }
    (literals, infallible)
}

/// `a/b/../c` as `a/c`, without touching the disk.
fn lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in path.components() {
        match c {
            std::path::Component::ParentDir => {
                if !out.pop() {
                    out.push("..");
                }
            }
            std::path::Component::CurDir => {}
            c => out.push(c.as_os_str()),
        }
    }
    out
}

/// What a source file does at run time that has no place in a port: runs a program, loads a
/// library, includes a file from outside the crate or one that holds the recording, or looks up
/// where its crate lives. A file of a path dependency also reaches into `dep_root`, its own crate,
/// and may not include the original's source (`original` are its extensions). `Err` findings fail
/// the gate; `warnings` are in test code only.
fn runtime_findings(
    file: &Path,
    crate_dir: &Path,
    dep_root: Option<&Path>,
    original: &[&str],
    scan: &Scan,
    recorded: Option<&Recorded>,
) -> Vec<String> {
    let at = |line: usize| {
        format!(
            "{}:{line}",
            file.strip_prefix(crate_dir)
                .unwrap_or(file)
                .to_string_lossy()
                .replace('\\', "/")
        )
    };
    let line_of = |pos: usize| 1 + scan.code[..pos].matches('\n').count();
    let mut found = Vec::new();
    let patterns = [
        (
            r"\bCommand\s*::\s*new\b|\bprocess\s*::\s*Command\b|\bposix_spawn\b|\bCreateProcess\w*\b",
            "starts a program",
        ),
        (
            r"\blibloading\b|\bdlopen\b|\bLoadLibrary\w*\b",
            "loads a library at run time",
        ),
    ];
    for (pattern, what) in patterns {
        if let Ok(re) = regex::Regex::new(pattern) {
            for m in re.find_iter(&scan.code) {
                found.push(format!("{} {what}", at(line_of(m.start()))));
            }
        }
    }
    // The nth `""` in the code is the nth string literal.
    let placeholders: Vec<usize> = scan.code.match_indices("\"\"").map(|(i, _)| i).collect();
    let literal_after = |end: usize| -> Option<&String> {
        let rest = &scan.code[end..];
        let skipped = rest.len() - rest.trim_start().len();
        if !rest.trim_start().starts_with("\"\"") {
            return None;
        }
        let n = placeholders.iter().position(|p| *p == end + skipped)?;
        scan.strings.get(n).map(|(_, s)| s)
    };
    let dir = file.parent().unwrap_or(crate_dir);
    let inside = |target: &Path| {
        target.starts_with(lexical(crate_dir)) || dep_root.is_some_and(|d| target.starts_with(d))
    };
    if let Ok(re) = regex::Regex::new(r"\b(include_str|include_bytes|include)\s*!\s*\(") {
        for m in re.captures_iter(&scan.code) {
            let whole = m.get(0).map_or(0, |w| w.end());
            let line = line_of(whole);
            let Some(arg) = literal_after(whole) else {
                found.push(format!(
                    "{} includes a file by a computed path (`{}!` of something other than a string)",
                    at(line),
                    &m[1]
                ));
                continue;
            };
            let target = lexical(&dir.join(arg));
            if !inside(&target) {
                found.push(format!(
                    "{} includes `{arg}`, a file outside the crate",
                    at(line)
                ));
            } else if target
                .extension()
                .is_some_and(|e| original.contains(&e.to_string_lossy().as_ref()))
            {
                found.push(format!(
                    "{} includes `{arg}`, source in the original's language",
                    at(line)
                ));
            } else if RECORDING_FILES.iter().any(|f| arg.ends_with(f)) || arg.ends_with(".jsonl") {
                found.push(format!("{} includes the recording (`{arg}`)", at(line)));
            } else if let (Some(recorded), Ok(bytes)) = (recorded, std::fs::read(&target)) {
                let text = String::from_utf8_lossy(&bytes);
                let held = recorded
                    .strings
                    .iter()
                    .filter(|r| text.contains(r.as_str()))
                    .count()
                    + recorded.numbers_in(&text);
                if held >= LITERALS_FAIL {
                    found.push(format!(
                        "{} includes `{arg}`, which holds {held} recorded values",
                        at(line)
                    ));
                }
            }
        }
    }
    if let Ok(re) = regex::Regex::new(r"#\s*\[\s*path\s*=\s*") {
        for m in re.find_iter(&scan.code) {
            if let Some(arg) = literal_after(m.end())
                && !inside(&lexical(&dir.join(arg)))
            {
                found.push(format!(
                    "{} takes a module from `{arg}`, outside the crate",
                    at(line_of(m.end()))
                ));
            }
        }
    }
    for (line, s) in &scan.strings {
        if matches!(
            s.as_str(),
            "CARGO_MANIFEST_DIR" | "RUST_ANYTHING_REPO" | "OUT_DIR"
        ) {
            found.push(format!(
                "{} looks up where the crate or its repository lives (`{s}`)",
                at(*line)
            ));
        }
    }
    found
}

/// The dependencies the port's `Cargo.toml` pulls in from outside the registry or runs at build
/// time: a path dependency is part of the port and is read like it, a build script that is not
/// the one `bridge` writes, an extra build dependency and a procedural macro run code at build
/// time.
fn cargo_findings(crate_dir: &Path) -> (Vec<String>, Vec<String>, Vec<PathBuf>) {
    let (mut found, mut notes, mut paths) = (Vec::new(), Vec::new(), Vec::new());
    let Ok(text) = std::fs::read_to_string(crate_dir.join("Cargo.toml")) else {
        return (found, notes, paths);
    };
    let Ok(doc) = text.parse::<toml_edit::DocumentMut>() else {
        found.push("Cargo.toml cannot be read".into());
        return (found, notes, paths);
    };
    if doc
        .get("lib")
        .and_then(|l| l.get("proc-macro"))
        .and_then(|p| p.as_bool())
        == Some(true)
    {
        found.push(
            "Cargo.toml: the crate is a procedural macro, which runs code at build time".into(),
        );
    }
    if let Some(table) = doc
        .get("build-dependencies")
        .and_then(|t| t.as_table_like())
    {
        for (name, _) in table.iter() {
            if name != "napi-build" {
                found.push(format!(
                    "Cargo.toml: build dependency `{name}` (only `napi-build`, which `bridge` adds, is expected)"
                ));
            }
        }
    }
    for section in ["dependencies", "dev-dependencies"] {
        let Some(table) = doc.get(section).and_then(|t| t.as_table_like()) else {
            continue;
        };
        for (name, dep) in table.iter() {
            let Some(dep) = dep.as_table_like() else {
                continue;
            };
            if let Some(path) = dep.get("path").and_then(|p| p.as_str()) {
                paths.push(lexical(&crate_dir.join(path)));
                notes.push(format!(
                    "path dependency `{name}` ({path}) is read like the port"
                ));
            } else if dep.get("git").is_some() {
                notes.push(format!(
                    "git dependency `{name}`: its code is not from the registry"
                ));
            }
        }
    }
    if let Ok(build) = std::fs::read_to_string(crate_dir.join("build.rs")) {
        let norm = |t: &str| t.split_whitespace().collect::<String>();
        let generated = [
            crate::bridge::DYNAMIC_LOOKUP_BUILD_RS,
            "fn main() {\n    napi_build::setup();\n}\n",
        ];
        if !generated.iter().any(|g| norm(g) == norm(&build)) {
            found.push(
                "build.rs is not the one `bridge` writes: a build script runs code at build time"
                    .into(),
            );
        }
    }
    (found, notes, paths)
}

/// The port runs no program, loads no library and includes nothing from outside its crate or from
/// the recording; a build script, an extra build dependency and a procedural macro are the
/// bridge's own or absent. Path dependencies are read the same way, each from its own crate
/// unless that crate holds the bridged one or the original unit; none of them may include the
/// original's source. In test code the same things only warn.
pub fn runtime_check(crate_dir: &Path, manifest: &Manifest) -> Check {
    let recorded = recorded_values(crate_dir);
    let (mut found, mut notes, deps) = cargo_findings(crate_dir);
    let real = |p: &Path| p.canonical().unwrap_or_else(|_| lexical(p));
    let (bridged, unit) = (real(crate_dir), real(&manifest.root.join(&manifest.unit)));
    let mut files: Vec<(PathBuf, bool, Option<PathBuf>)> = walk_rs(crate_dir)
        .into_iter()
        .map(|f| (f, false, None))
        .collect();
    let mut seen_deps = BTreeSet::new();
    let mut queue = deps;
    while let Some(dep) = queue.pop() {
        if !seen_deps.insert(dep.clone()) || seen_deps.len() > 20 {
            continue;
        }
        let own = !bridged.starts_with(real(&dep)) && !unit.starts_with(real(&dep));
        files.extend(
            walk_rs(&dep.join("src"))
                .into_iter()
                .map(|f| (f, true, own.then(|| dep.clone()))),
        );
        if dep.join("build.rs").exists() {
            found.push(format!(
                "path dependency {} has a build.rs: a build script runs code at build time",
                dep.display()
            ));
        }
    }
    let mut tests_only = 0usize;
    for (file, in_dep, dep_root) in files {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let in_crate = file.starts_with(crate_dir);
        let rel = file.strip_prefix(crate_dir).unwrap_or(&file);
        let is_test_file = in_crate
            && rel.components().count() > 1
            && matches!(
                rel.components().next().and_then(|c| c.as_os_str().to_str()),
                Some("tests" | "benches" | "examples")
            );
        let scan = scan_rust(&text, true);
        let original = if in_dep {
            manifest.language.extensions()
        } else {
            &[]
        };
        let all = runtime_findings(
            &file,
            crate_dir,
            dep_root.as_deref(),
            original,
            &scan,
            recorded.as_ref(),
        );
        if is_test_file {
            tests_only += all.len();
        } else {
            found.extend(all);
        }
    }
    if tests_only > 0 {
        notes.push(format!(
            "{} in tests/, benches/ or examples/ (not part of the port that runs)",
            crate::report::count(tests_only, "such use")
        ));
    }
    found.sort();
    found.dedup();
    let passed = found.is_empty();
    let mut detail = if passed {
        "no program started, no library loaded, no file included from outside the crate or from the recording".to_string()
    } else {
        format!(
            "the port must compute its results itself, not run or read the original or the recording:\n{}",
            found.join("\n")
        )
    };
    if !notes.is_empty() {
        let first = detail.split('\n').next().unwrap_or_default().to_string();
        detail = if passed {
            format!("{first}; {}", notes.join("; "))
        } else {
            format!("{detail}\n{}", notes.join("\n"))
        };
    }
    Check {
        fix: None,
        name: "runtime",
        passed,
        detail,
    }
}

/// A function of the port: where its body is in the code and what it calls by name.
struct FnSpan {
    name: String,
    from: usize,
    to: usize,
    calls: BTreeSet<String>,
}

fn functions(code: &str) -> Vec<FnSpan> {
    let (Ok(decl), Ok(call)) = (
        regex::Regex::new(r"\bfn\s+([A-Za-z_]\w*)"),
        regex::Regex::new(r"\b([A-Za-z_]\w*)\s*(?:::\s*<[^>]*>\s*)?\("),
    ) else {
        return Vec::new();
    };
    let bytes = code.as_bytes();
    let mut out = Vec::new();
    for m in decl.captures_iter(code) {
        let name = m[1].to_string();
        let mut at = m.get(0).map_or(0, |w| w.end());
        let mut round = 0i32;
        let mut open = None;
        while at < bytes.len() {
            match bytes[at] {
                b'(' | b'[' => round += 1,
                b')' | b']' => round -= 1,
                b'{' if round <= 0 => {
                    open = Some(at);
                    break;
                }
                b';' if round <= 0 => break,
                _ => {}
            }
            at += 1;
        }
        let Some(open) = open else { continue };
        let mut depth = 0i32;
        let mut close = bytes.len();
        for (k, b) in bytes.iter().enumerate().skip(open) {
            match b {
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        close = k;
                        break;
                    }
                }
                _ => {}
            }
        }
        let calls = call
            .captures_iter(&code[open..close.min(code.len())])
            .map(|c| c[1].to_string())
            .filter(|n| *n != name)
            .collect();
        out.push(FnSpan {
            name,
            from: open,
            to: close,
            calls,
        });
    }
    out
}

/// A panic in the port: `unwrap`, `expect` and the panicking macros, in a function an export
/// that fails in the original reaches.
#[derive(Debug, PartialEq, Eq)]
struct PanicSite {
    file: String,
    line: usize,
    what: &'static str,
    function: String,
    /// The failing export that reaches it.
    from: String,
}

/// Panics in `files` that a function named in `failing` reaches, and how many `// INFALLIBLE:`
/// reasons excused some. A panic is excused by a comment with a reason on its line or in the
/// comment lines directly above; text in a string, `#[cfg(test)]` items, and a `//` inside a
/// literal do not change what is code.
fn panic_sites(
    files: &[(String, String)],
    failing: &BTreeSet<String>,
) -> (Vec<PanicSite>, usize, usize) {
    let Ok(sites) = regex::Regex::new(
        r"\.\s*unwrap\s*\(\s*\)|\.\s*expect\s*\(|\b(?:panic|unreachable|todo|unimplemented)\s*!\s*[(\[{]",
    ) else {
        return (Vec::new(), 0, 0);
    };
    struct Parsed {
        name: String,
        text: String,
        scan: Scan,
        fns: Vec<FnSpan>,
    }
    let parsed: Vec<Parsed> = files
        .iter()
        .map(|(name, text)| {
            let scan = scan_rust(text, true);
            let fns = functions(&scan.code);
            Parsed {
                name: name.clone(),
                text: text.clone(),
                scan,
                fns,
            }
        })
        .collect();
    // Which function each export-level name leads to, through the calls between the port's
    // functions (by name: a method and a function of one name are one node, which errs towards
    // reporting).
    let mut calls: std::collections::BTreeMap<&str, BTreeSet<&str>> =
        std::collections::BTreeMap::new();
    for p in &parsed {
        for f in &p.fns {
            calls
                .entry(f.name.as_str())
                .or_default()
                .extend(f.calls.iter().map(String::as_str));
        }
    }
    let mut reached: std::collections::BTreeMap<&str, &str> = std::collections::BTreeMap::new();
    for entry in failing {
        let mut todo = vec![entry.as_str()];
        while let Some(name) = todo.pop() {
            if reached.contains_key(name) {
                continue;
            }
            reached.insert(name, entry.as_str());
            if let Some(next) = calls.get(name) {
                todo.extend(next.iter().copied());
            }
        }
    }
    let (mut out, mut excused, mut bare) = (Vec::new(), 0usize, 0usize);
    for p in &parsed {
        let lines: Vec<&str> = p.text.lines().collect();
        for m in sites.find_iter(&p.scan.code) {
            let line = 1 + p.scan.code[..m.start()].matches('\n').count();
            let at = m.start();
            let Some(f) = p
                .fns
                .iter()
                .filter(|f| f.from <= at && at <= f.to)
                .min_by_key(|f| f.to - f.from)
            else {
                continue;
            };
            let Some(from) = reached.get(f.name.as_str()) else {
                continue;
            };
            let in_comments_above = (1..line).rev().map_while(|l| {
                lines
                    .get(l - 1)
                    .filter(|t| t.trim_start().starts_with("//"))
                    .map(|_| l)
            });
            let marked = p.scan.infallible.contains(&line)
                || in_comments_above
                    .clone()
                    .any(|l| p.scan.infallible.contains(&l));
            if marked {
                excused += 1;
                continue;
            }
            if p.scan.bare_infallible.contains(&line)
                || in_comments_above
                    .clone()
                    .any(|l| p.scan.bare_infallible.contains(&l))
            {
                bare += 1;
            }
            let what = [
                (".unwrap", ".unwrap()"),
                (".expect", ".expect("),
                ("panic", "panic!("),
                ("unreachable", "unreachable!("),
                ("todo", "todo!("),
                ("unimplemented", "unimplemented!("),
            ]
            .iter()
            .find(|(k, _)| {
                let s: String = m.as_str().split_whitespace().collect();
                s.starts_with(k)
            })
            .map_or("panic", |(_, w)| w);
            out.push(PanicSite {
                file: p.name.clone(),
                line,
                what,
                function: f.name.clone(),
                from: (*from).to_string(),
            });
        }
    }
    (out, excused, bare)
}

/// The `panics` check: where the original fails, the port returns an error too. Read from the
/// code of every port file, so a `#[cfg(test)]` line, a `//` inside a string or a panic in a helper
/// the failing export calls changes nothing; every `// INFALLIBLE:` that excuses one is counted.
pub fn panics_check(crate_dir: &Path, manifest: &Manifest) -> Check {
    let exports: Vec<(String, String, u32)> = manifest
        .exports
        .iter()
        .map(|f| (f.name.clone(), f.file.clone(), f.line))
        .collect();
    let raised = crate::error_paths::raises(manifest.language, &manifest.root, &exports);
    let cases = std::fs::read_to_string(crate_dir.join(CASES)).unwrap_or_default();
    let failed = crate::error_paths::recorded_errors(&cases);
    let failing: BTreeSet<String> = manifest
        .exports
        .iter()
        .filter(|f| failed.contains(&f.name) || raised.iter().any(|r| r.export == f.name))
        .map(|f| crate::bridge::snake_case(&f.name))
        .collect();
    let files: Vec<(String, String)> = port_files(crate_dir)
        .iter()
        .filter_map(|p| {
            Some((
                p.strip_prefix(crate_dir)
                    .unwrap_or(p)
                    .to_string_lossy()
                    .replace('\\', "/"),
                std::fs::read_to_string(p).ok()?,
            ))
        })
        .collect();
    let (bad, excused, bare) = panic_sites(&files, &failing);
    let marks = match (excused, bare) {
        (0, 0) => String::new(),
        (n, 0) => format!(" ({n} excused by `// INFALLIBLE:`)"),
        (n, b) => format!(
            " ({n} excused by `// INFALLIBLE:`; {b} such comments give no reason and excuse nothing)"
        ),
    };
    Check {
        fix: None,
        name: "panics",
        passed: bad.is_empty(),
        detail: if bad.is_empty() {
            format!("no unwrap, expect or panic where the original returns an error{marks}")
        } else {
            format!(
                "the original returns an error here, so the port must too (return Err), or mark a state the original also treats as impossible with `// {} <why>`{marks}\n{}",
                crate::error_paths::INFALLIBLE,
                bad.iter()
                    .map(|p| format!(
                        "{}:{} `{}` in {}{}",
                        p.file,
                        p.line,
                        p.what,
                        p.function,
                        if p.function == p.from {
                            String::new()
                        } else {
                            format!(" (called from {})", p.from)
                        }
                    ))
                    .collect::<Vec<_>>()
                    .join("\n")
            )
        },
    }
}

/// How many exports without a case the detail of `coverage` names before it counts the rest.
const COVERAGE_LISTED: usize = 20;

/// Every export the bridge lists (functions, classes, methods; not `js_only`) needs a recorded
/// case in `cases.jsonl`, unless the repository's decisions waive its obligation. "Has a case" is
/// decided by the code the evidence rules `unit-fn`, `unit-class` and `unit-method` use, so the
/// gate and `obligations --evidence` cannot disagree. The line about which source lines the
/// recording covered stays in the detail.
fn coverage_check(crate_dir: &Path, manifest: &Manifest) -> Check {
    use crate::obligations::evidence::{exports_without_case, parse_cases};
    let line = crate::recording::saved_coverage(crate_dir)
        .and_then(|c| crate::recording::coverage_line(&c));
    let with_line = |text: String| match &line {
        Some(l) => format!("{l}; {text}"),
        None => text,
    };
    let mut waived = match crate::obligations::standing::waived_ids(&manifest.root) {
        Ok(ids) => ids,
        Err(e) => {
            return Check {
                fix: None,
                name: "coverage",
                passed: false,
                detail: with_line(format!("the waived obligations could not be read: {e:#}")),
            };
        }
    };
    if manifest
        .root
        .join(crate::obligations::evidence::BINDINGS_FILE)
        .exists()
    {
        match crate::obligations::standing::standing_and_bound(&manifest.root) {
            Ok((_, bound)) => waived.extend(bound),
            Err(e) => {
                return Check {
                    fix: None,
                    name: "coverage",
                    passed: false,
                    detail: with_line(format!(
                        "the obligations bound by hand could not be read: {e:#}"
                    )),
                };
            }
        }
    }
    // The cases are read under the same guard as every other file of the repository, relative to
    // the crate folder: a link that leaves it or a file that is not ordinary fails the check with
    // the reason, instead of reading as "no cases" (which would then look like missing exports).
    use crate::obligations::evidence::{Opened, open};
    let guard_root = crate_dir
        .canonicalize()
        .unwrap_or_else(|_| crate_dir.to_path_buf());
    let text = match open(&guard_root, CASES) {
        Opened::Absent => String::new(),
        Opened::Text(text) => text,
        Opened::Refused(why) => {
            return Check {
                fix: None,
                name: "coverage",
                passed: false,
                detail: with_line(format!("{CASES} is not opened: {why}")),
            };
        }
    };
    let missing: Vec<_> = exports_without_case(manifest, &parse_cases(&text))
        .into_iter()
        .filter(|u| !waived.contains(&u.id))
        .collect();
    if missing.is_empty() {
        return Check {
            fix: None,
            name: "coverage",
            passed: true,
            detail: line.unwrap_or_else(|| "every export has a recorded case".into()),
        };
    }
    let mut named: Vec<String> = missing
        .iter()
        .take(COVERAGE_LISTED)
        .map(|u| u.id.clone())
        .collect();
    if missing.len() > COVERAGE_LISTED {
        named.push(format!("and {} more", missing.len() - COVERAGE_LISTED));
    }
    Check {
        fix: None,
        name: "coverage",
        passed: false,
        detail: with_line(format!(
            "{} of the unit's exports {} no recorded case: {}",
            missing.len(),
            if missing.len() == 1 { "has" } else { "have" },
            named.join(", ")
        )),
    }
}

fn lockfile_check(crate_dir: &Path) -> Option<Check> {
    if !crate_dir.join("Cargo.lock").exists() {
        return Some(Check {
            fix: None,
            name: "lockfile",
            passed: true,
            detail: "warning: no Cargo.lock yet; keep the one the build writes, so builds are reproducible".into(),
        });
    }
    let mut cmd = Command::new("cargo");
    cmd.args([
        "metadata",
        "--locked",
        "--offline",
        "--format-version",
        "1",
        "--manifest-path",
    ])
    .arg(crate_dir.join("Cargo.toml"));
    let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
    let stderr = String::from_utf8_lossy(&out.stderr);
    let stale = !out.status.success() && stderr.contains("--locked");
    Some(Check {
        fix: None,
        name: "lockfile",
        passed: true,
        detail: if stale {
            "warning: Cargo.lock is out of date with Cargo.toml; keep the refreshed one the build wrote".into()
        } else {
            "Cargo.lock matches Cargo.toml".into()
        },
    })
}

fn advisories_check(crate_dir: &Path) -> Option<Check> {
    let manifest = crate_dir.join("Cargo.toml");
    let attempts: [(&str, Vec<std::ffi::OsString>); 2] = [
        (
            "cargo-deny",
            vec![
                "deny".into(),
                "--manifest-path".into(),
                manifest.clone().into(),
                "check".into(),
                "advisories".into(),
            ],
        ),
        (
            "cargo-audit",
            vec![
                "audit".into(),
                "--file".into(),
                crate_dir.join("Cargo.lock").into(),
            ],
        ),
    ];
    for (tool, args) in attempts {
        if !crate::setup::on_path(tool) {
            continue;
        }
        let mut cmd = Command::new("cargo");
        cmd.args(&args);
        let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
        let text = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        return Some(Check {
            fix: None,
            name: "advisories",
            passed: true,
            detail: if out.status.success() {
                format!("no known advisories ({tool})")
            } else {
                format!(
                    "warning: {tool} reports advisories\n{}",
                    last_lines(&text, 15)
                )
            },
        });
    }
    None
}

/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
    let cargo = |args: &[&str]| -> (bool, String, Option<String>) {
        let mut cmd = Command::new("cargo");
        cmd.args(args)
            .arg("--manifest-path")
            .arg(crate_dir.join("Cargo.toml"))
            .env("CARGO_TARGET_DIR", target_dir);
        // Lint arguments go after `--`, so the manifest path must come before them.
        match crate::process::output(&mut cmd, crate::process::BUILD) {
            Ok(o) => (
                o.status.success(),
                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
                None,
            ),
            Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
        }
    };
    let mut checks = Vec::new();

    let (ok, out, fix) = cargo(&["fmt", "--check"]);
    checks.push(Check {
        name: "fmt",
        passed: ok,
        // The fix line (`cargo fmt --manifest-path ...`) is the advice: it names the crate, which
        // a bare "run `cargo fmt`" does not when gate runs from another folder.
        detail: if ok {
            "formatted".into()
        } else if out.trim().is_empty() {
            "not formatted".into()
        } else {
            out
        },
        fix,
    });

    let mut clippy = Command::new("cargo");
    clippy
        .args(["clippy", "--all-targets", "--manifest-path"])
        .arg(crate_dir.join("Cargo.toml"))
        .args(["--", "-D", "warnings"])
        .env("CARGO_TARGET_DIR", target_dir);
    let (ok, out, fix) = match crate::process::output(&mut clippy, crate::process::BUILD) {
        Ok(o) => (
            o.status.success(),
            clippy_detail(&String::from_utf8_lossy(&o.stderr), 15),
            None,
        ),
        Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
    };
    checks.push(Check {
        fix,
        name: "clippy",
        passed: ok,
        detail: if ok { "no warnings".into() } else { out },
    });

    let (ok, out, fix) = cargo(&["test", "--quiet"]);
    checks.push(Check {
        fix,
        name: "cargo test",
        passed: ok,
        detail: if ok { "passed".into() } else { out },
    });

    checks.push(unsafe_check(crate_dir));

    checks
}

/// Every `unsafe` in the crate's Rust files has a `// SAFETY:` comment: in `src/`, and in
/// `build.rs`, `tests/` and the files `#[path]` can reach, which cargo compiles too.
fn unsafe_check(crate_dir: &Path) -> Check {
    let crate_rs: Vec<PathBuf> = walk_rs(crate_dir)
        .into_iter()
        .filter(|p| !crate::batch_check::is_generated_test(crate_dir, p))
        .collect();
    let (unexplained, explained) = unsafe_blocks(&crate_rs);
    Check {
        fix: None,
        name: "unsafe",
        passed: unexplained.is_empty(),
        detail: if unexplained.is_empty() {
            unsafe_pass_detail(explained)
        } else {
            format!(
                "unsafe without a `// SAFETY:` comment: {}",
                unexplained.join(", ")
            )
        },
    }
}

fn unsafe_pass_detail(explained: usize) -> String {
    match explained {
        0 => "no unsafe code".into(),
        1 => "1 unsafe use, with a `// SAFETY:` comment".into(),
        _ => format!("{explained} unsafe uses, each with a `// SAFETY:` comment"),
    }
}

/// No function in `src/port.rs` is still `unimplemented!`.
pub fn ported_check(crate_dir: &Path) -> Check {
    let path = crate_dir.join("src/port.rs");
    let port = match std::fs::read_to_string(&path) {
        Ok(port) => port,
        Err(error) => {
            return Check {
                fix: None,
                name: "ported",
                passed: false,
                detail: format!("cannot read {}: {error}", path.display()),
            };
        }
    };
    let todo = stubs(&port);
    Check {
        fix: None,
        name: "ported",
        passed: todo == 0,
        detail: if todo == 0 {
            "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
        } else {
            format!(
                "{} in port.rs still `unimplemented!`, `todo!` or a function that only panics",
                crate::report::count(todo, "place")
            )
        },
    }
}

/// Stubs left in a port: `unimplemented!`, `todo!`, and functions whose whole body is a `panic!`.
fn stubs(port: &str) -> usize {
    let code = scan_rust(port, false).code;
    let macros = regex::Regex::new(r"\b(?:unimplemented|todo)\s*!\s*[(\[{]")
        .map(|re| re.find_iter(&code).count())
        .unwrap_or(0);
    let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
        .map(|re| re.find_iter(&code).count())
        .unwrap_or(0);
    macros + panics
}

/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
fn unsafe_blocks(files: &[PathBuf]) -> (Vec<String>, usize) {
    let mut unexplained = Vec::new();
    let mut explained = 0;
    for path in files {
        let text = std::fs::read_to_string(path).unwrap_or_default();
        let lines: Vec<&str> = text.lines().collect();
        let code = scan_rust(&text, false).code;
        for (i, code) in code.split('\n').enumerate() {
            let uses_unsafe = code
                .split(|c: char| !(c.is_alphanumeric() || c == '_'))
                .any(|word| word == "unsafe");
            if !uses_unsafe {
                continue;
            }
            let has_safety = lines[..i]
                .iter()
                .rev()
                .take_while(|l| l.trim_start().starts_with("//"))
                .any(|l| l.contains("SAFETY:"));
            if has_safety {
                explained += 1;
            } else {
                unexplained.push(format!("{}:{}", path.display(), i + 1));
            }
        }
    }
    (unexplained, explained)
}

fn last_lines(text: &str, n: usize) -> String {
    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
    lines[lines.len().saturating_sub(n)..].join("\n")
}

/// What to show of a failed `cargo clippy`: at most `n` lines from the first `error` block (the
/// first `warning` when there is no error). Clippy prints the error and its `--> file:line` first
/// and the build summary and manifest warnings last, so the tail alone often lacks the one line
/// that says what is wrong and where. Output with neither falls back to its last `n` lines.
fn clippy_detail(stderr: &str, n: usize) -> String {
    let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect();
    let start = lines
        .iter()
        .position(|l| l.starts_with("error"))
        .or_else(|| lines.iter().position(|l| l.starts_with("warning")));
    match start {
        Some(i) => lines[i..lines.len().min(i + n)].join("\n"),
        None => last_lines(stderr, n),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CASES, Check, GateOutcome, TESTS_BASELINE, behavior_detail, fix_for, known_diffs_added,
        lifted_into, spawn_fix, spawn_sites, stubs, unexcused_spawns, unsafe_blocks,
        unsafe_pass_detail,
    };
    use std::path::{Path, PathBuf};

    #[test]
    fn a_unit_lifted_into_the_app_is_known_by_its_crate_name() {
        let repo =
            std::env::temp_dir().join(format!("rust-anything-lifted-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&repo);
        std::fs::create_dir_all(repo.join("rust/app")).unwrap();
        std::fs::create_dir_all(repo.join("rust/tool-rs")).unwrap();
        let state = |lifted: bool| {
            format!(
                r#"{{"schema": "rust-anything/app@1", "name": "tool", "commands": ["go"], "lifted": {lifted},
                    "units": [{{"name": "tool", "crate": "tool-rs", "path": "../tool-rs", "commands": ["go"], "switch": "RUST_ANYTHING_UNIT_TOOL"}}]}}"#
            )
        };
        let unit = repo.join("rust/tool-rs");
        // Not lifted: the unit is gated as before.
        std::fs::write(repo.join("rust/app/rust-anything.json"), state(false)).unwrap();
        assert_eq!(lifted_into(&unit), None);
        // Lifted: its bindings are gone, and the app's replay checks its cases.
        std::fs::write(repo.join("rust/app/rust-anything.json"), state(true)).unwrap();
        assert_eq!(lifted_into(&unit).as_deref(), Some("tool"));
        // A crate that is not one of the app's units is not.
        std::fs::create_dir_all(repo.join("rust/other-rs")).unwrap();
        assert_eq!(lifted_into(&repo.join("rust/other-rs")), None);
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn the_behavior_line_never_counts_an_accepted_case_as_a_plain_match() {
        assert_eq!(behavior_detail(10, 10, 0), "10/10 recorded cases match");
        assert_eq!(
            behavior_detail(10, 10, 3),
            "7/10 recorded cases match exactly, 3 more accepted as known differences \
             (known-diffs.jsonl)"
        );
    }

    #[test]
    fn known_diffs_added_counts_from_the_last_passing_gate_only() {
        let dir = std::env::temp_dir().join(format!("ra-known-added-{}", std::process::id()));
        std::fs::create_dir_all(dir.join(".rust-anything")).unwrap();
        let entry = r#"{"fn":"f","args":[1],"actual":2,"reason":"rounding"}"#;
        std::fs::write(
            dir.join("known-diffs.jsonl"),
            format!("{entry}\n{entry}\n{entry}\n"),
        )
        .unwrap();
        // Nobody has looked at them yet: without a baseline (a fresh clone) every entry is new.
        assert_eq!(known_diffs_added(&dir), 3, "no baseline yet");
        std::fs::write(dir.join(TESTS_BASELINE), r#"{"tests":1,"asserts":1}"#).unwrap();
        assert_eq!(
            known_diffs_added(&dir),
            3,
            "a baseline from before the count"
        );
        std::fs::write(
            dir.join(TESTS_BASELINE),
            r#"{"tests":1,"asserts":1,"known_diffs":1}"#,
        )
        .unwrap();
        assert_eq!(known_diffs_added(&dir), 2);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_stub_macro_with_a_space_or_other_brackets_is_a_stub() {
        assert_eq!(
            stubs("pub fn f(x: u8) -> u8 { if x > 200 { todo! () } else { x } }\n"),
            1
        );
        assert_eq!(stubs("pub fn g() -> u8 { unimplemented!{} }\n"), 1);
        assert_eq!(stubs("pub fn h() -> u8 { todo![] }\n"), 1);
        assert_eq!(
            stubs("pub fn label() -> &'static str { \"todo! [] or unimplemented!{}\" }\n"),
            0
        );
    }

    #[test]
    fn unsafe_outside_src_needs_a_safety_comment_too() {
        let dir = crate::app::temp_dir("guard-unsafe-tests").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::create_dir_all(dir.join("tests")).unwrap();
        std::fs::write(dir.join("src/port.rs"), "pub fn f() -> u8 { 1 }\n").unwrap();
        std::fs::write(
            dir.join("tests/t.rs"),
            "#[test]\nfn t() { let p = &1u8 as *const u8; let _ = unsafe { *p }; }\n",
        )
        .unwrap();
        std::fs::write(dir.join("build.rs"), "fn main() { unsafe { x() } }\n").unwrap();
        let c = super::unsafe_check(&dir);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(!c.passed, "{c:?}");
        assert!(c.detail.contains("t.rs:2"), "{}", c.detail);
        assert!(c.detail.contains("build.rs:1"), "{}", c.detail);
    }

    #[test]
    fn counts_every_kind_of_stub() {
        let port = "pub fn a() -> u8 { todo!() }\n\
                    pub fn b() -> u8 { unimplemented!(\"later\") }\n\
                    pub fn c(x: u8) -> u8 {\n    panic!(\"not ported\")\n}\n\
                    pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
                    // todo!() in a comment\n";
        assert_eq!(stubs(port), 3);
        assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
    }

    #[test]
    fn failed_checks_say_what_to_run() {
        let check = |name, detail: &str| Check {
            fix: None,
            name,
            passed: false,
            detail: detail.into(),
        };
        let dir = std::path::Path::new("port");
        assert_eq!(
            fix_for(&check("recording", "changed"), dir).as_deref(),
            Some("rust-anything record port")
        );
        assert_eq!(
            fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
            Some("rust-anything record port")
        );
        assert_eq!(
            fix_for(&check("ported", "stub"), dir).as_deref(),
            Some(
                "port the functions still stubbed in port/src/port.rs, then `rust-anything gate port` again"
            )
        );
        assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
        assert!(
            fix_for(
                &check("coverage", "1 of the unit's exports has no recorded case"),
                dir
            )
            .is_some_and(|f| f.starts_with("rust-anything record port")
                && f.contains("rust-anything obligations waive <id>"))
        );

        let batch_mismatch_fix = fix_for(
            &check(
                "batch",
                "Batch CountIndex (count): 1/2 cases match across 1 group (1 failed)",
            ),
            dir,
        )
        .unwrap();
        assert!(
            batch_mismatch_fix.contains("src/port.rs"),
            "{batch_mismatch_fix}"
        );

        let batch_collision_fix = fix_for(
            &check(
                "batch",
                "Batch CountIndex (count): failed to run: port/tests/rust_anything_batch.rs exists and was not generated by rust-anything",
            ),
            dir,
        )
        .unwrap();
        assert!(
            !batch_collision_fix.contains("src/port.rs")
                && batch_collision_fix.contains(crate::batch_check::TEST_FILE),
            "{batch_collision_fix}"
        );

        let batch_exec_fix = fix_for(
            &check(
                "batch",
                "Batch CountIndex (count): failed to run: compile error",
            ),
            dir,
        )
        .unwrap();
        assert!(
            !batch_exec_fix.contains("src/port.rs")
                && batch_exec_fix.contains("batch check error above"),
            "{batch_exec_fix}"
        );

        let collision_structured = super::batch_fix(
            &[crate::batch_check::BatchDiff {
                function: "count".into(),
                index: "CountIndex".into(),
                error: Some(
                    "tests/rust_anything_batch.rs exists and was not generated by rust-anything"
                        .into(),
                ),
                ..Default::default()
            }],
            dir,
        )
        .unwrap();
        assert!(
            !collision_structured.contains("src/port.rs")
                && collision_structured.contains(crate::batch_check::TEST_FILE),
            "{collision_structured}"
        );

        let mixed_structured = super::batch_fix(
            &[
                crate::batch_check::BatchDiff {
                    function: "a".into(),
                    index: "AIndex".into(),
                    failed: 1,
                    cases: 2,
                    passed: 1,
                    ..Default::default()
                },
                crate::batch_check::BatchDiff {
                    function: "b".into(),
                    index: "BIndex".into(),
                    error: Some("aborted".into()),
                    ..Default::default()
                },
            ],
            dir,
        )
        .unwrap();
        assert!(
            mixed_structured.contains("batch check error above")
                && mixed_structured.contains("rust-anything diff"),
            "{mixed_structured}"
        );

        let mut missing_cmd = std::process::Command::new("cargo");
        missing_cmd.env_remove("PATH");
        let missing_err = crate::process::spawn_error(
            &missing_cmd,
            "cargo build",
            std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
        );
        let missing_fix = spawn_fix(&missing_err).unwrap();
        assert!(
            !missing_fix.contains("fix the compile error above"),
            "{missing_fix}"
        );
        assert!(missing_fix.contains("cargo"), "{missing_fix}");
        assert!(
            missing_fix.contains("rust-anything doctor"),
            "{missing_fix}"
        );
        assert!(!missing_fix.contains('\n'), "{missing_fix}");

        let denied_err = crate::process::spawn_error(
            &std::process::Command::new("cargo"),
            "cargo build",
            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
        );
        let spawn_hint = spawn_fix(&denied_err).unwrap();
        assert!(
            !spawn_hint.contains("fix the compile error above"),
            "{spawn_hint}"
        );
        assert!(spawn_hint.contains("rust-anything doctor"), "{spawn_hint}");

        let compile_err =
            anyhow::anyhow!("cargo build failed (exit status: 101)\n\"not found on PATH\"");
        assert!(spawn_fix(&compile_err).is_none());
        let compile_fix = fix_for(&check("build", &compile_err.to_string()), dir).unwrap();
        assert!(
            compile_fix.starts_with("fix the compile error above"),
            "{compile_fix}"
        );
    }

    #[test]
    fn unsafe_pass_detail_handles_zero_one_and_multiple_uses() {
        assert_eq!(unsafe_pass_detail(0), "no unsafe code");
        assert_eq!(
            unsafe_pass_detail(1),
            "1 unsafe use, with a `// SAFETY:` comment"
        );
        assert_eq!(
            unsafe_pass_detail(2),
            "2 unsafe uses, each with a `// SAFETY:` comment"
        );
    }

    #[test]
    fn requires_safety_comments() {
        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("a.rs"),
            "#![forbid(unsafe_code)]\n\
             // SAFETY: checked above\n\
             unsafe { x() }\n\
             let y = unsafe { z() };\n\
             // unsafe in a comment\n\
             let _err = Err(\"RangeError: unsafe input\".into());\n\
             let _raw = r#\"unsafe \"quoted\" string\"#;\n\
             let _with_real = \"a string with unsafe\"; unsafe { real_work() };\n\
             const FIXTURE: &str = r#\"\n\
             unsafe { example() }\n\
             \"#;\n\
             /* unsafe {\n\
             unsafe { in_a_comment() } */\n\
             unsafe { last() }\n\
             pub unsafe/* separator */fn glued() {}\n",
        )
        .unwrap();
        let (unexplained, explained) = unsafe_blocks(&super::walk_rs(&dir));
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(explained, 1);
        assert_eq!(unexplained.len(), 4, "{unexplained:?}");
        assert!(unexplained[0].ends_with("a.rs:4"), "{}", unexplained[0]);
        assert!(unexplained[1].ends_with("a.rs:8"), "{}", unexplained[1]);
        assert!(unexplained[2].ends_with("a.rs:14"), "{}", unexplained[2]);
        assert!(unexplained[3].ends_with("a.rs:15"), "{}", unexplained[3]);
    }

    #[test]
    fn missing_port_source_fails_the_ported_check() {
        let dir = crate::app::temp_dir("gate-port").unwrap();
        let check = super::ported_check(&dir);
        std::fs::remove_dir(dir).unwrap();
        assert!(!check.passed);
        assert!(check.detail.contains("cannot read"));
        assert!(check.detail.contains("port.rs"));
    }

    #[test]
    fn ported_check_counts_one_place_and_several_places() {
        let detail = |port: &str| {
            let dir = crate::app::temp_dir("gate-ported").unwrap();
            std::fs::create_dir_all(dir.join("src")).unwrap();
            std::fs::write(dir.join("src/port.rs"), port).unwrap();
            let check = super::ported_check(&dir);
            std::fs::remove_dir_all(dir).unwrap();
            assert!(!check.passed);
            check.detail
        };
        let one = detail("pub fn a() -> i32 { todo!() }\n");
        assert!(one.starts_with("1 place in port.rs "), "{one}");
        let two = detail("pub fn a() -> i32 { todo!() }\npub fn b() -> i32 { unimplemented!() }\n");
        assert!(two.starts_with("2 places in port.rs "), "{two}");
    }

    #[test]
    fn scan_finds_literals_outside_comments_and_tests() {
        let port = "// \"a comment string\" 123456\n\
                    /* 987654 /* nested */ \"no\" */\n\
                    pub fn f(x: &str) -> u64 { if x == \"tab\\there\\u{e9}\" { 1_234_567u64 } else { 0x123456 } }\n\
                    pub fn g<'a>(c: char) -> &'a str { if c == '\"' { r#\"say \"hi\" now\"# } else { b\"bytes!!!\"; \"x\" } }\n\
                    pub fn h() -> f64 { 3.14159e-2 + (0..100000).count() as f64 } // recorded-literal: pi from a table\n\
                    pub fn i() -> f64 { t.0 + 2.5f32 as f64 }\n\
                    #[cfg(test)]\nmod tests { const X: &str = \"only in tests\"; }\n";
        let scan = super::scan_rust(port, true);
        let strings: Vec<(usize, &str)> =
            scan.strings.iter().map(|(l, s)| (*l, s.as_str())).collect();
        assert_eq!(
            strings,
            [
                (3, "tab\there\u{e9}"),
                (4, "say \"hi\" now"),
                (4, "bytes!!!"),
                (4, "x")
            ]
        );
        let numbers: Vec<(usize, &str)> =
            scan.numbers.iter().map(|(l, n)| (*l, n.as_str())).collect();
        assert_eq!(
            numbers,
            [
                (3, "1234567"),
                (3, "1193046"),
                (5, "3.14159e-2"),
                (5, "0"),
                (5, "100000"),
                (6, "2.5")
            ]
        );
        assert!(scan.marked.contains(&5) && scan.marked.len() == 1);
        assert!(!scan.code.contains("comment") && !scan.code.contains("only in tests"));
        let all = super::scan_rust(port, false);
        assert_eq!(all.strings.last().unwrap().1, "only in tests");
    }

    #[test]
    fn common_numbers_are_never_suspicious() {
        use super::{significant_digits, well_known};
        assert_eq!(significant_digits("1234500"), 5);
        assert_eq!(significant_digits("0.00012345"), 5);
        assert_eq!(significant_digits("1.25e10"), 3);
        for n in [
            "65536",
            "65535",
            "4294967295",
            "2147483647",
            "9007199254740991",
            "18446744073709551615",
            "1000000",
            "1.7976931348623157e308",
            "3.4028235e38",
            "2.220446049250313e-16",
        ] {
            assert!(well_known(n), "{n}");
        }
        for n in ["12345", "4294967299", "3.14159", "99999"] {
            assert!(!well_known(n), "{n}");
        }
    }

    #[test]
    fn literals_leave_out_recorded_error_text() {
        let dir = crate::app::temp_dir("gate-literals-errors").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("words.py"), "def ratio(a, b):\n    return a / b\n").unwrap();
        std::fs::write(
            dir.join(CASES),
            "{\"fn\":\"ratio\",\"args\":[1,0],\"error\":\"ZeroDivisionError: division by zero\",\"error_type\":\"ZeroDivisionError\"}\n\
             {\"class\":\"Ratio\",\"ctor\":[0],\"calls\":[],\"results\":[{\"error\":\"OverflowError: stack is full\"}]}\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("src/port.rs"),
            "pub fn ratio(a: f64, b: f64) -> Result<f64, String> {\n    if b == 0.0 { return Err(\"ZeroDivisionError: division by zero\".into()) }\n    if a > 1e9 { return Err(\"OverflowError: stack is full\".into()) }\n    Ok(a / b)\n}\n",
        )
        .unwrap();
        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "words.py",
            "crate_name": "demo",
            "kind": "pyo3",
            "exports": [],
        }))
        .unwrap();
        let check = super::literals_check(&dir, &manifest).unwrap();
        assert!(check.passed, "{check:?}");
        assert_eq!(check.detail, "no recorded values written into the port");
    }

    #[test]
    fn literals_fail_from_three_recorded_values_the_original_does_not_spell() {
        let dir = crate::app::temp_dir("gate-literals").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("lib.ts"),
            "export const greet = (n: string) => `hello there, ${n}` + \"spelled out\" + 31337\n",
        )
        .unwrap();
        std::fs::write(
            dir.join(CASES),
            "{\"fn\":\"greet\",\"args\":[\"somebody else\"],\"ok\":\"hello there, somebody else\"}\n\
             {\"fn\":\"greet\",\"args\":[\"x\"],\"ok\":[\"spelled out\",\"second answer\",31337,271828,\"third answer\"]}\n",
        )
        .unwrap();
        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "lib.ts",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [],
        }))
        .unwrap();
        let check = |port: &str| {
            std::fs::write(dir.join("src/port.rs"), port).unwrap();
            super::literals_check(&dir, &manifest).unwrap()
        };
        let honest = check(
            "pub fn greet(n: &str) -> String { format!(\"hello there, {n}\") + \"spelled out\" }\n",
        );
        assert!(honest.passed, "{honest:?}");
        assert_eq!(honest.detail, "no recorded values written into the port");

        let two = check(
            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    String::new()\n}\n",
        );
        assert!(two.passed, "{two:?}");
        assert!(
            two.detail.starts_with("2 recorded values"),
            "{}",
            two.detail
        );
        assert!(
            two.detail.contains("\"somebody else\" (src/port.rs:2)"),
            "{}",
            two.detail
        );

        let three = check(
            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    let _ = 271_828;\n    String::new()\n}\n",
        );
        assert!(!three.passed, "{three:?}");
        assert!(
            three.detail.contains("271828 (src/port.rs:3)"),
            "{}",
            three.detail
        );

        let marked = check(
            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    let _ = 271_828; // recorded-literal: e from a table\n    String::new()\n}\n",
        );
        assert!(marked.passed, "{marked:?}");

        let reads = check("const C: &str = include_str!(\"../cases.jsonl\");\n");
        assert!(!reads.passed, "{reads:?}");
        assert!(reads.detail.contains("src/port.rs:1"), "{}", reads.detail);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn the_clippy_detail_starts_at_the_error_not_at_the_build_summary() {
        // Clippy prints the error first and the summary and manifest warnings last; the last 15
        // lines of this are all of the second kind.
        let mut stderr = String::from(
            "    Checking math-rs v0.1.0 (/x)\n\
             error: function `helper` is never used\n\
             \x20 --> src/port.rs:10:4\n\
             \x20  |\n\
             10 | fn helper() -> u8 {\n\
             \x20  |    ^^^^^^\n\
             \x20  |\n\
             \x20  = note: `-D dead-code` implied by `-D warnings`\n\n\
             error: could not compile `math-rs` (lib) due to 1 previous error\n",
        );
        for i in 0..12 {
            stderr.push_str(&format!("warning: unused manifest key: package.extra{i}\n"));
        }
        let (clippy_detail, last_lines) = (super::clippy_detail, super::last_lines);
        let detail = clippy_detail(&stderr, 15);
        assert!(
            detail.starts_with("error: function `helper` is never used\n"),
            "{detail}"
        );
        assert!(detail.contains("src/port.rs:10"), "{detail}");
        assert!(detail.lines().count() <= 15, "{detail}");
        assert!(
            !last_lines(&stderr, 15).contains("src/port.rs:10"),
            "the tail alone loses the location"
        );

        // No error: the first warning. Neither: the last lines, as before.
        let warned = "    Checking x v0.1.0\nwarning: unused variable: `a`\n --> src/lib.rs:1:1\n";
        assert!(clippy_detail(warned, 15).starts_with("warning: unused variable"));
        let plain = "line one\nline two\nline three\n";
        assert_eq!(clippy_detail(plain, 2), "line two\nline three");
    }

    #[test]
    fn size_check_says_1_line_for_singular_source() {
        let dir = crate::app::temp_dir("gate-size").unwrap();
        let src_dir = dir.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::write(src_dir.join("add.ts"), "export const add = 1;\n").unwrap();
        std::fs::write(src_dir.join("port.rs"), "pub fn add() -> i32 { 1 }\n").unwrap();
        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "src",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [],
        }))
        .unwrap();
        let check = super::size_check(&dir, &manifest, &mut Vec::new()).unwrap();
        std::fs::remove_dir_all(dir).unwrap();
        assert!(
            check
                .detail
                .contains("1 line of Rust for 1 line of TypeScript/JavaScript"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn a_failed_fmt_check_on_a_lifted_crate_has_its_fix_line() {
        // `lifted_checks` returns before `run`'s own fix loop, and the fmt detail no longer says
        // "run `cargo fmt`": the fix line is the only advice, so this path needs it too.
        let dir = crate::app::temp_dir("gate-lifted-fmt").unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"tool-rs\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn f(a:u8)->u8{a}\n").unwrap();
        let outcome = super::lifted_checks(&dir, "tool").unwrap();
        let fmt = outcome.checks.iter().find(|c| c.name == "fmt");
        let shown = format!("{fmt:?}");
        let (failed, fix) = fmt.map_or((false, None), |c| (!c.passed, c.fix.clone()));
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(failed, "{shown}");
        assert!(
            fix.as_deref().is_some_and(|f| f.starts_with("cargo fmt")),
            "{shown}"
        );
    }

    #[test]
    fn a_failed_size_check_gives_its_advice_once_in_the_fix_line() {
        let dir = crate::app::temp_dir("gate-size-advice").unwrap();
        let src_dir = dir.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::write(src_dir.join("add.ts"), "export const add = 1;\n").unwrap();
        let big: String = (0..100)
            .map(|i| format!("pub fn f{i}() -> i32 {{ {i} }}\n"))
            .collect();
        std::fs::write(src_dir.join("port.rs"), big).unwrap();
        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "src",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [],
        }))
        .unwrap();
        let mut check = super::size_check(&dir, &manifest, &mut Vec::new()).unwrap();
        check.fix = super::fix_for(&check, &dir);
        std::fs::remove_dir_all(dir).unwrap();
        assert!(!check.passed, "{check:?}");
        let text = super::text(&GateOutcome {
            passed: false,
            cases: None,
            stamp: crate::state::Stamp::default(),
            failed: vec!["size"],
            behavior: None,
            checks: vec![check],
            comparison: Default::default(),
            notes: Vec::new(),
        });
        // The detail ends after the explanation; the advice is the fix line, once.
        let first = text.lines().nth(1).unwrap();
        assert!(first.ends_with("or a case handled one by one"), "{text}");
        assert_eq!(text.matches("fold repeated code").count(), 1, "{text}");
        assert!(
            text.lines()
                .any(|l| l.trim_start().starts_with("fix: use the crates")),
            "{text}"
        );
    }

    fn oversized_python_port(name: &str) -> (PathBuf, crate::bridge::Manifest) {
        let dir = crate::app::temp_dir(name).unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::create_dir_all(dir.join("rust")).unwrap();
        let python: String = (0..10).map(|i| format!("x{i} = {i}\n")).collect();
        std::fs::write(dir.join("src/scrape.py"), python).unwrap();
        let rust: String = (0..120)
            .map(|i| format!("pub fn f{i}() -> i32 {{ {i} }}\n"))
            .collect();
        std::fs::write(dir.join("src/port.rs"), rust).unwrap();
        let manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "src/scrape.py",
            "language": "python",
            "crate_name": "demo",
            "kind": "pyo3",
            "exports": [],
        }))
        .unwrap();
        std::fs::write(
            dir.join("rust/DECISIONS.md"),
            "# Decisions\n\n## ADR-001: Allow `src/scrape.py` a larger port\nStatus: accepted\n",
        )
        .unwrap();
        (dir, manifest)
    }

    fn allow_size(dir: &Path, max: &str) {
        std::fs::write(
            dir.join("rust/obligations-decisions.toml"),
            format!(
                "[[size]]\nadr = \"ADR-001\"\ndate = \"2026-12-02\"\nreason = \"re-implements \
                 html.parser and the bs4 tree builder\"\nunit = \"src/scrape.py\"\nmax = {max}\n"
            ),
        )
        .unwrap();
    }

    #[test]
    fn a_size_decision_lets_a_larger_port_pass_and_says_so() {
        let (dir, manifest) = oversized_python_port("gate-size-allowed");
        let mut notes = Vec::new();
        let before = super::size_check(&dir, &manifest, &mut notes).unwrap();
        allow_size(&dir, "15");
        let after = super::size_check(&dir, &manifest, &mut notes).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(!before.passed, "{before:?}");
        assert!(after.passed, "{after:?}");
        assert!(
            after.detail.ends_with(
                "(12.0x); allowed up to 15x by ADR-001: re-implements html.parser and the bs4 \
                 tree builder"
            ),
            "{}",
            after.detail
        );
        assert_eq!(
            notes,
            [
                "`size` passed at 12.0x on ADR-001 of rust/DECISIONS.md, which allows up to 15x: \
                 re-implements html.parser and the bs4 tree builder"
            ]
        );
    }

    #[test]
    fn a_port_over_its_size_decision_still_fails() {
        let (dir, manifest) = oversized_python_port("gate-size-over-allowed");
        allow_size(&dir, "5.5");
        let mut notes = Vec::new();
        let check = super::size_check(&dir, &manifest, &mut notes).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(!check.passed, "{check:?}");
        assert!(
            check
                .detail
                .ends_with("(12.0x); over the 5.5x that ADR-001 allows"),
            "{}",
            check.detail
        );
        assert!(notes.is_empty(), "{notes:?}");
    }

    #[test]
    fn an_oversized_port_fails_when_the_decisions_cannot_be_read() {
        let (dir, manifest) = oversized_python_port("gate-size-bad-decisions");
        allow_size(&dir, "2");
        let check = super::size_check(&dir, &manifest, &mut Vec::new()).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(!check.passed, "{check:?}");
        assert!(
            check.detail.contains(
                "the size decisions could not be read: invalid rust/obligations-decisions.toml"
            ),
            "{}",
            check.detail
        );
    }

    #[test]
    fn text_aligns_all_check_details_including_error_cases_and_known_diffs() {
        let outcome = GateOutcome {
            passed: true,
            cases: None,
            stamp: crate::state::Stamp::default(),
            failed: Vec::new(),
            behavior: None,
            checks: vec![
                Check {
                    name: "tests",
                    passed: true,
                    detail: "0 tests, 0 assertions; saved as the baseline once gate passes".into(),
                    fix: None,
                },
                Check {
                    name: "error cases",
                    passed: true,
                    detail: "the 1 function that fails in the original has a recorded failing case"
                        .into(),
                    fix: None,
                },
                Check {
                    name: "panics",
                    passed: true,
                    detail: "no unwrap, expect or panic where the original returns an error".into(),
                    fix: None,
                },
                Check {
                    name: "known diffs",
                    passed: true,
                    detail: "all recorded diffs match".into(),
                    fix: None,
                },
            ],
            comparison: Default::default(),
            notes: Vec::new(),
        };
        let text = super::text(&outcome);
        assert_eq!(text.lines().next(), Some("comparison: exact"));
        let lines: Vec<&str> = text.lines().skip(1).take(4).collect();
        // Column where the detail starts (after "pass  " (6 chars) + 11-char name + " " (1 char) = 18 chars)
        let col = "pass  error cases ".len();
        assert_eq!(col, 18);
        for line in &lines {
            assert!(line.len() > col, "line too short: {line}");
            assert_eq!(
                &line[col..col + 2],
                match line.split_whitespace().nth(1).unwrap() {
                    "tests" => "0 ",
                    "error" => "th",
                    "panics" => "no",
                    "known" => "al",
                    other => panic!("unexpected check: {other}"),
                }
            );
        }
        assert!(text.contains("Gate passed."));
    }

    #[test]
    fn text_says_when_error_messages_were_not_compared() {
        let outcome = |unchecked_messages| GateOutcome {
            passed: true,
            cases: None,
            stamp: crate::state::Stamp::default(),
            failed: Vec::new(),
            behavior: None,
            checks: Vec::new(),
            comparison: crate::recording::Loosening {
                unchecked_messages,
                ..Default::default()
            },
            notes: Vec::new(),
        };
        let text = super::text(&outcome(2));
        assert_eq!(
            text.lines().nth(1),
            Some(
                "error messages not compared: 2 recorded errors checked by class only \
                 (`record --messages` compares the text too)"
            ),
            "{text}"
        );
        assert!(!super::text(&outcome(0)).contains("messages"));
    }

    #[test]
    fn text_aligns_continuation_and_fix_lines_with_the_detail() {
        let outcome = GateOutcome {
            passed: false,
            cases: None,
            stamp: crate::state::Stamp::default(),
            failed: Vec::new(),
            behavior: None,
            checks: vec![
                Check {
                    name: "ported",
                    passed: false,
                    detail: "1 place in port.rs still `todo!`\nsecond line of the detail".into(),
                    fix: Some("port the functions still stubbed in src/port.rs".into()),
                },
                Check {
                    name: "error cases",
                    passed: true,
                    detail: "every failing function has a recorded failing case".into(),
                    fix: None,
                },
            ],
            comparison: Default::default(),
            notes: Vec::new(),
        };
        let text = super::text(&outcome);
        let col = "FAIL  error cases ".len();
        let lines: Vec<&str> = text.lines().skip(1).collect();
        assert_eq!(&lines[0][col..], "1 place in port.rs still `todo!`");
        assert_eq!(
            lines[1],
            format!("{}second line of the detail", " ".repeat(col))
        );
        assert_eq!(
            lines[2],
            format!(
                "{}fix: port the functions still stubbed in src/port.rs",
                " ".repeat(col)
            )
        );
        assert_eq!(
            &lines[3][col..],
            "every failing function has a recorded failing case"
        );
        assert_eq!(lines[4], "Gate failed.");
    }

    #[test]
    fn a_port_that_starts_a_process_is_found_unless_marked() {
        let port = "use std::process::Command;\n\npub fn f() -> Result<String, String> {\n    \
                    let out = Command::new(\"node\").output().map_err(|e| e.to_string())?;\n    \
                    Ok(String::from_utf8_lossy(&out.stdout).into_owned())\n}\n";
        let sites = spawn_sites(port);
        assert_eq!(
            sites,
            [(1, "std::process::Command"), (4, "Command::new")],
            "{sites:?}"
        );
        let marked = port.replace(
            "    let out",
            "    // SPAWNS: the original runs git here\n    let out",
        );
        assert_eq!(spawn_sites(&marked).len(), 1, "the import is still a spawn");
        for clean in [
            "// Command::new is not called here\nfn f() -> &'static str { \"Command::new(\" }\n",
            "use std::process::exit;\nfn f() { exit(1) }\n",
            "fn f() {}\n#[cfg(test)]\nmod t { fn x() { std::process::Command::new(\"a\"); } }\n",
        ] {
            assert!(spawn_sites(clean).is_empty(), "{clean}");
        }
        assert_eq!(
            spawn_sites("use std::process::{Command, Stdio};\n").len(),
            1
        );
        assert_eq!(
            spawn_sites("fn f() { duct::cmd(\"ls\", [\"-l\"]); }\n").len(),
            1
        );
    }

    #[test]
    fn a_spawns_mark_counts_only_where_the_original_spawns_too() {
        let port = "// SPAWNS: the original runs git here\nfn f() { Command::new(\"git\"); }\n";
        assert!(unexcused_spawns(port, true).is_empty());
        assert_eq!(unexcused_spawns(port, false), [(2, "Command::new")]);
    }
}

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

    /// A crate folder with an original `lib.ts` that spells out nothing, and a recording that
    /// holds the given result values.
    fn crate_with(tag: &str, results: &str) -> (PathBuf, Manifest) {
        let dir = crate::app::temp_dir(tag).unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("lib.ts"), "export const f = (x: number) => x\n").unwrap();
        std::fs::write(
            dir.join(CASES),
            format!("{{\"fn\":\"f\",\"args\":[1],\"ok\":{results}}}\n"),
        )
        .unwrap();
        let manifest: Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "lib.ts",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [{"name": "f", "file": "lib.ts", "line": 1, "params": [], "returns": "unknown", "is_async": false}],
        }))
        .unwrap();
        (dir, manifest)
    }

    #[test]
    fn an_included_table_of_recorded_numbers_fails_the_runtime_check() {
        let (dir, m) = crate_with("guard-include-numbers", "7.123456");
        let cases = "{\"fn\":\"f\",\"args\":[1],\"ok\":7.123456}\n\
                     {\"fn\":\"f\",\"args\":[2],\"ok\":14.246912}\n\
                     {\"fn\":\"f\",\"args\":[3],\"ok\":21.370368}\n";
        std::fs::write(dir.join(CASES), cases).unwrap();
        std::fs::write(
            dir.join("src/answers.txt"),
            cases.replace("\"ok\"", "\"r\""),
        )
        .unwrap();
        std::fs::write(
            dir.join("src/port.rs"),
            "static T: &str = include_str!(\"answers.txt\");\npub fn f(x: f64) -> f64 { T.len() as f64 * x }\n",
        )
        .unwrap();
        let c = runtime_check(&dir, &m);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            !c.passed && c.detail.contains("holds 3 recorded values"),
            "{c:?}"
        );
    }

    fn literals(dir: &Path, manifest: &Manifest, port: &str) -> Check {
        std::fs::write(dir.join("src/port.rs"), port).unwrap();
        literals_check(dir, manifest).unwrap()
    }

    #[test]
    fn negative_hex_and_split_spellings_of_recorded_values_count() {
        let (dir, m) = crate_with(
            "guard-spellings",
            "[-12345.678,-23456.789,-34567.891,3735928559,\"hello world one\",\"hello world two\",\"hello world three\"]",
        );
        // The plain forms were always caught; these were not.
        for (what, port) in [
            (
                "negative numbers",
                "pub fn f() -> [f64; 3] { [-12345.678, -23456.789, -34567.891] }\n",
            ),
            (
                "hex and negative",
                "pub fn f() -> [f64; 3] { [0xDEADBEEF as f64, -12345.678, -23456.789] }\n",
            ),
            (
                "strings split in two",
                "pub fn f() -> [String; 3] { [[\"hello\", \" world one\"].concat(), String::from(\"hello \") + \"world two\", \"hello world\".to_owned() + \" three\"] }\n",
            ),
        ] {
            let check = literals(&dir, &m, port);
            assert!(!check.passed, "{what}: {check:?}");
        }
        // Subtraction is not a negative literal.
        let sub = literals(
            &dir,
            &m,
            "pub fn f(a: f64) -> f64 { a - 12345.678 + (a -23456.789) }\n",
        );
        assert!(sub.passed, "{sub:?}");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn a_format_string_and_one_long_literal_that_hold_recorded_strings_count() {
        let (dir, m) = crate_with(
            "guard-format",
            "[\"order 1001 is ready for pickup\",\"order 1002 is ready for pickup\",\"order 1003 is ready for pickup\"]",
        );
        let table = literals(
            &dir,
            &m,
            "pub fn f() -> Vec<String> { include_table(\"order 1001 is ready for pickup;order 1002 is ready for pickup;order 1003 is ready for pickup\") }\n",
        );
        assert!(!table.passed, "{table:?}");
        let (dir2, m2) = crate_with(
            "guard-format2",
            "[\"hello there, somebody else\",\"hello there, another one\",\"hello there, a third\"]",
        );
        // Three distinct recorded strings produced by one format string are not three literals,
        // but the template is reported once when the original never spells it.
        let one = literals(
            &dir2,
            &m2,
            "pub fn f(n: &str) -> String { format!(\"hello there, {n}\") }\n",
        );
        assert!(
            one.passed && one.detail.contains("hello there, a third"),
            "{one:?}"
        );
        std::fs::remove_dir_all(dir).unwrap();
        std::fs::remove_dir_all(dir2).unwrap();
    }

    #[test]
    fn a_table_cannot_hide_in_an_ignored_hidden_or_after_a_cfg_test_line() {
        let (dir, m) = crate_with(
            "guard-hidden",
            "[\"hello world one\",\"hello world two\",\"hello world three\"]",
        );
        let table = "pub fn t() -> [&'static str; 3] { [\"hello world one\", \"hello world two\", \"hello world three\"] }\n";
        std::fs::write(dir.join("src/port.rs"), "pub mod table;\n").unwrap();
        // 1. `src/.ignore` names the file: cargo still compiles it.
        std::fs::write(dir.join("src/.ignore"), "table.rs\n").unwrap();
        std::fs::write(dir.join("src/table.rs"), table).unwrap();
        assert!(!literals_check(&dir, &m).unwrap().passed, ".ignore");
        std::fs::remove_file(dir.join("src/table.rs")).unwrap();
        // 2. A hidden folder.
        std::fs::create_dir_all(dir.join("src/.d")).unwrap();
        std::fs::write(dir.join("src/.d/t.rs"), table).unwrap();
        assert!(!literals_check(&dir, &m).unwrap().passed, "hidden folder");
        std::fs::remove_dir_all(dir.join("src/.d")).unwrap();
        // 3. A `#[cfg(test)]` item first: only that item is a test.
        let port = format!("#[cfg(test)]\nuse std::fmt;\n{table}");
        assert!(!literals(&dir, &m, &port).passed, "cfg(test) use first");
        let port = format!("#[cfg(test)]\nfn helper() {{}}\n{table}");
        assert!(!literals(&dir, &m, &port).passed, "cfg(test) fn first");
        // 4. A stray file next to Cargo.toml that `#[path]` includes.
        std::fs::write(dir.join("stray.rs"), table).unwrap();
        std::fs::write(dir.join("src/port.rs"), "").unwrap();
        assert!(!literals_check(&dir, &m).unwrap().passed, "stray file");
        std::fs::remove_file(dir.join("stray.rs")).unwrap();
        // A real test module is still left out.
        let port = format!("pub fn f() {{}}\n#[cfg(test)]\nmod tests {{\n{table}}}\n");
        assert!(literals(&dir, &m, &port).passed, "a test module");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn recorded_literal_markers_excuse_two_values_need_a_reason_and_are_counted() {
        let (dir, m) = crate_with(
            "guard-marks",
            "[\"hello world one\",\"hello world two\",\"hello world three\"]",
        );
        let line = |s: &str, mark: &str| {
            format!(
                "pub fn t{}() -> &'static str {{ \"{s}\" }} {mark}\n",
                s.len()
            )
        };
        let reasoned = "// recorded-literal: the library's own table";
        let two = literals(
            &dir,
            &m,
            &(line("hello world one", reasoned) + &line("hello world two", reasoned)),
        );
        assert!(two.passed, "{two:?}");
        assert!(two.detail.contains("2 values exempted"), "{}", two.detail);
        // Three exempted lines are a table with a comment on each row.
        let three = literals(
            &dir,
            &m,
            &(line("hello world one", reasoned)
                + &line("hello world two", reasoned)
                + &line("hello world three", reasoned)),
        );
        assert!(!three.passed, "{three:?}");
        // A marker with no reason excuses nothing.
        let bare = literals(
            &dir,
            &m,
            &(line("hello world one", "// recorded-literal:")
                + &line("hello world two", "// recorded-literal:")
                + &line("hello world three", "// recorded-literal:")),
        );
        assert!(!bare.passed, "{bare:?}");
        assert!(bare.detail.contains("without a reason"), "{}", bare.detail);
        let (lit, _) = {
            std::fs::write(
                dir.join("src/port.rs"),
                line("hello world one", reasoned) + "// INFALLIBLE: it is checked above\n",
            )
            .unwrap();
            marker_counts(&dir)
        };
        assert_eq!(lit, 1);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn the_port_may_not_run_the_original_or_include_its_recording() {
        let (dir, m) = crate_with(
            "guard-runtime",
            "[\"hello world one\",\"hello world two\",\"hello world three\"]",
        );
        let check = |port: &str| {
            std::fs::write(dir.join("src/port.rs"), port).unwrap();
            runtime_check(&dir, &m)
        };
        assert!(check("pub fn f() -> u8 { 1 }\n").passed);
        for (what, port) in [
            (
                "Command::new",
                "pub fn f() { let _ = std::process::Command::new(\"node\").arg(\"orig.js\").output(); }\n",
            ),
            (
                "include_bytes outside the crate",
                "pub static D: &[u8] = include_bytes!(\"../../original/data.bin\");\n",
            ),
            (
                "include_str of the recording",
                "pub static D: &str = include_str!(\"../cases.jsonl\");\n",
            ),
            (
                "include of a computed path",
                "pub static D: &str = include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/d.txt\"));\n",
            ),
            (
                "a module from outside the crate",
                "#[path = \"../../elsewhere/t.rs\"]\nmod t;\n",
            ),
            (
                "the crate's own place",
                "pub fn f() -> String { std::env::var(\"CARGO_MANIFEST_DIR\").unwrap_or_default() }\n",
            ),
        ] {
            let c = check(port);
            assert!(!c.passed, "{what}: {c:?}");
        }
        // A copy of the recording inside the crate is read through its content.
        std::fs::write(
            dir.join("src/d.txt"),
            "hello world one\nhello world two\nhello world three\n",
        )
        .unwrap();
        let c = check("pub static D: &str = include_str!(\"d.txt\");\n");
        assert!(
            !c.passed && c.detail.contains("holds 3 recorded values"),
            "{c:?}"
        );
        std::fs::write(dir.join("src/d.txt"), "just a table of unicode ranges\n").unwrap();
        assert!(check("pub static D: &str = include_str!(\"d.txt\");\n").passed);
        // In a test module the same thing is not part of the port.
        assert!(
            check("pub fn f() {}\n#[cfg(test)]\nmod t { fn r() { let _ = std::process::Command::new(\"node\"); } }\n")
                .passed
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn a_build_script_a_proc_macro_and_extra_build_dependencies_are_the_bridges_or_absent() {
        let (dir, m) = crate_with("guard-cargo", "[1]");
        std::fs::write(dir.join("src/port.rs"), "pub fn f() {}\n").unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"demo\"\n[build-dependencies]\nnapi-build = \"2\"\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("build.rs"),
            "fn main() {\n    napi_build::setup();\n}\n",
        )
        .unwrap();
        assert!(runtime_check(&dir, &m).passed);
        std::fs::write(
            dir.join("build.rs"),
            "fn main() {\n    napi_build::setup();\n    std::fs::write(\"src/t.rs\", \"x\").ok();\n}\n",
        )
        .unwrap();
        assert!(
            !runtime_check(&dir, &m).passed,
            "a build.rs that is not bridge's"
        );
        std::fs::remove_file(dir.join("build.rs")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"demo\"\n[lib]\nproc-macro = true\n[build-dependencies]\ncc = \"1\"\n",
        )
        .unwrap();
        let c = runtime_check(&dir, &m);
        assert!(
            !c.passed && c.detail.contains("procedural macro") && c.detail.contains("`cc`"),
            "{c:?}"
        );
        // A path dependency is part of the port: what it starts is found.
        std::fs::create_dir_all(dir.join("dep/src")).unwrap();
        std::fs::write(
            dir.join("dep/src/lib.rs"),
            "pub fn g() { let _ = std::process::Command::new(\"python3\"); }\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"demo\"\n[dependencies]\ndep = { path = \"dep\" }\n",
        )
        .unwrap();
        let c = runtime_check(&dir, &m);
        assert!(!c.passed && c.detail.contains("dep/src/lib.rs"), "{c:?}");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A repository with the original `lib.ts` at its root, the bridged crate `rust/unit-rs` that
    /// re-exports the library crate `rust/core/lib` it depends on by path, as after a hand lift.
    fn bridge_over_library(tag: &str) -> (PathBuf, PathBuf, PathBuf, Manifest) {
        let (repo, m) = crate_with(
            tag,
            "[\"hello world one\",\"hello world two\",\"hello world three\"]",
        );
        let krate = repo.join("rust/unit-rs");
        let lib = repo.join("rust/core/lib");
        std::fs::create_dir_all(krate.join("src")).unwrap();
        std::fs::create_dir_all(lib.join("src/port")).unwrap();
        std::fs::copy(repo.join(CASES), krate.join(CASES)).unwrap();
        std::fs::write(krate.join("src/port.rs"), "pub use core_lib::frame;\n").unwrap();
        std::fs::write(
            krate.join("Cargo.toml"),
            "[package]\nname = \"unit-rs\"\n[dependencies]\ncore-lib = { path = \"../core/lib\" }\n",
        )
        .unwrap();
        std::fs::write(lib.join("Cargo.toml"), "[package]\nname = \"core-lib\"\n").unwrap();
        (repo, krate, lib, m)
    }

    #[test]
    fn a_path_module_of_a_path_dependency_is_found_from_the_file_that_declares_it() {
        let (repo, krate, lib, m) = bridge_over_library("guard-dep-path-mod");
        std::fs::write(lib.join("src/port/doors.rs"), "pub fn open() {}\n").unwrap();
        let check = |lib_rs: &str| {
            std::fs::write(lib.join("src/lib.rs"), lib_rs).unwrap();
            runtime_check(&krate, &m)
        };
        let c = check("#[path = \"port/doors.rs\"]\nmod doors;\npub fn frame() {}\n");
        assert!(c.passed, "{c:?}");
        std::fs::write(repo.join("stray.rs"), "pub fn open() {}\n").unwrap();
        let c = check("#[path = \"../../../stray.rs\"]\nmod doors;\npub fn frame() {}\n");
        assert!(
            !c.passed && c.detail.contains("takes a module from `../../../stray.rs`"),
            "{c:?}"
        );
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn an_include_inside_a_path_dependency_is_judged_from_that_crate_not_the_bridged_one() {
        let (repo, krate, lib, m) = bridge_over_library("guard-dep-include");
        std::fs::write(lib.join("src/lib.rs"), "pub mod gpu;\npub fn frame() {}\n").unwrap();
        std::fs::write(lib.join("src/sum.wgsl"), "@compute fn main() {}\n").unwrap();
        let check = |gpu: &str| {
            std::fs::write(lib.join("src/gpu.rs"), gpu).unwrap();
            runtime_check(&krate, &m)
        };
        let c = check("pub static SUM: &str = include_str!(\"sum.wgsl\");\n");
        assert!(c.passed, "{c:?}");
        for (what, gpu) in [
            (
                "the original, outside the library",
                "pub static O: &str = include_str!(\"../../../../lib.ts\");\n",
            ),
            (
                "the recording in the bridged crate",
                "pub static O: &str = include_str!(\"../../../unit-rs/cases.jsonl\");\n",
            ),
            (
                "a program started from the library",
                "pub fn f() { let _ = std::process::Command::new(\"node\"); }\n",
            ),
        ] {
            let c = check(gpu);
            assert!(!c.passed, "{what}: {c:?}");
        }
        std::fs::write(
            lib.join("src/table.txt"),
            "hello world one\nhello world two\nhello world three\n",
        )
        .unwrap();
        let c = check("pub static T: &str = include_str!(\"table.txt\");\n");
        assert!(
            !c.passed && c.detail.contains("holds 3 recorded values"),
            "{c:?}"
        );
        std::fs::write(
            lib.join("src/copy.ts"),
            "export const f = (x: number) => x\n",
        )
        .unwrap();
        let c = check("pub static O: &str = include_str!(\"copy.ts\");\n");
        assert!(
            !c.passed && c.detail.contains("source in the original's language"),
            "{c:?}"
        );
        std::fs::write(lib.join("src/gpu.rs"), "pub fn g() {}\n").unwrap();
        std::fs::write(repo.join("data.txt"), "just a table of unicode ranges\n").unwrap();
        let mut wrapped = m.clone();
        wrapped.unit = "rust/core/lib/lib.ts".into();
        std::fs::copy(repo.join("lib.ts"), lib.join("lib.ts")).unwrap();
        std::fs::write(
            lib.join("src/lib.rs"),
            "pub static D: &str = include_str!(\"../data.txt\");\n",
        )
        .unwrap();
        std::fs::write(lib.join("data.txt"), "just a table of unicode ranges\n").unwrap();
        assert!(runtime_check(&krate, &m).passed);
        let c = runtime_check(&krate, &wrapped);
        assert!(
            !c.passed && c.detail.contains("a file outside the crate"),
            "a library that holds the original: {c:?}"
        );
        std::fs::write(
            krate.join("Cargo.toml"),
            "[package]\nname = \"unit-rs\"\n[dependencies]\nwhole = { path = \"../..\" }\n",
        )
        .unwrap();
        std::fs::write(
            repo.join("src/lib.rs"),
            "pub static D: &str = include_str!(\"../data.txt\");\n",
        )
        .unwrap();
        let c = runtime_check(&krate, &m);
        assert!(
            !c.passed && c.detail.contains("a file outside the crate"),
            "a dependency that holds the bridged crate: {c:?}"
        );
        std::fs::remove_dir_all(repo).unwrap();
    }

    fn panics(port: &str, failing: &[&str]) -> (Vec<PanicSite>, usize, usize) {
        let failing: BTreeSet<String> = failing.iter().map(|s| s.to_string()).collect();
        panic_sites(&[("src/port.rs".to_string(), port.to_string())], &failing)
    }

    #[test]
    fn panics_are_not_hidden_by_a_cfg_test_line_a_string_or_a_helper() {
        // The three snippets of the audit (A1-12), each of which passed `panics` before.
        let (bad, _, _) = panics(
            "#[cfg(test)]\nuse std::fmt;\npub fn f(v: Option<u8>) -> u8 { v.unwrap() }\n",
            &["f"],
        );
        assert_eq!(bad.len(), 1, "{bad:?}");
        let (bad, _, _) = panics(
            "pub fn f(v: Option<u8>) -> u8 { let _u = \"http://x\"; v.unwrap() }\n",
            &["f"],
        );
        assert_eq!(bad.len(), 1, "{bad:?}");
        let (bad, _, _) = panics(
            "fn helper(v: Option<u8>) -> u8 { v.unwrap() }\npub fn f(v: Option<u8>) -> u8 { helper(v) }\n",
            &["f"],
        );
        assert_eq!(bad.len(), 1, "{bad:?}");
        assert_eq!(
            (bad[0].function.as_str(), bad[0].from.as_str()),
            ("helper", "f")
        );
        // Not reached from a failing export, in a test module, or in a string: not a panic here.
        let (bad, _, _) = panics(
            "pub fn g(v: Option<u8>) -> u8 { v.unwrap() }\npub fn f() -> u8 { \".unwrap()\"; 1 }\n#[cfg(test)]\nmod t { fn x() { None::<u8>.unwrap(); } }\n",
            &["f"],
        );
        assert!(bad.is_empty(), "{bad:?}");
    }

    #[test]
    fn an_infallible_mark_needs_a_reason_and_is_counted() {
        let with = |mark: &str| {
            format!("pub fn f(v: Option<u8>) -> u8 {{\n    {mark}\n    v.unwrap()\n}}\n")
        };
        let (bad, excused, bare) = panics(
            &with("// INFALLIBLE: v is Some, checked by the caller"),
            &["f"],
        );
        assert!(bad.is_empty() && excused == 1 && bare == 0, "{bad:?}");
        let (bad, excused, bare) = panics(&with("// INFALLIBLE:"), &["f"]);
        assert_eq!((bad.len(), excused, bare), (1, 0, 1), "{bad:?}");
        // The marker inside a string is not a comment.
        let (bad, excused, _) = panics(
            "pub fn f(v: Option<u8>) -> u8 { let _m = \"// INFALLIBLE: because\"; v.unwrap() }\n",
            &["f"],
        );
        assert_eq!((bad.len(), excused), (1, 0));
    }

    #[test]
    fn known_differences_added_or_beyond_a_tenth_of_the_cases_fail_until_accepted_by_number() {
        let dir = crate::app::temp_dir("guard-known").unwrap();
        let entry = r#"{"fn":"f","args":[1],"actual":2,"reason":"rounding"}"#;
        let write = |n: usize| {
            std::fs::write(
                dir.join("known-diffs.jsonl"),
                format!("{entry}\n").repeat(n),
            )
            .unwrap();
        };
        let opts = |n: Option<usize>| GateOptions {
            accept_known_diffs: n,
            ..GateOptions::default()
        };
        // No entries: no check.
        assert!(accepted_diffs_check(&dir, 0, 100, &opts(None)).is_none());
        // More than a tenth of the cases is a different port, with or without a baseline.
        write(2);
        let c = accepted_diffs_check(&dir, 2, 10, &opts(None)).unwrap();
        assert!(!c.passed && c.detail.contains("more than a tenth"), "{c:?}");
        assert!(
            accepted_diffs_check(&dir, 2, 10, &opts(Some(2)))
                .unwrap()
                .passed
        );
        // Two entries that no gate has seen: they fail, with the way out named.
        let c = accepted_diffs_check(&dir, 2, 100, &opts(None)).unwrap();
        assert!(!c.passed, "{c:?}");
        assert!(c.detail.contains("--accept-known-diffs 2"), "{}", c.detail);
        let c = accepted_diffs_check(&dir, 2, 100, &opts(Some(2))).unwrap();
        assert!(
            c.passed && c.detail.contains("named by --accept-known-diffs"),
            "{c:?}"
        );
        // After a passing gate they are the baseline; one more is new again.
        save_baseline(&dir, Some(2), None).unwrap();
        assert!(
            accepted_diffs_check(&dir, 2, 100, &opts(None))
                .unwrap()
                .passed
        );
        write(3);
        assert!(
            !accepted_diffs_check(&dir, 3, 100, &opts(None))
                .unwrap()
                .passed
        );
        // Both rules fail at once (1 added entry accepting 20 of 100 cases):
        // one failure command naming the number that clears both (`20`, not `1`).
        let dir_both = crate::app::temp_dir("guard-known-both").unwrap();
        std::fs::write(dir_both.join("known-diffs.jsonl"), format!("{entry}\n")).unwrap();
        let c = accepted_diffs_check(&dir_both, 20, 100, &opts(None)).unwrap();
        assert!(!c.passed, "{c:?}");
        assert!(c.detail.contains("--accept-known-diffs 20"), "{}", c.detail);
        assert!(!c.detail.contains("--accept-known-diffs 1"), "{}", c.detail);
        let c1 = accepted_diffs_check(&dir_both, 20, 100, &opts(Some(1))).unwrap();
        assert!(!c1.passed, "{c1:?}");
        assert!(
            c1.detail.contains("--accept-known-diffs 20"),
            "{}",
            c1.detail
        );
        let c20 = accepted_diffs_check(&dir_both, 20, 100, &opts(Some(20))).unwrap();
        assert!(c20.passed, "{c20:?}");
        std::fs::remove_dir_all(dir_both).unwrap();
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn a_recording_may_not_shrink_since_the_last_passing_gate() {
        let (dir, m) = crate_with("guard-shrink", "1");
        crate::recording::save_fingerprint(&dir, &m, None).unwrap();
        let mut more = std::fs::read_to_string(dir.join(CASES)).unwrap();
        more = more.repeat(5);
        std::fs::write(dir.join(CASES), &more).unwrap();
        crate::recording::save_fingerprint(&dir, &m, None).unwrap();
        save_baseline(&dir, None, None).unwrap();
        // Re-recorded with one case.
        std::fs::write(
            dir.join(CASES),
            more.lines().next().unwrap().to_string() + "\n",
        )
        .unwrap();
        crate::recording::save_fingerprint(&dir, &m, None).unwrap();
        let mut notes = Vec::new();
        let c = recording_check(&dir, &m, &GateOptions::default(), &mut notes).unwrap();
        assert!(!c.passed && c.detail.contains("shrank: 5 cases"), "{c:?}");
        let said = GateOptions {
            accept_smaller_recording: true,
            ..GateOptions::default()
        };
        let c = recording_check(&dir, &m, &said, &mut notes).unwrap();
        assert!(c.passed, "{c:?}");
        assert!(
            notes
                .iter()
                .any(|n| n.contains("--accept-smaller-recording")),
            "{notes:?}"
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A repository `R` and its crate `R/rust/unit` bridged for `src/a.ts` (exports `f` and `g`),
    /// with these lines in `cases.jsonl`.
    fn unit_repo(tag: &str, cases: &[&str]) -> (std::path::PathBuf, std::path::PathBuf) {
        let repo = crate::app::temp_dir(tag).unwrap();
        let dir = repo.join("rust/unit");
        std::fs::create_dir_all(&dir).unwrap();
        let export = |name: &str| {
            serde_json::json!({
                "name": name, "file": "src/a.ts", "line": 1, "params": [], "returns": "number",
                "is_async": false,
            })
        };
        let manifest = serde_json::json!({
            "schema": "rust-anything/bridge@1",
            "root": "../..",
            "unit": "src/a.ts",
            "language": "ts",
            "kind": "napi",
            "crate_name": "unit",
            "exports": [export("f"), export("g")],
            "classes": [],
            "js_only": [],
        });
        std::fs::write(
            dir.join("rust-anything.json"),
            serde_json::to_string_pretty(&manifest).unwrap(),
        )
        .unwrap();
        std::fs::write(dir.join("cases.jsonl"), format!("{}\n", cases.join("\n"))).unwrap();
        (repo, dir)
    }

    fn coverage(dir: &std::path::Path) -> Check {
        let manifest = crate::bridge::Manifest::load(dir).unwrap();
        super::coverage_check(dir, &manifest)
    }

    #[test]
    fn coverage_fails_for_an_export_without_a_case_and_names_it() {
        let (repo, dir) = unit_repo("gate-cov-fail", &[r#"{"fn":"f","args":[],"ok":1}"#]);
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(!check.passed, "{}", check.detail);
        assert!(
            check
                .detail
                .contains("1 of the unit's exports has no recorded case")
        );
        assert!(
            check.detail.contains("export:src/a.ts#g"),
            "{}",
            check.detail
        );
        assert!(
            !check.detail.contains("export:src/a.ts#f"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn coverage_passes_when_every_export_has_a_case() {
        let (repo, dir) = unit_repo(
            "gate-cov-pass",
            &[
                r#"{"fn":"f","args":[],"ok":1}"#,
                r#"{"fn":"g","args":[],"ok":2}"#,
            ],
        );
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(check.passed, "{}", check.detail);
    }

    #[test]
    fn coverage_passes_for_an_export_the_decisions_waive() {
        let (repo, dir) = unit_repo("gate-cov-waived", &[r#"{"fn":"f","args":[],"ok":1}"#]);
        std::fs::write(
            repo.join("rust/DECISIONS.md"),
            "# Decisions\n\n## ADR-001: Waive g\nStatus: accepted\nDecision: `export:src/a.ts#g`\n",
        )
        .unwrap();
        std::fs::write(
            repo.join("rust/obligations-decisions.toml"),
            "[[waive]]\nadr = \"ADR-001\"\ndate = \"2026-01-02\"\nreason = \"never called\"\nitems = [\"export:src/a.ts#g\"]\n",
        )
        .unwrap();
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(check.passed, "{}", check.detail);
    }

    #[test]
    fn coverage_fails_when_the_decisions_cannot_be_read() {
        let (repo, dir) = unit_repo(
            "gate-cov-invalid",
            &[
                r#"{"fn":"f","args":[],"ok":1}"#,
                r#"{"fn":"g","args":[],"ok":2}"#,
            ],
        );
        std::fs::write(repo.join("rust/obligations-decisions.toml"), "not [toml\n").unwrap();
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(!check.passed);
        assert!(
            check
                .detail
                .contains("the waived obligations could not be read"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn coverage_without_any_case_file_fails_every_export() {
        let (repo, dir) = unit_repo("gate-cov-nofile", &[]);
        std::fs::remove_file(dir.join("cases.jsonl")).unwrap();
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(!check.passed);
        assert!(
            check
                .detail
                .contains("2 of the unit's exports have no recorded case"),
            "{}",
            check.detail
        );
    }

    #[cfg(unix)]
    #[test]
    fn coverage_fails_with_the_reason_when_the_cases_are_a_link_out() {
        let outside = crate::app::temp_dir("gate-cov-outside").unwrap();
        std::fs::write(
            outside.join("cases.jsonl"),
            "{\"fn\":\"f\",\"args\":[],\"ok\":1}\n{\"fn\":\"g\",\"args\":[],\"ok\":2}\n",
        )
        .unwrap();
        let (repo, dir) = unit_repo("gate-cov-link", &[]);
        std::fs::remove_file(dir.join("cases.jsonl")).unwrap();
        std::os::unix::fs::symlink(outside.join("cases.jsonl"), dir.join("cases.jsonl")).unwrap();
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        std::fs::remove_dir_all(&outside).unwrap();
        // Cases read through the link would have covered everything: the check fails on the guard.
        assert!(!check.passed, "{}", check.detail);
        assert!(
            check.detail.contains("cases.jsonl is not opened"),
            "{}",
            check.detail
        );
        assert!(
            !check.detail.contains("no recorded case"),
            "a refusal is not a missing case: {}",
            check.detail
        );
    }

    #[test]
    fn coverage_fails_with_the_reason_when_the_cases_are_not_an_ordinary_file() {
        let (repo, dir) = unit_repo("gate-cov-dir", &[]);
        std::fs::remove_file(dir.join("cases.jsonl")).unwrap();
        std::fs::create_dir(dir.join("cases.jsonl")).unwrap();
        let check = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(!check.passed, "{}", check.detail);
        assert!(
            check.detail.contains("cases.jsonl is not opened"),
            "{}",
            check.detail
        );
    }

    /// A real unit, bridged from a fixture in its own temporary repository: are the ids that
    /// `coverage` asks for the registry's, the ones `waive` accepts? Returns those `coverage` asks
    /// for and the registry does not know (nothing is hidden: `waive` refuses them, and `coverage`
    /// still asks for them after every other one is waived). No language tool is run: the bridge
    /// only reads the sources.
    fn concordance(fixture: &str, unit: &str) -> Vec<String> {
        let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures")
            .join(fixture);
        let repo = crate::app::temp_dir(&format!("gate-concord-{fixture}")).unwrap();
        crate::http::copy_tree(&source, &repo).unwrap();
        let dir = repo.join("rust/unit");
        crate::bridge::bridge(&crate::bridge::Options {
            root: &repo,
            unit,
            kind: None,
            out: Some(dir.clone()),
            name: None,
            force: false,
            keep: Vec::new(),
            lang: None,
            batch: Vec::new(),
            as_json: Vec::new(),
            allocator: Default::default(),
        })
        .unwrap();
        let manifest = crate::bridge::Manifest::load(&dir).unwrap();

        let wanted: Vec<String> = crate::obligations::evidence::exports_without_case(
            &manifest,
            &crate::obligations::evidence::parse_cases(""),
        )
        .into_iter()
        .map(|u| u.id)
        .collect();
        assert!(!wanted.is_empty(), "{fixture}: the unit has exports");
        let before = coverage(&dir);
        assert!(!before.passed, "{fixture}: {}", before.detail);

        // The ids the repository's registry knows, and those it does not.
        let root = repo.canonicalize().unwrap();
        let ledger = crate::obligations::ledger(&root, None).unwrap();
        let (known, unknown): (Vec<String>, Vec<String>) = wanted
            .iter()
            .cloned()
            .partition(|id| ledger.obligations.iter().any(|o| &o.id == id));

        // `waive` accepts every known id; an unknown one is refused, and nothing hides it.
        if !known.is_empty() {
            crate::obligations::standing::waive(&repo, &known, "concordance test").unwrap();
        }
        for id in &unknown {
            let refused = crate::obligations::standing::waive(
                &repo,
                std::slice::from_ref(id),
                "concordance test",
            );
            assert!(
                refused.is_err(),
                "{fixture}: `{id}` is waived though unknown"
            );
        }
        let after = coverage(&dir);
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(
            after.passed,
            unknown.is_empty(),
            "{fixture}: {}",
            after.detail
        );
        for id in &unknown {
            assert!(after.detail.contains(id.as_str()), "{}", after.detail);
        }
        unknown
    }

    #[test]
    fn coverage_ids_match_the_registry_and_waive_for_a_python_unit() {
        // A known divergence that hides nothing: class `Stack` is defined in `stack.py`;
        // `coverage` asks for it as `export:src/textkit/stack.py#Stack` (the bridge's id), while
        // the registry lists it only re-exported, as `export:src/textkit/__init__.py#Stack` (and
        // its methods as `stack.py#Stack.<method>`). `waive` refuses the bridge's id, so
        // `coverage` still asks for it: only a recorded case lifts it. Every other id agrees and
        // is waived. When the two forms meet, this test must say so.
        let unknown = concordance("python", "src/textkit/");
        assert_eq!(unknown, ["export:src/textkit/stack.py#Stack"]);
    }

    #[test]
    fn coverage_ids_match_the_registry_and_waive_for_a_c_unit() {
        let unknown = concordance("c", "src/text.c");
        assert_eq!(unknown, Vec::<String>::new());
    }

    #[test]
    fn a_lifted_flag_is_believed_only_while_the_app_has_no_way_back_to_the_original() {
        let repo = crate::app::temp_dir("guard-lifted").unwrap();
        std::fs::create_dir_all(repo.join("rust/app/src/units")).unwrap();
        std::fs::create_dir_all(repo.join("rust/tool-rs")).unwrap();
        let unit = repo.join("rust/tool-rs");
        assert!(lifted_problems(&unit).is_empty());
        std::fs::write(repo.join("rust/app/src/original.rs"), "").unwrap();
        assert!(lifted_problems(&unit)[0].contains("original.rs still exists"));
        std::fs::remove_file(repo.join("rust/app/src/original.rs")).unwrap();
        std::fs::write(
            repo.join("rust/app/src/units/tool.rs"),
            "fn go() { crate::original::run(); }\n",
        )
        .unwrap();
        assert!(lifted_problems(&unit)[0].contains("original::"));
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn test_ranges_cover_only_the_item_under_the_attribute() {
        let code = "#[cfg(test)]\nuse a::b;\nfn keep() {}\n#[test]\nfn t() {\n    x();\n}\nfn keep2() {}\n#[cfg(test)]\nmod tests {\n    fn y() {}\n}\n";
        assert_eq!(test_ranges(code), vec![(1, 2), (4, 7), (9, 12)]);
    }
}