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.

225 KB
Raw Blame
//! App-level record and replay for CLIs, in any language: the program is a black box.
//!
//! `record` runs the original on cases (the app's own examples, an inputs file, semantic traps)
//! twice, marks what differs between the two runs as noise, and writes each case as trycmd files
//! in `rust/app-cases/`. `replay` runs any build against those files and reports what differs.

use crate::walk::Canonical;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail, ensure};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use toml_edit::{DocumentMut, Item, Table, value};

pub const CASES_DIR: &str = "rust/app-cases";
pub const CONFIG_FILE: &str = "rust-anything.json";
pub const REPORT_FILE: &str = "replay-report.md";
pub const FALLBACK_ENV: &str = "RUST_ANYTHING_FALLBACK_LOG";
/// The variable that makes a generated front door journal its fallbacks (`obligations fallbacks`
/// reads the file). The writer is `front_door_journal.rs.in`, which spells the same name.
pub const JOURNAL_ENV: &str = "RUST_ANYTHING_FALLBACK_JOURNAL";
pub const BUILTIN_NORMALIZERS: [&str; 3] = ["timestamps", "uuids", "key-order"];
pub(crate) const SCHEMA: &str = "rust-anything/app-cases@1";
pub(crate) const MAX_TRAPS: usize = 300;
pub(crate) const FRESH_DIR: &str = "files";
const REMOVED_EXT: &str = "removed";
const MAX_INPUT_FILE: u64 = 1 << 20;
const TIMESTAMP: &str = r"\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4}(?: \([^)\n]*\))?|\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?|\b\d{2}:\d{2}:\d{2}(?:[.,]\d+)?\b";
const UUID: &str =
    r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b";

pub(crate) const INT_TRAPS: [&str; 8] = [
    "-7",
    "0",
    "-1",
    "2147483648",
    "9007199254740993",
    "9223372036854775807",
    "-9223372036854775808",
    "18446744073709551616",
];
pub(crate) const FLOAT_TRAPS: [&str; 7] = [
    "-0.0",
    "0.1",
    "0.30000000000000004",
    "1e21",
    "1e-7",
    "5e-324",
    "1.7976931348623157e308",
];
pub(crate) const STRING_TRAPS: [&str; 10] = [
    "héllo wörld",
    "👍🏽 thumbs",
    "日本語",
    "",
    "e\u{301}",
    "İstanbul",
    "straße",
    "ılık ırmak",
    "👨\u{200D}👩\u{200D}👧 family",
    "a\u{00A0}b",
];
pub(crate) const STDIN_TRAPS: [&str; 4] = [
    "naïve café 👍🏽\nsecond line\n",
    "",
    "日本語 テキスト\r\nline two\r\n",
    "  spaced   out  \n\n",
];
pub(crate) const JSON_TRAPS: [&str; 2] = [
    r#"{"zebra":1,"apple":2,"10":3,"2":4,"é":5,"Apple":6}"#,
    r#"{"n":9007199254740993,"f":1e21,"t":0.1,"neg":-7}"#,
];
const NOT_APP_NAMES: [&str; 29] = [
    "node", "nodejs", "python", "python3", "py", "ruby", "java", "go", "deno", "bun", "tsx",
    "ts-node", "sh", "bash", "zsh", "cargo", "npx", "npm", "pnpm", "yarn", "uv", "poetry",
    "bundle", "run", "exec", "env", "sudo", "php", "dotnet",
];

/// `rust/app-cases/rust-anything.json`: how to run the original, and the normalizers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub schema: String,
    pub name: String,
    pub run: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub normalize: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub normalizers: BTreeMap<String, String>,
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
    /// Set when the app is a server: cases are requests, in `http/`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http: Option<crate::http::HttpConfig>,
    /// Numbers in the output match within this relative tolerance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub float_tolerance: Option<f64>,
    /// Written files holding raw floats, by path: compared value by value (`f32le`, `f64le`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub float_files: BTreeMap<String, String>,
    /// Outputs whose line order the original's own runs disagreed on, by case: their lines must
    /// match in any order.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub unordered: BTreeMap<String, Vec<String>>,
    /// With a normalizer that can match a line break saved: the outputs in which one did, by case
    /// (`stdout`, `stderr`, `file <path>`), so the lifted `cargo test` skips only those cases.
    /// Absent in a recording made before it was kept: every case with a `[..]` is skipped then.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub across_lines: Option<BTreeMap<String, Vec<String>>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effects: Option<crate::effects::EffectsConfig>,
    /// CLIs: repository paths copied (from the snapshot in `files/`) into the working directory
    /// before every case; a path ending in `/` gives its contents.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fresh: Vec<String>,
    /// The cases the last `app record` wrote, so the next one can remove those it no longer
    /// writes without touching cases written by hand.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub recorded: Vec<String>,
}

pub(crate) fn default_timeout() -> u64 {
    30
}

pub(crate) fn check_timeout(timeout_secs: Option<u64>) -> Result<()> {
    ensure!(
        timeout_secs != Some(0),
        "--timeout must be at least 1 second"
    );
    Ok(())
}

impl Config {
    pub fn new(name: &str) -> Config {
        Config {
            schema: SCHEMA.to_string(),
            name: name.to_string(),
            run: Vec::new(),
            normalize: Vec::new(),
            normalizers: BTreeMap::new(),
            timeout_secs: default_timeout(),
            http: None,
            float_tolerance: None,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::new(),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        }
    }

    pub fn load(repo: &Path) -> Result<Option<Config>> {
        let path = cases_dir(repo).join(CONFIG_FILE);
        if !path.exists() {
            return Ok(None);
        }
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        Ok(Some(
            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
        ))
    }
}

pub fn cases_dir(repo: &Path) -> PathBuf {
    if crate::spec::is_new_app(repo) {
        repo.join(crate::spec::CASES)
    } else {
        repo.join(CASES_DIR)
    }
}

/// `rust/app-cases/rust-anything.cases.json`: what `app record` wrote for each case, kept next to
/// the cases so a replay can tell an edited, skipped or removed case from the recording, and
/// which fields hold wildcards the recording made (every other field is compared as written).
/// A recording without it is a legacy one: its `[..]` and `...` lines are read as wildcards.
pub(crate) const META_FILE: &str = "rust-anything.cases.json";

#[derive(Debug, Default, Serialize, Deserialize)]
pub(crate) struct CaseMeta {
    #[serde(default)]
    pub schema: String,
    /// What the original ran on when it was recorded: `runtime` (the interpreter's version line)
    /// and `package` (`name@version` of the npm package the command runs), when they are known.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub original: BTreeMap<String, String>,
    #[serde(default)]
    pub cases: BTreeMap<String, CaseEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CaseEntry {
    /// SHA-256 over the case's files as `app record` wrote them.
    pub digest: String,
    /// The fields whose `[..]` and `...` lines are the recording's noise: `stdout`, `stderr`,
    /// `effects`, `file <path>`.
    #[serde(default)]
    pub wild: Vec<String>,
}

impl CaseMeta {
    pub(crate) fn load(dir: &Path) -> Result<Option<CaseMeta>> {
        let path = dir.join(META_FILE);
        if !path.exists() {
            return Ok(None);
        }
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        Ok(Some(Self::parse(&text).with_context(|| {
            format!(
                "parsing {}: record again with `rust-anything app record`",
                path.display()
            )
        })?))
    }

    /// The file's text as `load` reads it, for a caller that opens the file itself (the
    /// obligations' wildcard sweep, under its own guard).
    pub(crate) fn parse(text: &str) -> serde_json::Result<CaseMeta> {
        serde_json::from_str(text)
    }

    pub(crate) fn save(&mut self, dir: &Path) -> Result<()> {
        self.schema = "rust-anything-cases/1".to_string();
        std::fs::write(
            dir.join(META_FILE),
            serde_json::to_string_pretty(self)? + "\n",
        )
        .with_context(|| format!("writing {}", dir.join(META_FILE).display()))
    }
}

/// Whether `replay` reads `[..]` and `...` lines as wildcards in `field` of a case, given what
/// `app record` kept of it: a case it wrote reads them only where it made them, and a legacy or
/// hand-written case (no entry) reads them everywhere, as it always did. The one definition:
/// `check` compares with it, and the obligations' wildcard sweep asks it which fields to examine.
pub(crate) fn wild_in(entry: Option<&CaseEntry>, field: &str) -> bool {
    entry.is_none_or(|e| e.wild.iter().any(|f| f == field))
}

/// The name of a written file's field, as `check` compares it and as a case's `wild` list holds it.
pub(crate) fn file_field(path: &Path) -> String {
    format!("file {}", path.display())
}

/// A fingerprint of everything that makes up one case: its `.toml`, input and expected output.
pub(crate) fn case_digest(dir: &Path, name: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hash = Sha256::new();
    let mut feed = |label: &str, bytes: &[u8]| {
        hash.update((label.len() as u64).to_le_bytes());
        hash.update(label.as_bytes());
        hash.update((bytes.len() as u64).to_le_bytes());
        hash.update(bytes);
    };
    for ext in CASE_FILES {
        let path = dir.join(format!("{name}.{ext}"));
        if path.is_file() {
            feed(ext, &std::fs::read(&path).unwrap_or_default());
        } else if path.is_dir() {
            for file in walk_files(&path) {
                let rel = file.strip_prefix(&path).unwrap_or(&file);
                feed(
                    &format!("{ext}/{}", rel.to_string_lossy().replace('\\', "/")),
                    &std::fs::read(&file).unwrap_or_default(),
                );
            }
        }
    }
    hash.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

/// Whether this process already said a recording is a legacy one.
static LEGACY_NOTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

fn note_once(text: &str) {
    if !LEGACY_NOTED.swap(true, Ordering::SeqCst) {
        eprintln!("{text}");
    }
}

/// One line of an `--inputs` file.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub stdin: Option<String>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub files: BTreeMap<String, String>,
    #[serde(default)]
    pub remove: Vec<String>,
}

#[derive(Debug, Clone)]
struct Case {
    args: Vec<String>,
    stdin: Option<Vec<u8>>,
    env: BTreeMap<String, String>,
    env_remove: Vec<String>,
    inherit_env: bool,
    files: BTreeMap<PathBuf, Vec<u8>>,
    remove: Vec<PathBuf>,
}

impl Case {
    fn new(args: Vec<String>) -> Self {
        Case {
            args,
            stdin: None,
            env: BTreeMap::new(),
            env_remove: Vec::new(),
            inherit_env: true,
            files: BTreeMap::new(),
            remove: Vec::new(),
        }
    }

    fn key(&self) -> String {
        serde_json::json!([self.args, self.stdin, self.env, self.files, self.remove]).to_string()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Status {
    Code(i32),
    Killed,
    Timeout,
}

impl std::fmt::Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Status::Code(c) => write!(f, "exit code {c}"),
            Status::Killed => write!(f, "killed by a signal"),
            Status::Timeout => write!(f, "timed out"),
        }
    }
}

struct Run {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    status: Status,
    files: BTreeMap<PathBuf, Vec<u8>>,
    removed: Vec<PathBuf>,
    fallback: Option<bool>,
    effects: Option<Vec<u8>>,
}

impl Run {
    fn written(&self, case: &Case) -> BTreeMap<PathBuf, Vec<u8>> {
        self.files
            .iter()
            .filter(|(path, bytes)| case.files.get(*path) != Some(*bytes))
            .map(|(p, b)| (p.clone(), b.clone()))
            .collect()
    }
}

pub(crate) struct Normalizers {
    patterns: Vec<Regex>,
    key_order: bool,
    float_tolerance: Option<f64>,
    float_files: BTreeMap<PathBuf, usize>,
    unordered: BTreeMap<String, Vec<String>>,
}

impl Normalizers {
    pub(crate) fn new(config: &Config) -> Result<Self> {
        let mut sources: Vec<(&str, &str)> = Vec::new();
        let mut key_order = false;
        for name in &config.normalize {
            match name.as_str() {
                "timestamps" => sources.push((name, TIMESTAMP)),
                "uuids" => sources.push((name, UUID)),
                "key-order" => key_order = true,
                other => bail!(
                    "unknown normalizer `{other}`: use {} or define it as `name=regex`",
                    BUILTIN_NORMALIZERS.join(", ")
                ),
            }
        }
        sources.extend(
            config
                .normalizers
                .iter()
                .map(|(n, p)| (n.as_str(), p.as_str())),
        );
        let patterns = sources
            .iter()
            .map(|(name, pattern)| {
                Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))
            })
            .collect::<Result<Vec<_>>>()?;
        let float_tolerance = config
            .float_tolerance
            .map(crate::tolerance::check)
            .transpose()?;
        let float_files = config
            .float_files
            .iter()
            .map(|(path, format)| Ok((PathBuf::from(path), float_width(format)?)))
            .collect::<Result<_>>()?;
        Ok(Normalizers {
            patterns,
            key_order,
            float_tolerance,
            float_files,
            unordered: config.unordered.clone(),
        })
    }

    /// Whether `path` (relative to the case's `.out` folder) is a float file: it is compared as
    /// floats of this width, never as text.
    pub(crate) fn float_file(&self, path: &Path) -> Option<usize> {
        self.float_files.get(path).copied()
    }

    /// Whether the original's runs disagreed on the line order of this case's `field`.
    pub(crate) fn unordered(&self, case: &str, field: &str) -> bool {
        self.unordered
            .get(case)
            .is_some_and(|fields| fields.iter().any(|f| f == field))
    }

    pub(crate) fn apply(&self, text: &str) -> String {
        self.apply_tracked(text).0
    }

    /// `apply`, and whether a pattern replaced a match that holds a line break.
    fn apply_tracked(&self, text: &str) -> (String, bool) {
        let mut out = text.to_string();
        let mut across = false;
        for p in &self.patterns {
            out = p
                .replace_all(&out, |caps: &regex::Captures| {
                    across |= caps[0].contains('\n');
                    "[..]"
                })
                .into_owned();
        }
        (out, across)
    }

    /// Whether a normalizer folded a line break into a `[..]` in either run of `a` and `b`.
    fn crosses_lines(&self, a: &[u8], b: &[u8]) -> bool {
        [a, b]
            .iter()
            .filter_map(|bytes| std::str::from_utf8(bytes).ok())
            .any(|text| self.apply_tracked(text).1)
    }

    /// Which file of `actual` each file of `expected` is: the one at the same path, or else one
    /// whose path differs only where a normalizer matches (a file named by a time or an id).
    /// Several such files with the same shape pair up in sorted order.
    pub(crate) fn pair_files<'a>(
        &self,
        expected: impl Iterator<Item = &'a PathBuf>,
        actual: impl Iterator<Item = &'a PathBuf> + Clone,
    ) -> BTreeMap<PathBuf, PathBuf> {
        let exact: BTreeSet<&PathBuf> = actual.clone().collect();
        let mut pairs = BTreeMap::new();
        let mut loose: BTreeMap<String, Vec<&PathBuf>> = BTreeMap::new();
        for path in expected {
            if exact.contains(path) {
                pairs.insert(path.clone(), path.clone());
            } else {
                let shape = self.apply(&path.to_string_lossy());
                if shape != path.to_string_lossy() {
                    loose.entry(shape).or_default().push(path);
                }
            }
        }
        for (shape, wanted) in loose {
            // A file already paired by its exact path is a key of `pairs` (it maps to itself).
            let found: Vec<&PathBuf> = actual
                .clone()
                .filter(|path| {
                    !pairs.contains_key(*path) && self.apply(&path.to_string_lossy()) == shape
                })
                .collect();
            for (path, other) in wanted.into_iter().zip(found) {
                pairs.insert(path.clone(), other.clone());
            }
        }
        pairs
    }

    fn canonical(&self, text: &str) -> String {
        if self.key_order {
            sort_json_text(text)
        } else {
            text.to_string()
        }
    }
}

fn sort_value(v: Value) -> Value {
    match v {
        Value::Object(map) => {
            let sorted: BTreeMap<String, Value> =
                map.into_iter().map(|(k, v)| (k, sort_value(v))).collect();
            Value::Object(sorted.into_iter().collect())
        }
        Value::Array(items) => Value::Array(items.into_iter().map(sort_value).collect()),
        other => other,
    }
}

fn sort_json_text(text: &str) -> String {
    let trimmed = text.trim();
    if trimmed.starts_with(['{', '['])
        && let Ok(v) = serde_json::from_str::<Value>(trimmed)
    {
        return serde_json::to_string_pretty(&sort_value(v)).unwrap_or_default() + "\n";
    }
    text.split('\n')
        .map(|line| {
            let t = line.trim();
            if t.starts_with(['{', '['])
                && let Ok(v) = serde_json::from_str::<Value>(t)
            {
                return sort_value(v).to_string();
            }
            line.to_string()
        })
        .collect::<Vec<_>>()
        .join("\n")
}

pub(crate) fn temp_dir(tag: &str) -> Result<PathBuf> {
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    let dir = std::env::temp_dir().join(format!(
        "rust-anything-app-{tag}-{}-{}",
        std::process::id(),
        NEXT.fetch_add(1, Ordering::SeqCst)
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    Ok(dir)
}

/// Removes the `temp_dir(tag)` folders whose process is gone.
pub(crate) fn sweep_temp_dirs(tag: &str) {
    if !cfg!(unix) {
        return;
    }
    let prefix = format!("rust-anything-app-{tag}-");
    let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(pid) = name
            .to_str()
            .and_then(|n| n.strip_prefix(&prefix))
            .and_then(|rest| rest.split('-').next())
            .and_then(|pid| pid.parse::<u32>().ok())
        else {
            continue;
        };
        let gone = pid != std::process::id()
            && Command::new("ps")
                .args(["-p", &pid.to_string(), "-o", "pid="])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .is_ok_and(|s| !s.success());
        if gone {
            let _ = std::fs::remove_dir_all(entry.path());
        }
    }
}

pub(crate) fn resolve_word(repo: &Path, word: &str) -> String {
    if word.starts_with('-') {
        return word.to_string();
    }
    let path = repo.join(word);
    let looks_like_path = word.contains('/') || word.contains('\\') || path.is_file();
    if looks_like_path && path.exists() {
        return path
            .canonical()
            .unwrap_or(path)
            .to_string_lossy()
            .into_owned();
    }
    word.to_string()
}

#[cfg(any(windows, test))]
fn is_python_program(program: &str) -> bool {
    Path::new(program)
        .file_stem()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            ["python", "python3", "py"]
                .iter()
                .any(|candidate| name.eq_ignore_ascii_case(candidate))
        })
}

fn run_case(
    command: &[String],
    repo: &Path,
    case: &Case,
    timeout: Duration,
    effects: Option<&crate::effects::EffectsConfig>,
    base: Option<&Path>,
    sandboxed: bool,
) -> Result<Run> {
    let sandbox = temp_dir("run")?;
    let result = run_in(
        command, repo, case, timeout, &sandbox, effects, base, sandboxed,
    );
    let _ = std::fs::remove_dir_all(&sandbox);
    result
}

#[allow(clippy::too_many_arguments)]
fn run_in(
    command: &[String],
    repo: &Path,
    case: &Case,
    timeout: Duration,
    sandbox: &Path,
    effects: Option<&crate::effects::EffectsConfig>,
    base: Option<&Path>,
    sandboxed: bool,
) -> Result<Run> {
    let work = sandbox.join("cwd");
    std::fs::create_dir_all(&work)?;
    if let Some(base) = base {
        crate::http::copy_tree(base, &work)?;
    }
    for path in &case.remove {
        let target = work.join(path);
        if target.is_dir() {
            std::fs::remove_dir_all(&target)?;
        } else if target.exists() {
            std::fs::remove_file(&target)?;
        }
    }
    for (path, bytes) in &case.files {
        let target = work.join(path);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&target, bytes)?;
    }
    // The database lives where the case runs, so reset it there, before taking the snapshot that
    // tells the case's own writes apart.
    let sinks = effects
        .map(|config| -> Result<_> {
            let sinks = crate::effects::Sinks::start(config)?;
            sinks.reset(&work, repo)?;
            Ok(sinks)
        })
        .transpose()?;
    let before: BTreeMap<PathBuf, FileStamp> = walk_files(&work)
        .into_iter()
        .filter_map(|path| {
            let stamp = FileStamp::of(&path)?;
            Some((path.strip_prefix(&work).ok()?.to_path_buf(), stamp))
        })
        .collect();
    let log = sandbox.join("fallback.log");
    let (program, rest) = command.split_first().context("empty command")?;
    let mut cmd = Command::new(resolve_word(repo, program));
    cmd.args(rest.iter().map(|w| resolve_word(repo, w)))
        .args(&case.args)
        .current_dir(&work);
    if !case.inherit_env {
        cmd.env_clear();
    }
    #[cfg(windows)]
    if is_python_program(program)
        && (!case.inherit_env || std::env::var_os("PYTHONIOENCODING").is_none())
    {
        // Python otherwise inherits the legacy Windows console code page even though its stdio
        // is piped. UTF-8 keeps generated Unicode traps recordable; a case can still override it.
        cmd.env("PYTHONIOENCODING", "utf-8");
    }
    // The fallback journal belongs to a front door started by hand: a variable exported in the
    // shell must not make replays (or the original) write to a journal.
    cmd.env_remove(JOURNAL_ENV);
    for key in &case.env_remove {
        cmd.env_remove(key);
    }
    if let Some(sinks) = &sinks {
        cmd.envs(sinks.env());
    }
    cmd.envs(&case.env).env(FALLBACK_ENV, &log);
    if sandboxed {
        cmd = crate::process::Sandbox {
            read_only: repo,
            scratch: sandbox,
            writable: &[],
            loopback: sinks.is_some(),
        }
        .wrap(&cmd, case.inherit_env)?;
    }
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;
        cmd.process_group(0);
    }
    if crate::mcp::cancelled() {
        bail!(
            "`{}` was not started: the call was cancelled",
            command.join(" ")
        );
    }
    let mut child = cmd
        .spawn()
        .with_context(|| format!("running `{}`", command.join(" ")))?;
    let _tracked = crate::mcp::track(child.id());
    let stdin = child.stdin.take();
    let input = case.stdin.clone().unwrap_or_default();
    let writer = std::thread::spawn(move || {
        if let Some(mut pipe) = stdin {
            let _ = pipe.write_all(&input);
        }
    });
    let out_pipe = child.stdout.take().context("no stdout pipe")?;
    let err_pipe = child.stderr.take().context("no stderr pipe")?;
    let out_reader = crate::process::Drain::start(Some(out_pipe), usize::MAX);
    let err_reader = crate::process::Drain::start(Some(err_pipe), usize::MAX);
    let start = Instant::now();
    let status = loop {
        if let Some(s) = child.try_wait()? {
            let pipes_done =
                writer.is_finished() && out_reader.is_finished() && err_reader.is_finished();
            if pipes_done {
                break s.code().map_or(Status::Killed, Status::Code);
            }
        }
        if start.elapsed() > timeout || crate::mcp::cancelled() {
            #[cfg(unix)]
            {
                let _ = Command::new("/bin/kill")
                    .args(["-KILL", "--", &format!("-{}", child.id())])
                    .stderr(Stdio::null())
                    .status();
            }
            let _ = child.kill();
            let _ = child.wait();
            break Status::Timeout;
        }
        std::thread::sleep(Duration::from_millis(2));
    };
    if crate::mcp::cancelled() {
        bail!(
            "`{}` was stopped: the call was cancelled",
            command.join(" ")
        );
    }
    let (stdout, stderr) = if status == Status::Timeout {
        crate::process::settle(&[&out_reader, &err_reader]);
        if writer.is_finished() {
            let _ = writer.join();
        }
        (out_reader.take(), err_reader.take())
    } else {
        let _ = writer.join();
        (out_reader.finish(), err_reader.finish())
    };

    let cwd_forms = cwd_forms(&work);
    let redact = |bytes: Vec<u8>| -> Vec<u8> {
        match String::from_utf8(bytes) {
            Ok(text) => redact_cwd(text, &cwd_forms).into_bytes(),
            Err(e) => e.into_bytes(),
        }
    };
    let mut files = BTreeMap::new();
    let mut present = BTreeSet::new();
    for path in walk_files(&work) {
        let rel = path.strip_prefix(&work).unwrap_or(&path).to_path_buf();
        present.insert(rel.clone());
        let stamp = before.get(&rel);
        if stamp.is_some() && stamp == FileStamp::of(&path).as_ref() {
            continue;
        }
        let bytes = std::fs::read(&path).unwrap_or_default();
        if stamp.is_some()
            && !case.files.contains_key(&rel)
            && let Some(base) = base
            && std::fs::read(base.join(&rel)).is_ok_and(|b| b == bytes)
        {
            continue;
        }
        files.insert(rel, redact(bytes));
    }
    let removed = before
        .keys()
        .filter(|rel| !present.contains(*rel))
        .cloned()
        .collect();
    let fallback = std::fs::metadata(&log).ok().map(|m| m.len() > 0);
    let effects = sinks.map(|s| redact(s.take(&work, repo)));
    Ok(Run {
        stdout: redact(stdout),
        stderr: redact(stderr),
        status,
        files,
        removed,
        fallback,
        effects,
    })
}

#[derive(PartialEq, Eq)]
struct FileStamp {
    len: u64,
    modified: Option<std::time::SystemTime>,
}

impl FileStamp {
    fn of(path: &Path) -> Option<Self> {
        let meta = std::fs::metadata(path).ok()?;
        Some(FileStamp {
            len: meta.len(),
            modified: meta.modified().ok(),
        })
    }
}

fn walk_files(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.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 Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                stack.push(entry.path());
            } else if kind.is_file() {
                out.push(entry.path());
            }
        }
    }
    out.sort();
    out
}

fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
    let threads = std::thread::available_parallelism()
        .map_or(4, |n| n.get())
        .clamp(1, 8);
    let next = AtomicUsize::new(0);
    let results: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
    let call = crate::mcp::this_call();
    std::thread::scope(|s| {
        for _ in 0..threads {
            s.spawn(|| {
                call.enter(|| {
                    loop {
                        let i = next.fetch_add(1, Ordering::SeqCst);
                        let Some(item) = items.get(i) else { break };
                        let r = f(item);
                        if let Ok(mut slot) = results[i].lock() {
                            *slot = Some(r);
                        }
                    }
                });
            });
        }
    });
    results
        .into_iter()
        .filter_map(|m| m.into_inner().ok().flatten())
        .collect()
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Tok {
    pub(crate) text: String,
    pub(crate) op: bool,
}

pub(crate) fn shell_tokens(line: &str) -> Option<Vec<Tok>> {
    let mut toks = Vec::new();
    let mut cur = String::new();
    let mut in_tok = false;
    let mut chars = line.chars().peekable();
    let flush = |toks: &mut Vec<Tok>, cur: &mut String, in_tok: &mut bool| {
        if *in_tok {
            toks.push(Tok {
                text: std::mem::take(cur),
                op: false,
            });
            *in_tok = false;
        }
    };
    while let Some(c) = chars.next() {
        match c {
            ' ' | '\t' => flush(&mut toks, &mut cur, &mut in_tok),
            '\'' => {
                in_tok = true;
                loop {
                    match chars.next()? {
                        '\'' => break,
                        x => cur.push(x),
                    }
                }
            }
            '"' => {
                in_tok = true;
                loop {
                    match chars.next()? {
                        '"' => break,
                        '\\' => match chars.next()? {
                            x @ ('"' | '\\' | '$' | '`') => cur.push(x),
                            x => {
                                cur.push('\\');
                                cur.push(x);
                            }
                        },
                        '`' => return None,
                        '$' if chars.peek() == Some(&'(') => return None,
                        x => cur.push(x),
                    }
                }
            }
            '\\' => {
                in_tok = true;
                let mut following = chars.clone();
                let next = following.next();
                let after_next = following.next();
                let escaped_substitution = next == Some('$') && after_next == Some('(');
                let unc_prefix = cur.is_empty()
                    && next == Some('\\')
                    && after_next
                        .is_some_and(|c| !c.is_whitespace() && !"'\"\\|<>&;$`".contains(c));
                if cfg!(windows)
                    && (unc_prefix
                        || (!escaped_substitution
                            && !chars
                                .peek()
                                .is_some_and(|c| c.is_whitespace() || "'\"\\|<>&;`".contains(*c))))
                {
                    cur.push('\\');
                } else if let Some(x) = chars.next() {
                    cur.push(x);
                }
            }
            '|' | '<' | '>' | ';' | '&' => {
                flush(&mut toks, &mut cur, &mut in_tok);
                let mut op = c.to_string();
                while let Some(&n) = chars.peek() {
                    if !"|<>&".contains(n) {
                        break;
                    }
                    op.push(n);
                    chars.next();
                }
                toks.push(Tok { text: op, op: true });
            }
            '#' if !in_tok => break,
            '`' => return None,
            '$' if chars.peek() == Some(&'(') => return None,
            _ => {
                in_tok = true;
                cur.push(c);
            }
        }
    }
    flush(&mut toks, &mut cur, &mut in_tok);
    Some(toks)
}

/// Splits a command line into words, shell-style quoting, no shell operators.
pub fn shell_split(line: &str) -> Result<Vec<String>> {
    let toks = shell_tokens(line).with_context(|| format!("cannot split `{line}`"))?;
    if let Some(op) = toks.iter().find(|t| t.op) {
        bail!(
            "`{line}` uses the shell operator `{}`: put the pipeline in a script and give its path",
            op.text
        );
    }
    Ok(toks.into_iter().map(|t| t.text).collect())
}

pub(crate) fn shell_quote(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', r"'\''"))
    }
}

/// Format a path for a suggested command. Keep a cmd-compatible spelling for simple Windows
/// paths with backticks or typographic quotes when the hint previously printed them bare.
pub fn cli_path(path: impl AsRef<Path>) -> String {
    format_cli_word(&path.as_ref().to_string_lossy(), HintWord::BarePath)
}

pub(crate) fn quoted_cli_path(path: &Path) -> String {
    format_cli_word(&path.to_string_lossy(), HintWord::QuotedPath)
}

pub(crate) fn cli_arg(word: &str) -> String {
    format_cli_word(word, HintWord::Argument)
}

#[derive(Clone, Copy, PartialEq)]
enum HintWord {
    BarePath,
    QuotedPath,
    Argument,
}

fn format_cli_word(word: &str, kind: HintWord) -> String {
    let native_windows = cfg!(windows) && std::env::var_os("MSYSTEM").is_none();
    cli_word(word, native_windows, kind)
}

/// Native Windows hints use PowerShell syntax. Prefer double quotes for ordinary paths with
/// spaces so the same hint also works in cmd. Git Bash uses the POSIX form.
fn cli_word(word: &str, native_windows: bool, kind: HintWord) -> String {
    if !native_windows {
        return shell_quote(word);
    }
    // A terminal separator describes a directory. The dot keeps the closing quote away from
    // the backslash in the native argument parser (notably in Windows PowerShell 5.1).
    if kind != HintWord::Argument && word.ends_with('\\') && !word.starts_with(r"\\?\") {
        return cli_word(&format!("{word}."), true, kind);
    }
    let bare = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_alphanumeric() || "/:.-_+=".contains(c));
    if bare {
        word.to_string()
    } else if word.contains(['"', '“', '”', '„', '`']) || word.ends_with('\\') {
        // cmd reads PowerShell's single quotes literally. Preserve a previously bare argument
        // only if it contains no whitespace, interpolation or command operators.
        if kind == HintWord::BarePath
            && !word.ends_with('`')
            && word
                .chars()
                .all(|c| c.is_alphanumeric() || r"\/:._-+=“”„`".contains(c))
        {
            return word.to_owned();
        }
        powershell_literal(word)
    } else if word.contains('$') {
        // PowerShell expands $name inside double quotes. Leave each dollar just outside a
        // quoted segment, where it cannot start a variable. cmd joins the same segments.
        // Start with an unquoted prefix so PowerShell keeps all the pieces in one argument.
        let plain = word
            .find(|c: char| !c.is_alphanumeric() && !r"\/:._-".contains(c))
            .unwrap_or(word.len());
        // A backslash immediately before an opening quote escapes that quote in native argv.
        let first = if word[plain..].starts_with('$') {
            plain
        } else {
            word[..plain].trim_end_matches('\\').len()
        };
        let mut out = if first == 0 && !word.starts_with('$') {
            if kind == HintWord::Argument || plain > 1 {
                // A literal ID cannot gain a path prefix. Keep UNC and device prefixes intact.
                return powershell_literal(word);
            }
            if plain == 1 {
                // The quoted segment starts with the single root separator. A rooted dot
                // anchors it without putting a backslash directly before the opening quote.
                String::from(r"\.")
            } else {
                String::from("./")
            }
        } else {
            word[..first].to_owned()
        };
        for (i, part) in word[first..].split('$').enumerate() {
            if i != 0 {
                out.push('$');
            }
            if i == 0 && part.is_empty() {
                continue;
            }
            let body = part.trim_end_matches('\\');
            out.push('"');
            out.push_str(body);
            out.push('"');
            out.push_str(&part[body.len()..]);
        }
        out
    } else {
        format!("\"{word}\"")
    }
}

fn powershell_literal(word: &str) -> String {
    let mut literal = String::from("'");
    for c in word.chars() {
        if matches!(c, '\'' | '‘' | '’' | '‚' | '‛') {
            literal.push('\'');
        }
        literal.push(c);
    }
    literal.push('\'');
    literal
}

/// Format a repository path argument for CLI hints, omitted when the caller passed `.`.
pub fn cli_root_arg(root: &Path) -> String {
    if root == Path::new(".") {
        String::new()
    } else {
        format!(" {}", quoted_cli_path(root))
    }
}

/// The spellings of the case's folder that become `[CWD]`: resolved, as given, and each of those
/// with its backslashes doubled.
fn cwd_forms(work: &Path) -> Vec<String> {
    let mut forms = vec![work.to_string_lossy().into_owned()];
    if let Ok(real) = work.canonical() {
        forms.insert(0, real.to_string_lossy().into_owned());
    }
    with_escaped_backslashes(forms)
}

/// `forms`, then each one that holds a `\` with it doubled, the way a JSON string or a JS error's
/// `path` prints a Windows path.
fn with_escaped_backslashes(mut forms: Vec<String>) -> Vec<String> {
    let escaped: Vec<String> = forms
        .iter()
        .filter(|f| f.contains('\\'))
        .map(|f| f.replace('\\', r"\\"))
        .collect();
    forms.extend(escaped);
    forms
}

fn redact_cwd(mut text: String, forms: &[String]) -> String {
    for form in forms {
        text = text.replace(form.as_str(), "[CWD]");
    }
    text
}

/// The lines of `text`, each as it is: a `\r` stays, and a lone `\n` is one empty line, not none.
/// Whether the text ends with a newline is for the caller to compare.
fn lines(text: &str) -> Vec<&str> {
    if text.is_empty() {
        return Vec::new();
    }
    text.strip_suffix('\n')
        .unwrap_or(text)
        .split('\n')
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    Equal(usize, usize),
    Delete(usize),
    Insert(usize),
}

fn diff_ops<A, B>(a: &[A], b: &[B], eq: impl Fn(&A, &B) -> bool) -> Vec<Op> {
    let mut head = 0;
    while head < a.len() && head < b.len() && eq(&a[head], &b[head]) {
        head += 1;
    }
    let mut tail = 0;
    while tail < a.len() - head
        && tail < b.len() - head
        && eq(&a[a.len() - 1 - tail], &b[b.len() - 1 - tail])
    {
        tail += 1;
    }
    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);
    let mut ops: Vec<Op> = (0..head).map(|i| Op::Equal(i, i)).collect();
    let (n, m) = (am.len(), bm.len());
    if n * m <= 4_000_000 {
        let mut lcs = vec![vec![0u32; m + 1]; n + 1];
        for i in (0..n).rev() {
            for j in (0..m).rev() {
                lcs[i][j] = if eq(&am[i], &bm[j]) {
                    lcs[i + 1][j + 1] + 1
                } else {
                    lcs[i + 1][j].max(lcs[i][j + 1])
                };
            }
        }
        let (mut i, mut j) = (0, 0);
        while i < n || j < m {
            if i < n && j < m && eq(&am[i], &bm[j]) {
                ops.push(Op::Equal(head + i, head + j));
                i += 1;
                j += 1;
            } else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
                ops.push(Op::Delete(head + i));
                i += 1;
            } else {
                ops.push(Op::Insert(head + j));
                j += 1;
            }
        }
    } else {
        ops.extend((0..n).map(|i| Op::Delete(head + i)));
        ops.extend((0..m).map(|j| Op::Insert(head + j)));
    }
    ops.extend((0..tail).map(|k| Op::Equal(a.len() - tail + k, b.len() - tail + k)));
    ops
}

pub(crate) fn line_matches(expected: &str, actual: &str) -> bool {
    if !expected.contains("[..]") {
        return expected == actual;
    }
    let parts: Vec<&str> = expected.split("[..]").collect();
    let (first, last) = (parts[0], parts[parts.len() - 1]);
    let Some(rest) = actual.strip_prefix(first) else {
        return false;
    };
    let Some(mut rest) = rest.strip_suffix(last) else {
        return false;
    };
    for mid in &parts[1..parts.len() - 1] {
        match rest.find(mid) {
            Some(i) => rest = &rest[i + mid.len()..],
            None => return false,
        }
    }
    true
}

/// Whether a line can match a line it is not equal to: `[..]` stands for any text, and with a
/// tolerance a number can meet a nearby number. Any other line matches its own text and nothing
/// else, so comparing the sorted sides already settles those.
fn can_match_beyond_its_text(line: &str, tol: Option<f64>) -> bool {
    line.contains("[..]") || (tol.is_some() && line.bytes().any(|b| b.is_ascii_digit()))
}

/// Expected lines against actual lines in any order: every expected line paired with a distinct
/// actual line. Sorting both sides and pairing by position cannot do this once a line matches
/// more than its own text, because no order agrees with a match that is not transitive -- `10.0`
/// has to meet `9.999999999999999` while sorting before `2.0`. So identical lines are paired off
/// first, and the lines that are left get a search that gives a line up when another line needs
/// it.
fn lines_match_in_any_order(expected: &[&str], actual: &[&str], tol: Option<f64>) -> bool {
    if expected.len() != actual.len() {
        return false;
    }
    let (mut sorted_e, mut sorted_a) = (expected.to_vec(), actual.to_vec());
    sorted_e.sort_unstable();
    sorted_a.sort_unstable();
    if sorted_e == sorted_a {
        return true;
    }
    if !expected.iter().any(|l| can_match_beyond_its_text(l, tol)) {
        return false;
    }
    let mut spare: HashMap<&str, usize> = HashMap::new();
    for line in actual {
        *spare.entry(*line).or_default() += 1;
    }
    let mut rest_expected = Vec::new();
    for line in expected {
        match spare.get_mut(line) {
            Some(count) if *count > 0 => *count -= 1,
            _ => rest_expected.push(*line),
        }
    }
    let rest_actual: Vec<&str> = spare
        .into_iter()
        .flat_map(|(line, count)| std::iter::repeat_n(line, count))
        .collect();
    let mut holder: Vec<Option<usize>> = vec![None; rest_actual.len()];
    for want in 0..rest_expected.len() {
        let mut tried = vec![false; rest_actual.len()];
        if !take_a_line(
            want,
            &rest_expected,
            &rest_actual,
            tol,
            &mut tried,
            &mut holder,
        ) {
            return false;
        }
    }
    true
}

/// One augmenting step: find a line for `want`, moving the expected lines that already hold one
/// along to another line they also match.
fn take_a_line(
    want: usize,
    expected: &[&str],
    actual: &[&str],
    tol: Option<f64>,
    tried: &mut [bool],
    holder: &mut [Option<usize>],
) -> bool {
    for i in 0..actual.len() {
        if tried[i] || !line_matches_within(expected[want], actual[i], tol) {
            continue;
        }
        tried[i] = true;
        if holder[i].is_none_or(|held| take_a_line(held, expected, actual, tol, tried, holder)) {
            holder[i] = Some(want);
            return true;
        }
    }
    false
}

/// A line within the float tolerance, for lines without wildcards.
fn line_matches_within(expected: &str, actual: &str, tol: Option<f64>) -> bool {
    line_matches(expected, actual)
        || tol.is_some_and(|t| {
            !expected.contains("[..]") && crate::tolerance::line_close(expected, actual, t)
        })
}

/// The expected line that stands for any number of lines (trycmd's `...`). The one definition:
/// `text_matches` reads it, and the obligations' standing asks `has_line_wildcard` which recorded
/// files hold one.
const LINE_WILDCARD: &str = "...";

/// Whether an expected line is the any-number-of-lines wildcard.
fn is_line_wildcard(line: &str) -> bool {
    line == LINE_WILDCARD
}

/// Whether expected text holds a line `text_matches` takes for any number of lines.
pub(crate) fn has_line_wildcard(text: &str) -> bool {
    lines(text).into_iter().any(is_line_wildcard)
}

/// Whether `compare` reads `...` lines as wildcards in an expected file, given what the recording
/// says of that file: `binary` text is compared as bytes, and a file whose line order the
/// original's own runs disagreed on (`unordered`) is compared line against line. A float file is
/// compared by value and never reaches `compare`, so the caller leaves it out. Content that is
/// not UTF-8 is compared as bytes too; the caller checks that, since it holds the bytes.
pub(crate) fn reads_line_wildcards(binary: bool, unordered: bool) -> bool {
    !binary && !unordered
}

/// trycmd's matching: `[..]` is any text within a line, a `...` line is any number of lines.
fn text_matches(expected: &str, actual: &str, tol: Option<f64>) -> bool {
    // The final newline is part of the output, and `lines` leaves it out.
    if expected.ends_with('\n') != actual.ends_with('\n') {
        return false;
    }
    let (e, a) = (lines(expected), lines(actual));
    let m = a.len();
    let mut next = vec![false; m + 1];
    next[m] = true;
    for line in e.iter().rev() {
        let mut cur = vec![false; m + 1];
        for j in (0..=m).rev() {
            cur[j] = if is_line_wildcard(line) {
                next[j] || (j < m && cur[j + 1])
            } else {
                j < m && line_matches_within(line, a[j], tol) && next[j + 1]
            };
        }
        next = cur;
    }
    next[0]
}

fn render_diff(expected: &str, actual: &str, tol: Option<f64>) -> String {
    let (e, a) = (lines(expected), lines(actual));
    let ops = diff_ops(&e, &a, |x, y| line_matches_within(x, y, tol));
    let changed: Vec<bool> = ops.iter().map(|op| !matches!(op, Op::Equal(..))).collect();
    let near = |k: usize| {
        let lo = k.saturating_sub(3);
        let hi = (k + 4).min(ops.len());
        changed[lo..hi].iter().any(|c| *c)
    };
    let mut out = String::new();
    let mut skipped = false;
    for (k, op) in ops.iter().enumerate() {
        match op {
            Op::Equal(_, j) if near(k) => {
                skipped = false;
                out += &format!("  {}\n", a[*j]);
            }
            Op::Equal(..) => {
                if !skipped {
                    out += "  ⋮\n";
                    skipped = true;
                }
            }
            Op::Delete(i) => {
                skipped = false;
                out += &format!("- {}\n", e[*i]);
            }
            Op::Insert(j) => {
                skipped = false;
                out += &format!("+ {}\n", a[*j]);
            }
        }
    }
    let trail = |s: &str| s.ends_with('\n') || s.is_empty();
    if out.is_empty() || trail(expected) != trail(actual) {
        out += &format!(
            "(trailing newline: expected {}, got {})\n",
            trail(expected),
            trail(actual)
        );
    }
    out
}

fn tokens(line: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = None;
    for (i, c) in line.char_indices() {
        if c.is_alphanumeric() {
            start.get_or_insert(i);
        } else {
            if let Some(s) = start.take() {
                out.push(&line[s..i]);
            }
            out.push(&line[i..i + c.len_utf8()]);
        }
    }
    if let Some(s) = start {
        out.push(&line[s..]);
    }
    out
}

pub(crate) fn merge_line(a: &str, b: &str) -> String {
    let (ta, tb) = (tokens(a), tokens(b));
    if ta.len() != tb.len() {
        // A different number of tokens (a random number of words): what both lines start with
        // and end with stays, and only the middle is noise. Nothing in common is the whole line.
        let prefix = ta.iter().zip(&tb).take_while(|(x, y)| x == y).count();
        let room = ta.len().min(tb.len()) - prefix;
        let suffix = ta
            .iter()
            .rev()
            .zip(tb.iter().rev())
            .take(room)
            .take_while(|(x, y)| x == y)
            .count();
        return format!(
            "{}[..]{}",
            ta[..prefix].concat(),
            ta[ta.len() - suffix..].concat()
        );
    }
    let same: Vec<bool> = ta.iter().zip(&tb).map(|(x, y)| x == y).collect();
    let mut out = String::new();
    for (i, x) in ta.iter().enumerate() {
        if same[i] {
            // A separator two random values happen to share (`k2Pq_x9Lm4` and `Zt7w_bR3nV` both hold
            // `_`) is part of the noise, not of the format: keeping it makes a replay fail on an id
            // that has no `_`. It stays when a neighbour still matches, so `id=[..]` keeps its `=`.
            let fixed_neighbour = [i.checked_sub(1), Some(i + 1)]
                .into_iter()
                .flatten()
                .any(|j| same.get(j) == Some(&true));
            if x.chars().all(char::is_alphanumeric) || fixed_neighbour {
                out += x;
            }
            continue;
        }
        if !out.ends_with("[..]") {
            out += "[..]";
        }
    }
    out
}

/// Two runs of the original: what they agree on stays, what differs becomes a wildcard.
fn merge_noise(a: &str, b: &str) -> String {
    if a == b {
        return a.to_string();
    }
    let (la, lb): (Vec<&str>, Vec<&str>) = (a.split('\n').collect(), b.split('\n').collect());
    let ops = diff_ops(&la, &lb, |x, y| x == y);
    let mut out: Vec<String> = Vec::new();
    let (mut dels, mut ins): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
    let flush = |out: &mut Vec<String>, dels: &mut Vec<&str>, ins: &mut Vec<&str>| {
        if dels.is_empty() && ins.is_empty() {
            return;
        }
        if dels.len() == ins.len() {
            for (x, y) in dels.iter().zip(ins.iter()) {
                out.push(merge_line(x, y));
            }
        } else if out.last().map(String::as_str) != Some("...") {
            out.push("...".to_string());
        }
        dels.clear();
        ins.clear();
    };
    for op in ops {
        match op {
            Op::Equal(i, _) => {
                flush(&mut out, &mut dels, &mut ins);
                out.push(la[i].to_string());
            }
            Op::Delete(i) => dels.push(la[i]),
            Op::Insert(j) => ins.push(lb[j]),
        }
    }
    flush(&mut out, &mut dels, &mut ins);
    out.join("\n")
}

fn stem(word: &str) -> String {
    Path::new(word)
        .file_stem()
        .map(|s| s.to_string_lossy().to_lowercase())
        .unwrap_or_default()
}

/// Names the app is invoked by, most specific first.
fn app_names(repo: &Path, run: &[String], explicit: Option<&str>) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    let mut add = |name: &str| {
        let name = name.rsplit('/').next().unwrap_or(name).to_lowercase();
        if !name.is_empty() && !NOT_APP_NAMES.contains(&name.as_str()) && !names.contains(&name) {
            names.push(name);
        }
    };
    if let Some(name) = explicit {
        add(name);
    }
    for word in run {
        let path = repo.join(word);
        if word.starts_with('-') || path.is_dir() || Path::new(word).is_dir() {
            continue;
        }
        add(&stem(word));
    }
    if let Ok(text) = std::fs::read_to_string(repo.join("package.json"))
        && let Ok(pkg) = serde_json::from_str::<Value>(crate::lang::without_bom(&text))
    {
        match &pkg["bin"] {
            Value::String(_) => add(pkg["name"].as_str().unwrap_or_default()),
            Value::Object(map) => map.keys().for_each(|k| add(k)),
            _ => {}
        }
    }
    if let Ok(text) = std::fs::read_to_string(repo.join("pyproject.toml"))
        && let Ok(doc) = text.parse::<DocumentMut>()
    {
        for table in [
            doc.get("project").and_then(|p| p.get("scripts")),
            doc.get("tool")
                .and_then(|t| t.get("poetry"))
                .and_then(|p| p.get("scripts")),
        ]
        .into_iter()
        .flatten()
        {
            if let Some(t) = table.as_table_like() {
                t.iter().for_each(|(k, _)| add(k));
            }
        }
    }
    for (dir, dirs_only) in [("cmd", true), ("bin", false), ("exe", false)] {
        let Ok(entries) = std::fs::read_dir(repo.join(dir)) else {
            continue;
        };
        let mut found: Vec<String> = entries
            .flatten()
            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir() == dirs_only))
            .map(|e| stem(&e.file_name().to_string_lossy()))
            .collect();
        found.sort();
        found.iter().for_each(|n| add(n));
    }
    names
}

fn safe_relative(arg: &str) -> bool {
    let p = Path::new(arg);
    !arg.is_empty()
        && !arg.starts_with('-')
        && p.components().all(|c| matches!(c, Component::Normal(_)))
}

fn read_input_file(candidates: &[PathBuf]) -> Option<Vec<u8>> {
    candidates
        .iter()
        .find(|p| p.is_file() && std::fs::metadata(p).is_ok_and(|m| m.len() <= MAX_INPUT_FILE))
        .and_then(|p| std::fs::read(p).ok())
}

fn parse_example(line: &str, names: &[String], repo: &Path, doc_dir: &Path) -> Option<Case> {
    let toks = shell_tokens(line)?;
    let ops: Vec<usize> = (0..toks.len()).filter(|&i| toks[i].op).collect();
    let words = |range: &[Tok]| -> Vec<String> { range.iter().map(|t| t.text.clone()).collect() };
    let lookup = |arg: &str| -> Option<Vec<u8>> {
        if !safe_relative(arg) {
            return None;
        }
        read_input_file(&[repo.join(arg), doc_dir.join(arg)])
    };
    let (main, stdin): (Vec<String>, Option<Vec<u8>>) = match ops.as_slice() {
        [] => (words(&toks), None),
        [i] if toks[*i].text == "|" => {
            let feed = words(&toks[..*i]);
            let stdin = match feed.first().map(String::as_str) {
                Some("echo") => {
                    let newline = feed.get(1).map(String::as_str) != Some("-n");
                    let text: Vec<&str> = feed[1..]
                        .iter()
                        .map(String::as_str)
                        .filter(|w| !matches!(*w, "-n" | "-e"))
                        .collect();
                    let mut text = text.join(" ");
                    if newline {
                        text.push('\n');
                    }
                    text.into_bytes()
                }
                Some("printf") if feed.len() == 2 => feed[1]
                    .replace("\\n", "\n")
                    .replace("\\t", "\t")
                    .into_bytes(),
                Some("cat") if feed.len() == 2 => lookup(&feed[1])?,
                _ => return None,
            };
            (words(&toks[*i + 1..]), Some(stdin))
        }
        [i] if toks[*i].text == "<" && *i + 2 == toks.len() => {
            (words(&toks[..*i]), Some(lookup(&toks[*i + 1].text)?))
        }
        _ => return None,
    };
    let mut env = BTreeMap::new();
    let mut rest = main.as_slice();
    while let Some((first, tail)) = rest.split_first() {
        let Some((k, v)) = first.split_once('=') else {
            break;
        };
        if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            break;
        }
        env.insert(k.to_string(), v.to_string());
        rest = tail;
    }
    let (prog, args) = rest.split_first()?;
    if !names.contains(&stem(prog)) {
        return None;
    }
    let mut case = Case::new(args.to_vec());
    case.env = env;
    case.stdin = stdin;
    for arg in args {
        if let Some(bytes) = lookup(arg) {
            case.files.insert(PathBuf::from(arg), bytes);
        }
    }
    Some(case)
}

fn find_examples(repo: &Path, names: &[String]) -> Vec<Case> {
    if names.is_empty() {
        return Vec::new();
    }
    scan_examples(repo, |line, doc_dir| {
        parse_example(line, names, repo, doc_dir)
    })
}

/// The documented examples no recorded case runs, as the command line the docs show.
pub(crate) fn unrecorded_examples(repo: &Path, config: &Config) -> Result<Vec<String>> {
    if config.http.is_some() {
        return crate::http::unrecorded_examples(repo);
    }
    let recorded: BTreeSet<String> = load_specs(&cases_dir(repo))?
        .iter()
        .map(|s| s.case.key())
        .collect();
    let mut seen = BTreeSet::new();
    Ok(
        find_examples(repo, &app_names(repo, &config.run, Some(&config.name)))
            .into_iter()
            .filter(|case| !recorded.contains(&case.key()) && seen.insert(case.key()))
            .map(|case| {
                std::iter::once(config.name.as_str())
                    .chain(case.args.iter().map(String::as_str))
                    .map(shell_quote)
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect(),
    )
}

/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
/// with the folder of the file it came from.
pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
    let skip = ["node_modules", "target", "vendor", ".git"];
    let walker = crate::walk::filtered(repo, move |e| {
        let name = e.file_name().to_string_lossy();
        !skip.contains(&name.as_ref())
    })
    .max_depth(Some(4))
    .sort_by_file_name(|a, b| a.cmp(b))
    .build();
    let rust_dir = repo.join("rust");
    let mut out = Vec::new();
    for entry in walker.flatten() {
        let path = entry.path();
        if path.starts_with(&rust_dir) || !path.is_file() {
            continue;
        }
        let ext = path
            .extension()
            .map(|e| e.to_string_lossy().to_lowercase())
            .unwrap_or_default();
        let markdown = matches!(ext.as_str(), "md" | "markdown");
        if !markdown && ext != "sh" {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        let doc_dir = path.parent().unwrap_or(repo);
        let mut fence: Option<String> = None;
        // A command wrapped with trailing backslashes, joined so far.
        let mut pending = String::new();
        for raw in text.lines() {
            let line = raw.trim();
            let candidate = if markdown {
                if line.starts_with("```") || line.starts_with("~~~") {
                    pending.clear();
                    fence = match fence {
                        Some(_) => None,
                        None => Some(
                            line.trim_start_matches(['`', '~'])
                                .split_whitespace()
                                .next()
                                .unwrap_or_default()
                                .to_lowercase(),
                        ),
                    };
                    continue;
                }
                let Some(lang) = &fence else { continue };
                // Continuation lines carry no `$ ` prompt, and keep their indentation: it is what
                // separates them from the previous word, as the shell adds no space when joining.
                if !pending.is_empty() {
                    raw
                } else {
                    let start = raw.trim_start();
                    match start.strip_prefix("$ ") {
                        Some(rest) => rest,
                        None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => start,
                        None => continue,
                    }
                }
            } else if !pending.is_empty() {
                raw
            } else {
                let start = raw.trim_start();
                start.strip_prefix("$ ").unwrap_or(start)
            };
            // The line's end is untrimmed, so `\ ` (an escaped space) does not continue.
            if !ends_in_comment(candidate)
                && let Some(head) = continued(candidate)
            {
                pending.push_str(head);
                continue;
            }
            pending.push_str(candidate);
            let command = std::mem::take(&mut pending);
            if let Some(case) = parse(&command, doc_dir) {
                out.push(case);
            }
        }
    }
    out
}

/// Whether a shell line ends inside a comment: an unquoted `#` that starts a word. A `\` at the
/// end of a comment is part of the comment, not a continuation.
fn ends_in_comment(line: &str) -> bool {
    let (mut single, mut double, mut escaped, mut word_start) = (false, false, false, true);
    for c in line.chars() {
        if escaped {
            escaped = false;
            word_start = false;
            continue;
        }
        match c {
            '\\' if !single => escaped = true,
            '\'' if !double => single = !single,
            '"' if !single => double = !double,
            '#' if word_start && !single && !double => return true,
            _ => {}
        }
        word_start = c.is_whitespace() && !single && !double;
    }
    false
}

/// The line without its trailing `\` when the shell would join it with the next line. An even
/// number of trailing backslashes ends in a literal one (`C:\\`), not a continuation.
fn continued(line: &str) -> Option<&str> {
    let head = line.strip_suffix('\\')?;
    let escaped = (head.len() - head.trim_end_matches('\\').len()) % 2 == 1;
    (!escaped).then_some(head)
}

fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let mut out = Vec::new();
    for (n, line) in crate::lang::without_bom(&text).lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let input: Input = serde_json::from_str(line)
            .with_context(|| format!("{}:{}: expected {{\"name\": ..., \"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}, \"remove\": [paths]}}; \"remove\" deletes paths from the --fresh copy before the case runs", path.display(), n + 1))?;
        let mut case = Case::new(input.args);
        case.stdin = input.stdin.map(String::into_bytes);
        case.env = input.env;
        for (file, content) in input.files {
            ensure!(
                safe_relative(&file),
                "{}:{}: file `{file}` must be a relative path inside the sandbox",
                path.display(),
                n + 1
            );
            case.files.insert(PathBuf::from(file), content.into_bytes());
        }
        for file in input.remove {
            ensure!(
                safe_relative(&file),
                "{}:{}: removed `{file}` must be a relative path inside the sandbox",
                path.display(),
                n + 1
            );
            case.remove.push(PathBuf::from(file));
        }
        out.push((input.name, case));
    }
    Ok(out)
}

pub(crate) fn is_word(arg: &str) -> bool {
    let mut chars = arg.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

pub(crate) fn interleave<T>(groups: Vec<Vec<T>>) -> Vec<T> {
    let mut queues: Vec<std::collections::VecDeque<T>> =
        groups.into_iter().map(Into::into).collect();
    let mut out = Vec::new();
    loop {
        let mut progressed = false;
        for q in &mut queues {
            if let Some(item) = q.pop_front() {
                out.push(item);
                progressed = true;
            }
        }
        if !progressed {
            break;
        }
    }
    out
}

/// Spreads traps round-robin across bases, deduplicating against `existing` and earlier traps
/// before capping at `limit`. `reserved` traps (such as the unknown-route probe) are always kept
/// first. Returns `(kept, dropped)` where `dropped` counts unique traps excluded by `limit`.
pub(crate) fn spread_traps<T, K, F>(
    per_base: Vec<Vec<T>>,
    reserved: Vec<T>,
    existing: &BTreeSet<K>,
    key: F,
    limit: usize,
) -> (Vec<T>, usize)
where
    K: Ord + Clone,
    F: Fn(&T) -> K,
{
    let mut seen = existing.clone();
    let mut out = Vec::new();
    let mut dropped = 0usize;
    for item in reserved {
        if seen.insert(key(&item)) {
            if out.len() < limit {
                out.push(item);
            } else {
                dropped += 1;
            }
        }
    }
    let mut queues: Vec<std::collections::VecDeque<T>> =
        per_base.into_iter().map(Into::into).collect();
    loop {
        let mut any = false;
        for q in &mut queues {
            while let Some(item) = q.pop_front() {
                if seen.insert(key(&item)) {
                    if out.len() < limit {
                        out.push(item);
                    } else {
                        dropped += 1;
                    }
                    any = true;
                    break;
                }
            }
        }
        if !any {
            break;
        }
    }
    (out, dropped)
}

fn trap_cases(bases: &[Case]) -> (Vec<Case>, usize) {
    let mut per_base = Vec::with_capacity(bases.len());
    for base in bases {
        let mut slots: Vec<Vec<Case>> = Vec::new();
        for (i, arg) in base.args.iter().enumerate() {
            if i == 0 && is_word(arg) {
                continue;
            }
            let number = arg.parse::<f64>().is_ok();
            if arg.starts_with('-') && !number {
                continue;
            }
            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
                INT_TRAPS.to_vec()
            } else if number && arg.contains(['.', 'e', 'E']) {
                FLOAT_TRAPS.to_vec()
            } else if base.files.contains_key(Path::new(arg)) {
                vec!["missing-input.txt"]
            } else {
                STRING_TRAPS.to_vec()
            };
            let slot: Vec<Case> = values
                .into_iter()
                .filter(|v| v != arg)
                .map(|v| {
                    let mut case = base.clone();
                    case.args[i] = v.to_string();
                    case
                })
                .collect();
            if !slot.is_empty() {
                slots.push(slot);
            }
        }
        if let Some(stdin) = &base.stdin {
            let json = std::str::from_utf8(stdin)
                .ok()
                .and_then(|t| serde_json::from_str::<Value>(t).ok())
                .is_some_and(|v| v.is_object() || v.is_array());
            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
            slots.push(
                values
                    .iter()
                    .map(|v| {
                        let mut case = base.clone();
                        case.stdin = Some(v.as_bytes().to_vec());
                        case
                    })
                    .collect(),
            );
        }
        per_base.push(interleave(slots));
    }
    let existing: BTreeSet<_> = bases.iter().map(Case::key).collect();
    spread_traps(per_base, Vec::new(), &existing, Case::key, MAX_TRAPS)
}

pub(crate) fn slug(text: &str) -> String {
    slug_max(text, 24)
}

/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
/// only past the 24th character stay apart.
pub(crate) fn given_slug(text: &str) -> String {
    slug_max(text, 96)
}

fn slug_max(text: &str, max: usize) -> String {
    let mut out = String::new();
    for c in text.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
        } else if !out.ends_with('-') && !out.is_empty() {
            out.push('-');
        }
    }
    out.truncate(max);
    out.trim_end_matches('-').to_string()
}

pub struct RecordOptions<'a> {
    pub repo: &'a Path,
    /// The command that runs the original; taken from the saved config when empty.
    pub run: &'a [String],
    pub inputs: Option<&'a Path>,
    /// Built-in normalizer names, or `name=regex` for your own.
    pub normalize: &'a [String],
    pub name: Option<&'a str>,
    pub traps: bool,
    pub timeout_secs: Option<u64>,
    /// `Some(true)` records as a server, `Some(false)` drops any saved server setting and records
    /// as a CLI, and `None` keeps the saved mode (or enables server mode if server-only options
    /// such as `port`, non-empty `server_args`, or `pace_ms` are given).
    pub http: Option<bool>,
    /// The port a server always listens on (implies `http`); unset keeps the saved port, `Some(0)`
    /// removes it so the server gets a free port through `PORT` and `{port}`.
    pub port: Option<u16>,
    /// Servers: arguments every start gets after its command, the original's and every build's
    /// (non-empty implies `http`); `None` keeps the saved list, `Some(&[])` clears it.
    pub server_args: Option<&'a [String]>,
    /// Repository files or folders copied into a fresh working directory before every case (CLIs)
    /// or start (servers); `None` keeps the saved list, `Some(&[])` clears it.
    pub fresh: Option<&'a [String]>,
    /// Servers: milliseconds to wait after each response, for work the server does after
    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
    pub pace_ms: Option<u64>,
    /// Numbers in the output match within this tolerance; kept from the last recording when
    /// `None`, removed with 0.
    pub float_tolerance: Option<f64>,
    /// Written files of raw floats, `path=f32le` or `path=f64le`; kept from the last recording
    /// when empty.
    pub float_files: &'a [String],
    pub effects: Option<crate::effects::EffectsConfig>,
    /// Servers: seconds to wait for the port before giving up; kept from the last recording when
    /// `None`; 0 restores the default, a minute.
    pub ready_secs: Option<u64>,
    /// Servers: a request that says the app is ready once it answers, e.g. `GET /health`; kept from
    /// the last recording when `None`.
    pub ready_request: Option<&'a str>,
    /// Run the original with no network, the repository read-only and a CPU limit and, on Linux only, a memory limit
    /// ([`crate::process::Sandbox`]); loopback stays open for a server and effect sinks where
    /// the sandbox allows it (macOS).
    pub sandbox: bool,
}

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

#[derive(Debug, Serialize)]
pub struct RecordOutcome {
    /// How the trycmd test in a lifted app was refreshed, or what to change by hand.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trycmd_test: Option<String>,
    pub dir: PathBuf,
    pub run: Vec<String>,
    pub cases: usize,
    pub examples: usize,
    pub inputs: usize,
    /// `--inputs` lines not recorded because an earlier case had the same arguments, stdin,
    /// environment and files: each as `name (the case it repeats)`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub duplicate_inputs: Vec<String>,
    /// Runs with no arguments, recorded because no examples or inputs were found (the
    /// `no-args` case).
    #[serde(default, skip_serializing_if = "is_zero")]
    pub no_args: usize,
    pub traps: usize,
    /// Unique traps dropped after hitting `MAX_TRAPS`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub traps_dropped: usize,
    /// Cases where the two runs of the original differed.
    pub noisy: Vec<String>,
    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
    /// in any order, `lines` became a `...` that matches anything.
    pub noise: Vec<Noise>,
    /// Cases whose exit code or written files differed between the two runs.
    pub unstable: Vec<String>,
    /// Every case (two or more) failed with the same exit code and the same standard error: the
    /// original most likely never ran (a missing module, a wrong path in the command). The last
    /// line of that error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub same_failure: Option<String>,
    /// Cases not written: the original timed out or did not answer.
    pub timed_out: Vec<String>,
    /// The cases this recording wrote.
    pub recorded: Vec<String>,
    /// `curl` lines in the README or scripts the recorder could not read (an option it does not
    /// know, a shell operator): they are not cases, so nothing checks what they show.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped_examples: Vec<String>,
    /// Cases the last recording in this folder wrote and this one did not (a timeout included):
    /// removed, apart from files a case that stays reads (`fs.base`).
    pub stale: Vec<String>,
    /// Cases in the folder that no recording wrote (by hand, or before the list was kept):
    /// left in place.
    pub kept: Vec<String>,
}

/// What each case's files are called after its name.
const CASE_FILES: [&str; 9] = [
    "toml",
    "stdin",
    "stdout",
    "stderr",
    REMOVED_EXT,
    crate::effects::EXT,
    "body",
    "in",
    "out",
];

/// Removes the cases the last recording in this folder wrote (`previous`) that this one did not
/// write, and names the cases in the folder that did not come from a recording, which it keeps.
/// Only `previous` marks a case as a recording's: a case written by hand stays even when an input
/// of its name timed out now. Files a case that stays reads through `fs.base` (that folder, or one
/// inside it) stay too.
pub(crate) fn drop_stale(outcome: &mut RecordOutcome, previous: &[String]) -> Result<()> {
    let written: BTreeSet<&str> = outcome.recorded.iter().map(String::as_str).collect();
    let ours: BTreeSet<&str> = previous
        .iter()
        .map(String::as_str)
        .filter(|name| !written.contains(name))
        .collect();
    let read = bases_read(&outcome.dir, &ours);
    let mut stale = Vec::new();
    for name in &ours {
        if name.is_empty() || *name == "." || *name == ".." || name.contains(['/', '\\', '\0']) {
            continue;
        }
        if outcome.dir.join(format!("{name}.toml")).is_file() {
            stale.push((*name).to_string());
        }
        for ext in CASE_FILES {
            let path = outcome.dir.join(format!("{name}.{ext}"));
            // A folder a case that stays reads, holds one it reads, or is on the way to it as
            // written: `two.in/sub`, `../app-cases/two.in/sub` (resolved) and `two.in/../shared`
            // (on Unix only found while `two.in` exists) all keep `two.in`.
            let resolved = path.canonicalize().ok();
            if any_base_reads(&read, &path, resolved.as_deref()) {
                continue;
            }
            if path.is_dir() {
                std::fs::remove_dir_all(&path)
                    .with_context(|| format!("removing {}", path.display()))?;
            } else if path.is_file() {
                std::fs::remove_file(&path)
                    .with_context(|| format!("removing {}", path.display()))?;
            }
        }
    }
    let mut kept: Vec<String> = std::fs::read_dir(&outcome.dir)?
        .flatten()
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            name.strip_suffix(".toml").map(str::to_string)
        })
        .filter(|name| !written.contains(name.as_str()))
        .collect();
    kept.sort();
    outcome.stale = stale;
    outcome.kept = kept;
    Ok(())
}

fn any_base_reads(read: &BTreeSet<PathBuf>, path: &Path, resolved: Option<&Path>) -> bool {
    read.iter()
        .any(|base| base.starts_with(path) || resolved.is_some_and(|r| base.starts_with(r)))
}

fn any_base_reaches(read: &BTreeSet<PathBuf>, path: &Path, resolved: Option<&Path>) -> bool {
    any_base_reads(read, path, resolved)
        || read
            .iter()
            .any(|base| path.starts_with(base) || resolved.is_some_and(|r| r.starts_with(base)))
}

/// The `fs.base` folders that the cases in `dir` other than `going` read, each as written (joined
/// to `dir`) and, when it exists, resolved.
fn bases_read(dir: &Path, going: &BTreeSet<&str>) -> BTreeSet<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return BTreeSet::new();
    };
    entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension().is_some_and(|e| e == "toml")
                && path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .is_some_and(|stem| !going.contains(stem))
        })
        .filter_map(|path| std::fs::read_to_string(path).ok())
        .filter_map(|text| text.parse::<DocumentMut>().ok())
        .filter_map(|doc| {
            doc.get("fs")
                .and_then(|f| f.get("base"))
                .and_then(Item::as_str)
                .map(|base| dir.join(base))
        })
        .flat_map(|base| {
            let resolved = base.canonicalize().ok();
            std::iter::once(base).chain(resolved)
        })
        .collect()
}

struct Recorded {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    effects: Option<Vec<u8>>,
    status: Status,
    written: BTreeMap<PathBuf, Vec<u8>>,
    removed: Vec<PathBuf>,
    binary: bool,
    noise: Vec<(String, NoiseKind)>,
    /// The outputs in which a normalizer replaced a match that holds a line break.
    across: Vec<String>,
    unstable: bool,
}

/// How two runs of the original disagreed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NoiseKind {
    /// Values within lines changed (times, ids): those parts are wildcards now.
    Values,
    /// The same lines came out in another order (hash maps, concurrency): replay compares them
    /// in any order, and a port must produce exactly those lines.
    Order,
    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
    /// anything. Look at these first.
    Lines,
}

#[derive(Debug, Clone, Serialize)]
pub struct Noise {
    pub case: String,
    pub field: String,
    pub kind: NoiseKind,
}

fn same_lines_any_order(a: &str, b: &str) -> bool {
    let (mut la, mut lb) = (lines(a), lines(b));
    la.sort_unstable();
    lb.sort_unstable();
    la == lb
}

pub(crate) fn settle_text(
    norm: &Normalizers,
    a: &[u8],
    b: &[u8],
) -> (Vec<u8>, Option<NoiseKind>, bool) {
    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
        (Ok(a), Ok(b)) => {
            let (a, b) = (norm.apply(a), norm.apply(b));
            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
                (a.into_bytes(), None, false)
            } else if same_lines_any_order(&a, &b) {
                (a.into_bytes(), Some(NoiseKind::Order), false)
            } else {
                let merged = merge_noise(&a, &b);
                let kind = if merged.split('\n').any(|l| l == "...") {
                    NoiseKind::Lines
                } else {
                    NoiseKind::Values
                };
                (merged.into_bytes(), Some(kind), false)
            }
        }
        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
    }
}

/// The last line of the standard error every recorded case printed, when there are two or more
/// and all failed the same way: same non-zero exit code, same error output.
fn same_failure<'a>(mut recorded: impl Iterator<Item = &'a Recorded>) -> Option<String> {
    let first = recorded.next()?;
    let mut count = 1;
    for rec in recorded {
        if rec.status != first.status || rec.stderr != first.stderr {
            return None;
        }
        count += 1;
    }
    let failed = !matches!(first.status, Status::Code(0));
    let last = String::from_utf8_lossy(&first.stderr)
        .lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .map(|l| l.trim().to_string())?;
    (count >= 2 && failed).then_some(last)
}

fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
        .iter()
        .any(|bytes| std::str::from_utf8(bytes).is_err());
    let settle_stream = |a: &[u8], b: &[u8]| {
        if binary {
            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
        } else {
            let (bytes, noise, _) = settle_text(norm, a, b);
            (bytes, noise)
        }
    };
    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
    let (effects, fx_noise) = match (&one.effects, &two.effects) {
        (Some(a), Some(b)) => {
            let (bytes, noise, _) = settle_text(norm, a, b);
            (Some(bytes), noise)
        }
        _ => (None, None),
    };
    let (w1, w2) = (one.written(case), two.written(case));
    let pairs = norm.pair_files(w1.keys(), w2.keys());
    let mut unstable = one.status != two.status
        || one.removed != two.removed
        || w1.len() != w2.len()
        || pairs.len() != w1.len()
        || (binary && (out_noise.is_some() || err_noise.is_some()));
    let mut noise: Vec<(String, NoiseKind)> = [
        ("stdout", out_noise),
        ("stderr", err_noise),
        (crate::effects::EXT, fx_noise),
    ]
    .into_iter()
    .filter_map(|(f, k)| Some((f.to_string(), k?)))
    .collect();
    let mut across: Vec<String> = [
        ("stdout", &one.stdout, &two.stdout),
        ("stderr", &one.stderr, &two.stderr),
    ]
    .into_iter()
    .filter(|(_, a, b)| !binary && norm.crosses_lines(a, b))
    .map(|(field, _, _)| field.to_string())
    .collect();
    let mut written = BTreeMap::new();
    for (path, a) in &w1 {
        let b = pairs.get(path).and_then(|other| w2.get(other)).unwrap_or(a);
        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
        if !file_bin && norm.crosses_lines(a, b) {
            across.push(format!("file {}", path.display()));
        }
        unstable |= file_bin && file_noise.is_some();
        if let Some(kind) = file_noise {
            noise.push((format!("file {}", path.display()), kind));
        }
        written.insert(path.clone(), bytes);
    }
    Recorded {
        stdout,
        stderr,
        effects,
        status: one.status.clone(),
        written,
        removed: one.removed.clone(),
        binary,
        noise,
        across,
        unstable,
    }
}

fn dotted() -> Table {
    let mut t = Table::new();
    t.set_dotted(true);
    t
}

/// The `.removed` file: one path per line, with `/` between components on every OS, so a
/// recording made on Windows replays on Linux and macOS, where `\` is part of a file name.
fn removed_list(paths: &[PathBuf]) -> String {
    paths
        .iter()
        .map(|p| {
            let parts: Vec<_> = p
                .components()
                .map(|c| c.as_os_str().to_string_lossy())
                .collect();
            format!("{}\n", parts.join("/"))
        })
        .collect()
}

fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
    for ext in [
        "stdin",
        "stdout",
        "stderr",
        REMOVED_EXT,
        crate::effects::EXT,
    ] {
        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
    }
    for ext in ["in", "out"] {
        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
    }
    let mut doc = DocumentMut::new();
    let mut bin_t = dotted();
    bin_t["name"] = value(bin);
    doc["bin"] = Item::Table(bin_t);
    let mut args = toml_edit::Array::new();
    for a in &case.args {
        args.push(a.as_str());
    }
    doc["args"] = value(args);
    if !case.env.is_empty() {
        let mut add = dotted();
        for (k, v) in &case.env {
            add[k.as_str()] = value(v.as_str());
        }
        let mut env = dotted();
        env.insert("add", Item::Table(add));
        doc["env"] = Item::Table(env);
    }
    match rec.status {
        Status::Code(code) => {
            let mut status = dotted();
            status["code"] = value(i64::from(code));
            doc["status"] = Item::Table(status);
        }
        _ => doc["status"] = value("interrupted"),
    }
    let mut fs = dotted();
    fs["sandbox"] = value(true);
    if !case.files.is_empty() {
        fs["base"] = value(format!("{name}.in"));
    }
    if !case.remove.is_empty() {
        let mut remove = toml_edit::Array::new();
        for path in &case.remove {
            remove.push(path.to_string_lossy().as_ref());
        }
        fs["remove"] = value(remove);
    }
    doc["fs"] = Item::Table(fs);
    if rec.binary {
        doc["binary"] = value(true);
    }
    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
    if let Some(stdin) = &case.stdin {
        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
    }
    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
    if !rec.removed.is_empty() {
        std::fs::write(
            dir.join(format!("{name}.{REMOVED_EXT}")),
            removed_list(&rec.removed),
        )?;
    }
    if let Some(effects) = &rec.effects {
        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
    }
    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
        for (path, bytes) in files {
            let target = dir.join(format!("{name}.{sub}")).join(path);
            if let Some(parent) = target.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&target, bytes)?;
        }
    }
    Ok(())
}

pub(crate) fn reserve_case_name(
    taken: &mut BTreeSet<String>,
    base: String,
    mut suffix: usize,
) -> String {
    let mut name = base.clone();
    while !taken.insert(name.clone()) {
        name = format!("{base}-{suffix}");
        suffix += 1;
    }
    name
}

/// A `--fresh` snapshot taken beside `dest`, which it replaces only once committed.
struct PendingSnapshot {
    dir: Option<PathBuf>,
    dest: PathBuf,
}

impl PendingSnapshot {
    fn take(repo: &Path, fresh: &[String], dest: PathBuf) -> Result<Self> {
        let mut name = dest.file_name().unwrap_or_default().to_os_string();
        name.push(".pending");
        let pending = dest.with_file_name(name);
        let mut snapshot = PendingSnapshot {
            dir: Some(pending.clone()),
            dest,
        };
        if crate::http::snapshot_to(repo, fresh, &pending)?.is_none() {
            snapshot.dir = None;
        }
        Ok(snapshot)
    }

    fn path(&self) -> Option<&Path> {
        self.dir.as_deref()
    }

    fn commit(mut self) -> Result<Option<PathBuf>> {
        let Some(dir) = self.dir.take() else {
            return Ok(None);
        };
        let mut name = self.dest.file_name().unwrap_or_default().to_os_string();
        name.push(".old");
        let old = self.dest.with_file_name(name);
        let _ = std::fs::remove_dir_all(&old);
        swap_in(&dir, &self.dest, &old)
    }
}

/// Puts `staged` where `dest` is, keeping whatever was there under `old` until the swap succeeds.
/// A failed swap puts the previous folder back; if that fails too, both paths are named, so `dest`
/// is never silently left missing (issue #1118).
fn swap_in(staged: &Path, dest: &Path, old: &Path) -> Result<Option<PathBuf>> {
    let moved = std::fs::rename(dest, old).is_ok();
    let renamed = std::fs::rename(staged, dest);
    if renamed.is_ok() {
        // The previous folder stays until the caller says the rest of the publish worked, so a
        // failure after this point can still put it back (issue #1118).
        return Ok(moved.then(|| old.to_path_buf()));
    }
    let renamed = renamed.with_context(|| format!("replacing {}", dest.display()));
    if moved && let Err(restore) = std::fs::rename(old, dest) {
        // `commit` has already taken the pending folder, so nothing else cleans it up.
        let _ = std::fs::remove_dir_all(staged);
        // `{:#}` keeps the installation error's own cause, not just its context (review of #1290).
        let failed = renamed
            .as_ref()
            .err()
            .map(|e| format!("{e:#}"))
            .unwrap_or_default();
        anyhow::bail!(
            "{failed}; the previous folder could not be put back from {} either ({restore}), so \
             the folder holds neither",
            old.display()
        );
    }
    let _ = std::fs::remove_dir_all(staged);
    renamed.map(|()| None)
}

impl Drop for PendingSnapshot {
    fn drop(&mut self) {
        if let Some(dir) = self.dir.take() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

/// Per-repository lock held across `app::record`, so two concurrent records of one repository take
/// turns instead of racing on `cases_dir` or `.pending` snapshots.
struct AppRecordLock(Option<(std::fs::File, PathBuf)>);

thread_local! {
    static APP_RECORD_HELD: std::cell::RefCell<Vec<PathBuf>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

impl AppRecordLock {
    fn take(repo: &Path) -> Result<Self> {
        // Keep one lock even when two recorders have different temporary directories.
        let lock_dir = repo.join("rust/.app-record");
        std::fs::create_dir_all(&lock_dir)
            .with_context(|| format!("creating {}", lock_dir.display()))?;
        ensure!(
            std::fs::symlink_metadata(&lock_dir)?.is_dir(),
            "{} must be a directory",
            lock_dir.display()
        );
        let path = lock_dir.join("app-record.lock");
        if APP_RECORD_HELD.with(|held| held.borrow().iter().any(|p| p == &path)) {
            return Ok(Self(None));
        }
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .with_context(|| format!("opening {}", path.display()))?;
        loop {
            match file.try_lock() {
                Ok(()) => break,
                Err(std::fs::TryLockError::WouldBlock) if crate::mcp::cancelled() => {
                    bail!("the wait for the app recording lock was stopped: the call was cancelled")
                }
                Err(std::fs::TryLockError::WouldBlock) => {
                    std::thread::sleep(Duration::from_millis(50))
                }
                Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
            }
        }
        Self::ignore_files(&lock_dir.join(".gitignore"))?;
        APP_RECORD_HELD.with(|held| held.borrow_mut().push(path.clone()));
        Ok(Self(Some((file, path))))
    }

    // The recording lock serializes repairs if a previous write stopped halfway.
    fn ignore_files(path: &Path) -> Result<()> {
        // replace_bytes stages the repair beside .gitignore using its process ID and sequence.
        const RULES: &str =
            "/.gitignore\n/app-record.lock\n/.gitignore.rust-anything.[0-9]*.[0-9]*.tmp\n";
        match std::fs::File::create_new(path) {
            Ok(mut file) => {
                return file
                    .write_all(RULES.as_bytes())
                    .with_context(|| format!("writing {}", path.display()));
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e).with_context(|| format!("creating {}", path.display())),
        }
        ensure!(
            std::fs::symlink_metadata(path)?.is_file(),
            "{} must be a regular file",
            path.display()
        );
        let mut content = std::fs::read(path)?;
        let original_len = content.len();
        for rule in RULES.lines().map(str::as_bytes) {
            if content
                .split(|&b| b == b'\n')
                .any(|line| line.strip_suffix(b"\r").unwrap_or(line) == rule)
            {
                continue;
            }
            if !content.is_empty() && !content.ends_with(b"\n") {
                content.push(b'\n');
            }
            content.extend_from_slice(rule);
            content.push(b'\n');
        }
        if content.len() != original_len {
            crate::setup::replace_bytes(path, &content)?;
        }
        Ok(())
    }
}

impl Drop for AppRecordLock {
    fn drop(&mut self) {
        if let Some((file, path)) = self.0.take() {
            let _ = file.unlock();
            APP_RECORD_HELD.with(|held| {
                let mut held = held.borrow_mut();
                if let Some(pos) = held.iter().rposition(|p| p == &path) {
                    held.remove(pos);
                }
            });
        }
    }
}

/// Split a `--normalize name=regex` into its name and pattern, refusing one that would save a
/// broken recording; `None` for a built-in name.
fn custom_normalizer(spec: &str) -> Result<Option<(&str, &str)>> {
    let Some((name, pattern)) = spec.split_once('=') else {
        return Ok(None);
    };
    ensure!(
        !name.is_empty(),
        "--normalize `{spec}` has no name: give it as `name=regex`"
    );
    ensure!(
        !BUILTIN_NORMALIZERS.contains(&name),
        "--normalize `{spec}`: `{name}` is a built-in normalizer; pass `--normalize {name}` for it, or give your pattern another name"
    );
    let re = Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))?;
    ensure!(
        !re.is_match(""),
        "normalizer `{name}` matches the empty string, so it would match everywhere and put `[..]` between every character: give a pattern that matches at least one character (e.g. `\\d+`, not `\\d*`)"
    );
    Ok(Some((name, pattern)))
}

pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
    check_timeout(opts.timeout_secs)?;
    for n in opts.normalize {
        custom_normalizer(n)?;
    }
    let repo = crate::walk::resolve_root(opts.repo)?;
    let _record_lock = AppRecordLock::take(&repo)?;
    let existing = Config::load(&repo)?;
    let previous_skips = crate::lift::previous_cases_test_skips(&repo, existing.as_ref());
    let run = if !opts.run.is_empty() {
        opts.run.to_vec()
    } else if let Some(c) = &existing {
        c.run.clone()
    } else {
        bail!(
            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
        );
    };
    let mut normalize = existing
        .as_ref()
        .map(|c| c.normalize.clone())
        .unwrap_or_default();
    let mut normalizers = existing
        .as_ref()
        .map(|c| c.normalizers.clone())
        .unwrap_or_default();
    for n in opts.normalize {
        if let Some((name, pattern)) = custom_normalizer(n)? {
            normalizers.insert(name.to_string(), pattern.to_string());
        } else if !normalize.contains(n) {
            normalize.push(n.clone());
        }
    }
    let inferred = |run: &[String]| {
        app_names(&repo, run, None)
            .into_iter()
            .next()
            .unwrap_or_else(|| "app".to_string())
    };
    let explicit = opts.name.map(str::to_string).or_else(|| {
        existing
            .as_ref()
            .filter(|c| opts.run.is_empty() || c.run == opts.run || c.name != inferred(&c.run))
            .map(|c| c.name.clone())
    });
    let names = app_names(&repo, &run, explicit.as_deref());
    let timeout_secs = opts
        .timeout_secs
        .or(existing.as_ref().map(|c| c.timeout_secs))
        .unwrap_or_else(default_timeout);
    ensure!(
        timeout_secs >= 1,
        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
    );
    let mut config = Config {
        schema: SCHEMA.to_string(),
        name: explicit
            .or_else(|| names.first().cloned())
            .unwrap_or_else(|| "app".to_string()),
        run,
        normalize,
        normalizers,
        timeout_secs,
        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts)?,
        float_tolerance: match opts.float_tolerance {
            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
            None => existing.as_ref().and_then(|c| c.float_tolerance),
        },
        float_files: if opts.float_files.is_empty() {
            existing
                .as_ref()
                .map(|c| c.float_files.clone())
                .unwrap_or_default()
        } else {
            opts.float_files
                .iter()
                .map(|spec| {
                    let (path, format) = spec.rsplit_once('=').with_context(|| {
                        format!("--float-file `{spec}`: use PATH=f32le or PATH=f64le")
                    })?;
                    float_width(format)?;
                    Ok((path.to_string(), format.to_string()))
                })
                .collect::<Result<_>>()?
        },
        unordered: BTreeMap::new(),
        across_lines: None,
        effects: crate::effects::EffectsConfig::merge(
            existing.as_ref().and_then(|c| c.effects.clone()),
            opts.effects.clone(),
        ),
        fresh: Vec::new(),
        recorded: Vec::new(),
    };
    if let Some(http) = config.http.as_mut() {
        if let Some(fresh) = opts.fresh {
            http.fresh = fresh.to_vec();
        }
    } else if let Some(fresh) = opts.fresh {
        config.fresh = fresh.to_vec();
    } else if let Some(c) = &existing {
        config.fresh = c.fresh.clone();
    }
    let norm = Normalizers::new(&config)?;
    // Even a partial recording publishes its new name and unordered cases. Refresh the lifted
    // test at the same point for CLI and HTTP, before a timeout or snapshot error is returned.
    let save_config = |config: &Config| {
        crate::lift::save_record_config(&repo, config, existing.as_ref(), &previous_skips)
    };
    if let Some(http) = &config.http {
        let snapshot = PendingSnapshot::take(
            &repo,
            &http.fresh,
            cases_dir(&repo)
                .join(crate::http::HTTP_DIR)
                .join(crate::http::FILES_DIR),
        )?;
        let mut outcome = crate::http::record(&repo, &config, &norm, opts, snapshot.path())?;
        let dropped = update_recorded_cases(&mut config, existing.as_ref(), &mut outcome)?;
        outcome.trycmd_test = save_config(&config)?;
        // Same as the CLI path: a failure says what was already published (issue #1118).
        let staged_snapshot = snapshot.path().is_some();
        let previous_snapshot = snapshot.commit().with_context(|| {
            format!("{CONFIG_FILE} is published, but the captured-file snapshot is not")
        })?;
        // The swap hands the previous snapshot back, so this branch drops it once the recording is
        // known to be complete (review of #1385).
        let complete = check_recording_complete(dropped, outcome.trycmd_test.as_deref())
            .with_context(|| {
                if staged_snapshot {
                    "the snapshot is published, but the recording is incomplete".to_string()
                } else {
                    format!("{CONFIG_FILE} is published, but the recording is incomplete")
                }
            });
        if let Some(previous) = previous_snapshot {
            let _ = std::fs::remove_dir_all(previous);
        }
        complete?;
        if config.http.as_ref().is_some_and(|h| h.fresh.is_empty()) {
            let _ = std::fs::remove_dir_all(
                cases_dir(&repo)
                    .join(crate::http::HTTP_DIR)
                    .join(crate::http::FILES_DIR),
            );
        }
        return Ok(outcome);
    }

    let examples = find_examples(&repo, &names);
    let inputs = match opts.inputs {
        Some(path) => read_inputs(path)?,
        None => Vec::new(),
    };
    let mut planned: Vec<(String, Case)> = Vec::new();
    // Each planned case's name by its key, so a repeated input can name the case it repeats.
    let mut seen: BTreeMap<String, String> = BTreeMap::new();
    let mut taken = BTreeSet::new();
    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
        if let Some(first) = seen.get(&case.key()) {
            return Err(first.clone());
        }
        let base_name = match given {
            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
                Some(s) => format!("{prefix}-{n:03}-{s}"),
                None => format!("{prefix}-{n:03}"),
            },
        };
        let name = reserve_case_name(&mut taken, base_name, n);
        seen.insert(case.key(), name.clone());
        planned.push((name, case));
        Ok(())
    };
    let mut bases = Vec::new();
    let mut counts = [0usize; 3];
    for case in examples {
        if push("example", counts[0] + 1, None, case.clone()).is_ok() {
            counts[0] += 1;
            bases.push(case);
        }
    }
    // An input line that repeats an earlier case (same arguments, stdin, environment and files)
    // is not run again; the outcome names it and the case it repeats.
    let mut duplicate_inputs = Vec::new();
    for (given, case) in inputs {
        let label = given
            .clone()
            .filter(|name| !name.is_empty())
            .unwrap_or_else(|| match case.args.join(" ") {
                joined if joined.is_empty() => "(no arguments)".to_string(),
                joined => joined,
            });
        match push("input", counts[1] + 1, given, case.clone()) {
            Ok(()) => {
                counts[1] += 1;
                bases.push(case);
            }
            Err(first) => duplicate_inputs.push(format!("{label} ({first})")),
        }
    }
    let mut no_args_fallback = false;
    if bases.is_empty() {
        let case = Case::new(Vec::new());
        if push("example", 1, Some("no-args".to_string()), case.clone()).is_ok() {
            no_args_fallback = true;
        }
        bases.push(case);
    }
    let mut traps_dropped = 0usize;
    if opts.traps {
        let (traps, dropped) = trap_cases(&bases);
        traps_dropped = dropped;
        for case in traps {
            if push("trap", counts[2] + 1, None, case).is_ok() {
                counts[2] += 1;
            }
        }
    }

    // The fallback went into an empty `planned`, so it is its first entry; read it only now that
    // the last `push` (which borrows `planned` mutably) is done.
    let no_args_name = if no_args_fallback {
        planned.first().map(|(name, _)| name.clone())
    } else {
        None
    };
    let timeout = Duration::from_secs(config.timeout_secs);
    let effects = config.effects.as_ref();
    let snapshot = PendingSnapshot::take(&repo, &config.fresh, cases_dir(&repo).join(FRESH_DIR))?;
    let base = snapshot.path();
    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
        let one = run_case(
            &config.run,
            &repo,
            case,
            timeout,
            effects,
            base,
            opts.sandbox,
        )?;
        let two = run_case(
            &config.run,
            &repo,
            case,
            timeout,
            effects,
            base,
            opts.sandbox,
        )?;
        Ok((one, two))
    };
    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
        planned.iter().map(run_twice).collect()
    } else {
        par_map(&planned, run_twice)
    };
    let dir = cases_dir(&repo);
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    let mut outcome = RecordOutcome {
        trycmd_test: None,
        dir: dir.clone(),
        run: config.run.clone(),
        cases: 0,
        examples: counts[0],
        inputs: counts[1],
        duplicate_inputs,
        no_args: 0,
        traps: counts[2],
        traps_dropped,
        noisy: Vec::new(),
        noise: Vec::new(),
        unstable: Vec::new(),
        same_failure: None,
        timed_out: Vec::new(),
        recorded: Vec::new(),
        skipped_examples: Vec::new(),
        stale: Vec::new(),
        kept: Vec::new(),
    };
    let mut settled = Vec::new();
    let mut literal = Vec::new();
    for ((name, case), runs) in planned.iter().zip(runs) {
        let (one, two) = runs?;
        for effects in [&one.effects, &two.effects].into_iter().flatten() {
            if let Some(failure) = crate::effects::dump_failure(effects) {
                bail!(
                    "case {name}: --db-dump failed while recording ({}): fix the command, since a failed dump would be recorded as the database state to match",
                    failure
                        .trim_start_matches("(db dump failed: ")
                        .trim_end_matches(')')
                );
            }
        }
        if one.status == Status::Timeout || two.status == Status::Timeout {
            outcome.timed_out.push(name.clone());
            continue;
        }
        let rec = settle(&norm, case, &one, &two);
        literal.extend(
            literal_wildcards(case, &one, &two, &rec)
                .into_iter()
                .map(|field| format!("{name} ({field})")),
        );
        settled.push((name, case, rec));
    }
    ensure!(
        literal.is_empty(),
        "the original prints `[..]` or a `...` line itself in {}, and its two runs also differ there: the recording would read that text as a wildcard. Make the runs agree (`--normalize name=regex` for the part that changes) and record again",
        literal.join(", ")
    );
    let leaked: Vec<String> = settled
        .iter()
        .flat_map(|(name, case, rec)| {
            leaked_secrets(case, rec)
                .into_iter()
                .map(move |var| format!("{name} (${var})"))
        })
        .collect();
    ensure!(
        leaked.is_empty(),
        "the recording holds the value of an environment variable whose name says it is a secret, in {}: it would be committed with the cases. Record with `env -u NAME` for each variable named, or change the inputs. Nothing was written",
        leaked.join(", ")
    );
    outcome.same_failure = same_failure(settled.iter().map(|(_, _, rec)| rec));
    let mut meta = CaseMeta::load(&dir).unwrap_or_default().unwrap_or_default();
    meta.original = original_runtime(&repo, &config.run);
    let mut across_lines: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (name, case, rec) in settled {
        write_case(&dir, &config.name, name, case, &rec)?;
        if !rec.across.is_empty() {
            across_lines.insert(name.clone(), rec.across.clone());
        }
        meta.cases.insert(
            name.clone(),
            CaseEntry {
                digest: case_digest(&dir, name),
                wild: rec
                    .noise
                    .iter()
                    .filter(|(_, kind)| *kind != NoiseKind::Order)
                    .map(|(field, _)| field.clone())
                    .collect(),
            },
        );
        if no_args_name.as_deref() == Some(name.as_str()) {
            outcome.no_args += 1;
        }
        outcome.cases += 1;
        outcome.recorded.push(name.clone());
        if !rec.noise.is_empty() {
            outcome.noisy.push(name.clone());
        }
        outcome
            .noise
            .extend(rec.noise.iter().map(|(field, kind)| Noise {
                case: name.clone(),
                field: field.clone(),
                kind: *kind,
            }));
        if rec.unstable {
            outcome.unstable.push(name.clone());
        }
    }
    let dropped = update_recorded_cases(&mut config, existing.as_ref(), &mut outcome)?;
    keep_across_lines(&mut config, existing.as_ref(), &outcome, across_lines);
    for name in &outcome.stale {
        meta.cases.remove(name);
    }
    meta.cases
        .retain(|name, _| dir.join(format!("{name}.toml")).is_file());
    // The three publishes are still three steps, but a failure in one now says which ones already
    // happened, instead of leaving a recording that looks complete (issue #1118).
    outcome.trycmd_test = save_config(&config)?;
    // The name on disk, not "config.json": `app record` writes `rust-anything.json` (review of #1290).
    let staged_snapshot = snapshot.path().is_some();
    let previous_snapshot = snapshot.commit().with_context(|| {
        format!("{CONFIG_FILE} is published, but the fresh-file snapshot is not")
    })?;
    meta.save(&dir).with_context(|| {
        // With no fresh files there is no snapshot to publish, so the message must not claim one
        // (review of #1290).
        if staged_snapshot {
            "the fresh-file snapshot is published, but the CLI metadata is not".to_string()
        } else {
            format!("{CONFIG_FILE} is published, but the CLI metadata is not")
        }
    })?;
    // The swap handed the previous snapshot back instead of removing it, so the publish drops it
    // once every step has succeeded.
    if let Some(previous) = previous_snapshot {
        let _ = std::fs::remove_dir_all(previous);
    }
    check_recording_complete(dropped, outcome.trycmd_test.as_deref())?;
    if config.fresh.is_empty() {
        let fresh_dir = dir.join(FRESH_DIR);
        let retained_reads = bases_read(&dir, &BTreeSet::new());
        let resolved = fresh_dir.canonicalize().ok();
        if !any_base_reaches(&retained_reads, &fresh_dir, resolved.as_deref()) {
            let _ = std::fs::remove_dir_all(&fresh_dir);
        }
    }
    Ok(outcome)
}

/// Fields of a case where the original printed wildcard syntax itself and its two runs also
/// differ, so the recording could not tell the original's text from its own wildcards.
fn literal_wildcards(case: &Case, one: &Run, two: &Run, rec: &Recorded) -> Vec<String> {
    let text = |bytes: &[u8]| has_wildcard_text(&String::from_utf8_lossy(bytes));
    let (w1, w2) = (one.written(case), two.written(case));
    rec.noise
        .iter()
        .filter(|(_, kind)| *kind != NoiseKind::Order)
        .filter(|(field, _)| match field.as_str() {
            "stdout" => text(&one.stdout) || text(&two.stdout),
            "stderr" => text(&one.stderr) || text(&two.stderr),
            f if f == crate::effects::EXT => [&one.effects, &two.effects]
                .iter()
                .any(|e| e.as_deref().is_some_and(text)),
            f => f.strip_prefix("file ").is_some_and(|path| {
                [&w1, &w2]
                    .iter()
                    .any(|files| files.get(Path::new(path)).is_some_and(|b| text(b)))
            }),
        })
        .map(|(field, _)| field.clone())
        .collect()
}

/// Parts of an environment variable's name that say its value is a secret.
const SECRET_NAME_PARTS: [&str; 8] = [
    "SECRET",
    "TOKEN",
    "PASSWORD",
    "PASSWD",
    "PASSPHRASE",
    "CREDENTIAL",
    "API_KEY",
    "PRIVATE_KEY",
];

/// The secret-looking environment variables (this process's, and the case's own) whose value
/// is in what would be written for the case. Names only, never values.
fn leaked_secrets(case: &Case, rec: &Recorded) -> Vec<String> {
    let mut texts: Vec<Vec<u8>> = vec![rec.stdout.clone(), rec.stderr.clone()];
    texts.extend(rec.effects.clone());
    texts.extend(rec.written.values().cloned());
    texts.extend(case.stdin.clone());
    texts.push(case.args.join("\n").into_bytes());
    leaked_values(&texts, case.env.clone())
}

/// The secret-looking environment variables (this process's, and `extra`) whose value is in one
/// of `texts`. Names only, never values.
pub(crate) fn leaked_values(
    texts: &[Vec<u8>],
    extra: impl IntoIterator<Item = (String, String)>,
) -> Vec<String> {
    let texts: Vec<String> = texts
        .iter()
        .map(|t| String::from_utf8_lossy(t).into_owned())
        .collect();
    let mut found: BTreeSet<String> = BTreeSet::new();
    let own = std::env::vars().chain(extra);
    for (name, value) in own {
        let upper = name.to_uppercase();
        if value.chars().count() >= 8
            && SECRET_NAME_PARTS.iter().any(|part| upper.contains(part))
            && texts.iter().any(|t| t.contains(&value))
        {
            found.insert(name);
        }
    }
    found.into_iter().collect()
}

/// What the original runs on and as: the interpreter's version, and the npm package a
/// `node node_modules/<package>/...` command runs, so a later `package` can tell the original it
/// pins from the one that was recorded.
fn original_runtime(repo: &Path, run: &[String]) -> BTreeMap<String, String> {
    let mut found = BTreeMap::new();
    if let Some(program) = run.first()
        && !program.contains('/')
        && !program.contains('\\')
    {
        let flag = if stem(program) == "java" {
            "-version"
        } else {
            "--version"
        };
        let known = [
            "node", "nodejs", "python", "python3", "ruby", "php", "deno", "bun", "java",
        ];
        if known.contains(&stem(program).as_str()) {
            let mut cmd = Command::new(program);
            cmd.arg(flag).current_dir(repo);
            if let Ok(out) = crate::process::output(&mut cmd, crate::process::QUICK)
                && out.status.success()
            {
                let text = [out.stdout, out.stderr].concat();
                if let Some(line) = String::from_utf8_lossy(&text)
                    .lines()
                    .map(str::trim)
                    .find(|l| !l.is_empty() && !l.starts_with("Picked up"))
                {
                    found.insert("runtime".to_string(), format!("{program} {line}"));
                }
            }
        }
    }
    if let Some(entry) = run.iter().find_map(|w| w.strip_prefix("node_modules/")) {
        let parts: Vec<&str> = entry.split('/').collect();
        let take = if entry.starts_with('@') { 2 } else { 1 };
        if parts.len() > take {
            let name = parts[..take].join("/");
            if let Ok(text) =
                std::fs::read_to_string(repo.join("node_modules").join(&name).join("package.json"))
                && let Ok(pkg) = serde_json::from_str::<Value>(&text)
                && let Some(version) = pkg["version"].as_str()
            {
                found.insert("package".to_string(), format!("{name}@{version}"));
            }
        }
    }
    found
}

/// Set to accept a recording that lost cases to timeouts or errors (the cases that did answer are
/// kept either way).
const ALLOW_DROPPED_ENV: &str = "RUST_ANYTHING_ALLOW_DROPPED";

/// Why a recording cannot stand: cases that did not answer, or none that did. `had_recording`:
/// the folder held cases from an earlier record, which stay; on a first recording there are none
/// to mention.
pub(crate) fn recording_dropped(outcome: &RecordOutcome, had_recording: bool) -> Option<String> {
    if std::env::var_os(ALLOW_DROPPED_ENV).is_some_and(|v| !v.is_empty() && v != "0") {
        return None;
    }
    if outcome.cases == 0 {
        return Some(format!(
            "recorded 0 cases ({} did not answer: {}){}. Fix the app or the inputs and record again",
            outcome.timed_out.len(),
            outcome.timed_out.join(", "),
            if had_recording {
                "; the cases recorded before were kept"
            } else {
                ""
            }
        ));
    }
    if outcome.timed_out.is_empty() {
        return None;
    }
    Some(format!(
        "{} of {} cases did not answer (timed out or no response) and were not recorded: {}. The {} that did {} written{}. Fix the app or the inputs and record again, or set {ALLOW_DROPPED_ENV}=1 to accept the smaller recording",
        outcome.timed_out.len(),
        outcome.timed_out.len() + outcome.cases,
        outcome.timed_out.join(", "),
        outcome.cases,
        if outcome.cases == 1 { "is" } else { "are" },
        if had_recording {
            ", and the cases recorded before were kept"
        } else {
            ""
        }
    ))
}

fn check_recording_complete(dropped: Option<String>, note: Option<&str>) -> Result<()> {
    match (dropped, note) {
        (Some(message), Some(note)) => bail!("{message}\n{note}"),
        (Some(message), None) => bail!("{message}"),
        (None, _) => Ok(()),
    }
}

/// When a partial recording retains an earlier case file, keep the comparison rules that
/// belong to that file. Re-recorded cases take their rules only from this run.
fn update_recorded_cases(
    config: &mut Config,
    previous: Option<&Config>,
    outcome: &mut RecordOutcome,
) -> Result<Option<String>> {
    let previous = previous.filter(|old| old.http.is_some() == config.http.is_some());
    let dropped = recording_dropped(
        outcome,
        previous.is_some_and(|old| !old.recorded.is_empty()),
    );
    let stale_from = previous.filter(|_| dropped.is_none());
    drop_stale(
        outcome,
        stale_from.map_or(&[], |old| old.recorded.as_slice()),
    )?;
    config.recorded.clone_from(&outcome.recorded);
    config.unordered = unordered_of(&outcome.noise);
    if dropped.is_some()
        && let Some(old) = previous
    {
        let mut kept: BTreeSet<_> = outcome.kept.iter().collect();
        for name in &old.recorded {
            if kept.remove(name) && outcome.dir.join(format!("{name}.toml")).is_file() {
                config.recorded.push(name.clone());
                if let Some(fields) = old.unordered.get(name) {
                    config.unordered.insert(name.clone(), fields.clone());
                }
            }
        }
    }
    Ok(dropped)
}

/// Save which recorded cases a line-spanning normalizer folded across a line break. A case that
/// an interrupted recording kept from before keeps its entry, and without an earlier list the
/// field stays unset, so `cases_normalized_across_lines` scans for `[..]` as it did.
fn keep_across_lines(
    config: &mut Config,
    previous: Option<&Config>,
    outcome: &RecordOutcome,
    mut found: BTreeMap<String, Vec<String>>,
) {
    config.across_lines = None;
    if !config.normalizers.values().any(|p| spans_lines(p)) {
        return;
    }
    let fresh: BTreeSet<&String> = outcome.recorded.iter().collect();
    let kept = config.recorded.iter().filter(|name| !fresh.contains(name));
    for name in kept {
        let Some(old) = previous.and_then(|c| c.across_lines.as_ref()) else {
            return;
        };
        if let Some(fields) = old.get(name) {
            found.insert(name.clone(), fields.clone());
        }
    }
    config.across_lines = Some(found);
}

fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
        out.entry(n.case.clone()).or_default().push(n.field.clone());
    }
    out
}

enum Expect {
    Code(i32),
    Failed,
    Killed,
    Skip,
}

struct Spec {
    name: String,
    case: Case,
    /// The expected texts `replay` compares, by field (`CLI_TEXT_FIELDS`).
    texts: BTreeMap<&'static str, Vec<u8>>,
    status: Expect,
    out_dir: Option<PathBuf>,
    removed: Option<Vec<PathBuf>>,
    binary: bool,
}

fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    walk_files(base)
        .into_iter()
        .map(|p| {
            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
            let bytes = std::fs::read(&p).unwrap_or_default();
            (rel, bytes)
        })
        .collect()
}

/// The recorded cases that wrote a file whose name a normalizer matches (a file named by a
/// time or an id). `app replay` pairs such a file by its normalized name; a comparison by
/// exact path, as trycmd does for the lifted `cargo test`, cannot.
pub(crate) fn cases_with_normalized_file_names(
    repo: &Path,
    config: &Config,
) -> Result<Vec<String>> {
    let norm = Normalizers::new(config)?;
    let mut cases = Vec::new();
    for entry in std::fs::read_dir(cases_dir(repo))
        .into_iter()
        .flatten()
        .flatten()
    {
        let folder = entry.file_name().to_string_lossy().into_owned();
        let Some(case) = folder.strip_suffix(".out") else {
            continue;
        };
        let renamed = read_files(&entry.path()).keys().any(|path| {
            let written = path.to_string_lossy();
            norm.apply(&written) != written
        });
        if renamed {
            cases.push(case.to_string());
        }
    }
    cases.sort();
    Ok(cases)
}

/// Whether a normalizer pattern can match a line break. Its `[..]` then stands for several
/// lines, which trycmd (a wildcard inside one line) cannot match again.
pub(crate) fn spans_lines(pattern: &str) -> bool {
    use regex_syntax::hir::{Class, Hir, HirKind};
    fn walk(hir: &Hir) -> bool {
        match hir.kind() {
            HirKind::Literal(lit) => lit.0.contains(&b'\n'),
            HirKind::Class(Class::Unicode(class)) => class
                .ranges()
                .iter()
                .any(|r| r.start() <= '\n' && '\n' <= r.end()),
            HirKind::Class(Class::Bytes(class)) => class
                .ranges()
                .iter()
                .any(|r| r.start() <= b'\n' && b'\n' <= r.end()),
            HirKind::Repetition(rep) => walk(&rep.sub),
            HirKind::Capture(cap) => walk(&cap.sub),
            HirKind::Concat(all) | HirKind::Alternation(all) => all.iter().any(walk),
            HirKind::Empty | HirKind::Look(_) => false,
        }
    }
    regex_syntax::parse(pattern).is_ok_and(|hir| walk(&hir))
}

/// The cases trycmd cannot check because a saved normalizer that spans lines rewrote what they
/// print or write: its `[..]` stands for several lines, and trycmd matches one line. A case
/// `app record` wrote is listed when the recording saw a normalizer match across a line break
/// in it (`across_lines`). Every other case, and every case of a recording that kept no such
/// list, counts when its standard output or error (in its `.stdout`/`.stderr` file or inline in
/// its `.toml`) or a file it wrote holds a `[..]`.
pub(crate) fn cases_normalized_across_lines(repo: &Path, config: &Config) -> Vec<String> {
    if !config.normalizers.values().any(|p| spans_lines(p)) {
        return Vec::new();
    }
    let wild = |bytes: Option<&Vec<u8>>| {
        bytes.is_some_and(|b| String::from_utf8_lossy(b).contains("[..]"))
    };
    let recorded: BTreeSet<&String> = config.recorded.iter().collect();
    load_specs(&cases_dir(repo))
        .unwrap_or_default()
        .into_iter()
        .filter(|spec| match &config.across_lines {
            Some(listed) if recorded.contains(&spec.name) => listed.contains_key(&spec.name),
            _ => {
                wild(spec.texts.get("stdout"))
                    || wild(spec.texts.get("stderr"))
                    || spec.out_dir.as_deref().is_some_and(|dir| {
                        read_files(dir)
                            .values()
                            .any(|bytes| String::from_utf8_lossy(bytes).contains("[..]"))
                    })
            }
        })
        .map(|spec| spec.name)
        .collect()
}

/// What the top of a case's `.toml` says: the arguments, the environment and the expected exit.
/// The one reader of these keys, for `replay` (through `load_spec`) and for the obligation
/// evidence, which reads nothing else of a case.
struct CaseHeader {
    args: Vec<String>,
    /// `env.add`; a value that is not a string reads as empty, as `replay` runs it.
    env: BTreeMap<String, String>,
    env_remove: Vec<String>,
    inherit_env: bool,
    status: Expect,
}

fn case_header(doc: &DocumentMut, path: &Path) -> Result<CaseHeader> {
    let args = match doc.get("args") {
        Some(item) if item.as_array().is_some() => item
            .as_array()
            .into_iter()
            .flatten()
            .map(|v| {
                v.as_str()
                    .map(str::to_string)
                    .unwrap_or_else(|| v.to_string())
            })
            .collect(),
        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
        None => Vec::new(),
    };
    let mut header = CaseHeader {
        args,
        env: BTreeMap::new(),
        env_remove: Vec::new(),
        inherit_env: true,
        status: Expect::Code(0),
    };
    if let Some(env) = doc.get("env") {
        header.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
            for (k, v) in add.iter() {
                header
                    .env
                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
            }
        }
        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
            header.env_remove = remove
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect();
        }
    }
    if let Some(item) = doc.get("status") {
        header.status = match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
            (Some("success"), _) => Expect::Code(0),
            (Some("failed"), _) => Expect::Failed,
            (Some("interrupted"), _) => Expect::Killed,
            (Some("skipped"), _) => Expect::Skip,
            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
            _ => bail!("{}: unknown `status`", path.display()),
        };
    }
    Ok(header)
}

fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
    let name = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let doc: DocumentMut = text
        .parse()
        .with_context(|| format!("parsing {}", path.display()))?;
    let header = case_header(&doc, path)?;
    let mut case = Case::new(header.args);
    let side = |key: &str| -> Result<Option<Vec<u8>>> {
        match expected_source(&doc, &name, key) {
            ExpectedSource::Inline(s) => Ok(Some(s.into_bytes())),
            ExpectedSource::File(file) => {
                let file = dir.join(file);
                Ok(if file.exists() {
                    Some(
                        std::fs::read(&file)
                            .with_context(|| format!("reading {}", file.display()))?,
                    )
                } else {
                    None
                })
            }
        }
    };
    case.stdin = side("stdin")?;
    case.inherit_env = header.inherit_env;
    case.env = header.env;
    case.env_remove = header.env_remove;
    let base = if let Some(b) = doc
        .get("fs")
        .and_then(|f| f.get("base"))
        .and_then(Item::as_str)
    {
        let joined = dir.join(b);
        let dir_canon = dir.canonical().unwrap_or_else(|_| dir.to_path_buf());
        if let Ok(base_canon) = joined.canonical() {
            ensure!(
                base_canon.starts_with(&dir_canon),
                "{}: `fs.base` `{b}` escapes the cases folder",
                path.display()
            );
            base_canon
        } else {
            ensure!(
                safe_relative(b),
                "{}: `fs.base` `{b}` must be a relative path inside the cases folder",
                path.display()
            );
            joined
        }
    } else {
        dir.join(format!("{name}.in"))
    };
    if base.is_dir() {
        case.files = read_files(&base);
    }
    if let Some(remove) = doc
        .get("fs")
        .and_then(|f| f.get("remove"))
        .and_then(Item::as_array)
    {
        let mut paths = Vec::new();
        for item in remove {
            if let Some(s) = item.as_str() {
                ensure!(
                    safe_relative(s),
                    "{}: `fs.remove` `{s}` must be a relative path inside the case directory",
                    path.display()
                );
                paths.push(PathBuf::from(s));
            }
        }
        case.remove = paths;
    }
    let status = header.status;
    let out_dir = dir.join(out_dir_name(&name));
    let mut texts = BTreeMap::new();
    for field in CLI_TEXT_FIELDS {
        if let Some(bytes) = side(field)? {
            texts.insert(field, bytes);
        }
    }
    Ok(Spec {
        texts,
        status,
        out_dir: out_dir.is_dir().then_some(out_dir),
        removed: side(REMOVED_EXT)?.map(|bytes| {
            String::from_utf8_lossy(&bytes)
                .lines()
                .filter(|l| !l.is_empty())
                .map(PathBuf::from)
                .collect()
        }),
        binary: case_is_binary(&doc),
        name,
        case,
    })
}

/// The expected texts of a CLI case that `replay` compares with `compare`, so with the `...`
/// line wildcard. The one list: `load_spec` reads these, `replay` compares these, and the
/// obligations' standing sweeps these for a wildcard. A field compared anywhere else must be
/// added here, or the sweep would miss it.
pub(crate) const CLI_TEXT_FIELDS: [&str; 3] = ["stdout", "stderr", crate::effects::EXT];

/// Where `replay` reads one expected value of a CLI case.
pub(crate) enum ExpectedSource {
    /// The text is the value of the key in the case's `.toml`; the neighbouring file is not read.
    Inline(String),
    /// No text key: the file `<name>.<key>` next to the `.toml`, when it exists.
    File(String),
}

/// Where `replay` reads the expected `key` of the case `name` from. The one place that says it.
pub(crate) fn expected_source(doc: &DocumentMut, name: &str, key: &str) -> ExpectedSource {
    match doc.get(key).and_then(Item::as_str) {
        Some(text) => ExpectedSource::Inline(text.to_string()),
        None => ExpectedSource::File(format!("{name}.{key}")),
    }
}

/// The folder of files a CLI case expects the run to write, next to its `.toml`. `replay` reads
/// it only when it is a folder (a link to one counts).
pub(crate) fn out_dir_name(name: &str) -> String {
    format!("{name}.out")
}

/// Whether a CLI case marks its streams as bytes (`binary = true`): they are then compared
/// without the wildcard.
pub(crate) fn case_is_binary(doc: &DocumentMut) -> bool {
    doc.get("binary").and_then(Item::as_bool).unwrap_or(false)
}

fn float_width(format: &str) -> Result<usize> {
    match format {
        "f32le" => Ok(4),
        "f64le" => Ok(8),
        other => bail!("float file format `{other}`: use f32le or f64le"),
    }
}

fn floats(bytes: &[u8], width: usize) -> Vec<f64> {
    bytes
        .chunks_exact(width)
        .map(|c| match c.try_into() {
            Ok(b) if width == 4 => f64::from(f32::from_le_bytes(b)),
            _ => c.try_into().map_or(f64::NAN, f64::from_le_bytes),
        })
        .collect()
}

fn compare_floats(
    expected: &[u8],
    actual: &[u8],
    width: usize,
    tol: Option<f64>,
) -> Option<String> {
    if !expected.len().is_multiple_of(width) || expected.len() != actual.len() {
        return Some(format!(
            "{} values expected, {} bytes got ({} bytes per value)\n",
            expected.len() / width,
            actual.len(),
            width
        ));
    }
    let (e, a) = (floats(expected, width), floats(actual, width));
    let tol = tol.unwrap_or(0.0);
    let same =
        |x: f64, y: f64| x == y || (x.is_nan() && y.is_nan()) || crate::tolerance::near(x, y, tol);
    let off: Vec<usize> = (0..e.len()).filter(|&i| !same(e[i], a[i])).collect();
    let first = *off.first()?;
    let (mut abs, mut rel) = (0.0f64, 0.0f64);
    for &i in &off {
        let d = (e[i] - a[i]).abs();
        abs = abs.max(d);
        rel = rel.max(d / e[i].abs().max(a[i].abs()).max(f64::MIN_POSITIVE));
    }
    Some(format!(
        "{} of {} values differ beyond the tolerance ({tol}); first at index {first}: {} expected, {} got; max abs diff {abs:e}, max rel diff {rel:e}\n",
        off.len(),
        e.len(),
        e[first],
        a[first]
    ))
}

/// Text with its wildcard syntax made plain, so it is compared as written: `[..]` and a `...`
/// line become two-character codes after `\u{e000}`, which itself is doubled. Both sides go
/// through it, and `unescape_literal` gives the text back for a message.
fn escape_literal(text: &str) -> String {
    let text = text.replace('\u{e000}', "\u{e000}\u{e000}");
    let text = text.replace("[..]", "\u{e000}1");
    if !text.split('\n').any(|l| l == "...") {
        return text;
    }
    text.split('\n')
        .map(|l| if l == "..." { "\u{e000}2" } else { l })
        .collect::<Vec<_>>()
        .join("\n")
}

fn unescape_literal(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        if c != '\u{e000}' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('1') => out.push_str("[..]"),
            Some('2') => out.push_str("..."),
            Some(other) => out.push(other),
            None => out.push(c),
        }
    }
    out
}

/// Whether `text` holds what `app record` would read as a wildcard: `[..]` or a `...` line.
pub(crate) fn has_wildcard_text(text: &str) -> bool {
    text.contains("[..]") || text.split('\n').any(|l| l == "...")
}

pub(crate) fn compare(
    norm: &Normalizers,
    expected: &[u8],
    actual: &[u8],
    binary: bool,
    unordered: bool,
) -> Option<String> {
    compare_with(norm, expected, actual, binary, unordered, true)
}

/// `compare`, where `wild` says whether `[..]` and `...` lines in `expected` are wildcards (the
/// recording's own noise) or text the original printed.
pub(crate) fn compare_with(
    norm: &Normalizers,
    expected: &[u8],
    actual: &[u8],
    binary: bool,
    unordered: bool,
    wild: bool,
) -> Option<String> {
    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
    {
        let e = norm.canonical(&norm.apply(e));
        let a = norm.canonical(&norm.apply(a));
        let (e, a) = if wild {
            (e, a)
        } else {
            (escape_literal(&e), escape_literal(&a))
        };
        let tol = norm.float_tolerance;
        let shown = |text: String| if wild { text } else { unescape_literal(&text) };
        if unordered {
            if e.ends_with('\n') != a.ends_with('\n') {
                return Some(shown(render_diff(&e, &a, tol)));
            }
            let (mut el, mut al) = (lines(&e), lines(&a));
            let same = lines_match_in_any_order(&el, &al, tol);
            el.sort_unstable();
            al.sort_unstable();
            return (!same).then(|| {
                shown(format!(
                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
                    render_diff(&el.join("\n"), &al.join("\n"), tol)
                ))
            });
        }
        return (!text_matches(&e, &a, tol)).then(|| shown(render_diff(&e, &a, tol)));
    }
    (expected != actual).then(|| {
        format!(
            "binary content differs ({} bytes expected, {} bytes got)\n",
            expected.len(),
            actual.len()
        )
    })
}

/// Where `compare` found the outputs to part: the first changed line and the column where its
/// literal text stops matching, or the first difference inside JSON; the channel is left to the
/// caller.
pub(crate) fn locate(
    norm: &Normalizers,
    expected: &[u8],
    actual: &[u8],
    binary: bool,
    unordered: bool,
) -> crate::mismatch::At {
    locate_with(norm, expected, actual, binary, unordered, true)
}

/// `locate`, as `compare_with` reads the wildcards of `expected`.
pub(crate) fn locate_with(
    norm: &Normalizers,
    expected: &[u8],
    actual: &[u8],
    binary: bool,
    unordered: bool,
    wild: bool,
) -> crate::mismatch::At {
    let mut at = locate_in_text(norm, expected, actual, binary, unordered, wild);
    if !wild && let Some(context) = at.context.as_mut() {
        context.expected = unescape_literal(&context.expected);
        context.actual = unescape_literal(&context.actual);
    }
    at
}

fn locate_in_text(
    norm: &Normalizers,
    expected: &[u8],
    actual: &[u8],
    binary: bool,
    unordered: bool,
    wild: bool,
) -> crate::mismatch::At {
    use crate::mismatch::{At, text_at};
    let (false, Ok(e), Ok(a)) = (
        binary,
        std::str::from_utf8(expected),
        std::str::from_utf8(actual),
    ) else {
        return At {
            expected_len: Some(expected.len()),
            actual_len: Some(actual.len()),
            ..At::new("binary")
        };
    };
    let e = norm.canonical(&norm.apply(e));
    let a = norm.canonical(&norm.apply(a));
    let (e, a) = if wild {
        (e, a)
    } else {
        (escape_literal(&e), escape_literal(&a))
    };
    let structured = |v: &serde_json::Value| v.is_object() || v.is_array();
    if !unordered
        && let (Ok(ej), Ok(aj)) = (
            serde_json::from_str::<serde_json::Value>(&e),
            serde_json::from_str::<serde_json::Value>(&a),
        )
        && structured(&ej)
        && structured(&aj)
    {
        return crate::mismatch::locate_in(&ej, &aj);
    }
    let tol = norm.float_tolerance;
    let (mut el, mut al) = (lines(&e), lines(&a));
    if unordered {
        el.sort_unstable();
        al.sort_unstable();
    }
    let ops = diff_ops(&el, &al, |x, y| line_matches_within(x, y, tol));
    let lengths = |at: At| At {
        expected_len: Some(e.chars().count()),
        actual_len: Some(a.chars().count()),
        ..at
    };
    let changed = ops.iter().position(|op| !matches!(op, Op::Equal(..)));
    let Some(first) = changed else {
        let trail = |s: &str| s.ends_with('\n') || s.is_empty();
        let kind = if trail(&e) == trail(&a) {
            "text"
        } else {
            "trailing newline"
        };
        return lengths(At {
            line: Some(el.len().max(1)),
            ..At::new(kind)
        });
    };
    match ops[first] {
        Op::Delete(i) => {
            let insert = ops[first..]
                .iter()
                .take_while(|op| !matches!(op, Op::Equal(..)))
                .find_map(|op| match op {
                    Op::Insert(j) => Some(*j),
                    _ => None,
                });
            let Some(j) = insert else {
                return lengths(At {
                    line: Some(i + 1),
                    ..At::new("lines missing")
                });
            };
            let literal = el[i].split("[..]").next().unwrap_or_default();
            let at = text_at("text", literal, al[j]);
            let column = at.column.unwrap_or(1);
            let before: usize = el[..i].iter().map(|l| l.chars().count() + 1).sum();
            let before_bytes: usize = el[..i].iter().map(|l| l.len() + 1).sum();
            let offset = at.offset.unwrap_or_default();
            lengths(At {
                line: Some(i + 1),
                column: Some(column),
                offset: Some(crate::mismatch::Offset {
                    char: before + offset.char,
                    byte: before_bytes + offset.byte,
                }),
                context: at.context,
                ..At::new("text")
            })
        }
        Op::Insert(j) | Op::Equal(_, j) => lengths(At {
            line: Some(j + 1),
            ..At::new("lines added")
        }),
    }
}

pub struct ReplayOptions<'a> {
    pub repo: &'a Path,
    /// Command line of the build to test; the original's command when `None`.
    pub build: Option<&'a str>,
    pub timeout_secs: Option<u64>,
    /// Servers: the port the build listens on, when it is fixed.
    pub port: Option<u16>,
    /// Replay only this case (a library: only this unit).
    pub case: Option<&'a str>,
}

pub(crate) fn only_case<T>(
    items: Vec<T>,
    case: Option<&str>,
    name: impl Fn(&T) -> &str,
) -> Result<Vec<T>> {
    let Some(case) = case else {
        return Ok(items);
    };
    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
    ensure!(
        !kept.is_empty(),
        "no case named {case}; the cases are: {}",
        names.join(", ")
    );
    Ok(kept)
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Problem {
    pub field: String,
    pub detail: String,
    /// Where the output first differs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub at: Option<crate::mismatch::At>,
}

impl Problem {
    pub fn new(field: impl Into<String>, detail: impl Into<String>) -> Problem {
        Problem {
            field: field.into(),
            detail: detail.into(),
            at: None,
        }
    }

    /// With the first difference, its channel the field when it has none.
    pub fn at(mut self, mut at: crate::mismatch::At) -> Problem {
        if at.channel.is_empty() {
            at.channel.clone_from(&self.field);
        }
        self.at = Some(at);
        self
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Failure {
    pub case: String,
    pub args: Vec<String>,
    pub problems: Vec<Problem>,
}

/// Cases the build handed to the original: the front door appends a line to the file named by
/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
#[derive(Debug, Serialize, Deserialize)]
pub struct Fallback {
    pub cases: usize,
    pub total: usize,
    pub rate: f64,
    /// The cases that fell back.
    pub names: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ReplayOutcome {
    pub build: Vec<String>,
    pub passed: usize,
    pub total: usize,
    pub skipped: usize,
    pub failures: Vec<Failure>,
    pub fallback: Option<Fallback>,
    pub report: PathBuf,
    /// The distinct differences among the failing cases, most cases first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<crate::mismatch::Group>,
}

#[allow(clippy::too_many_arguments)]
fn check(
    norm: &Normalizers,
    command: &[String],
    repo: &Path,
    spec: &Spec,
    timeout: Duration,
    effects: Option<&crate::effects::EffectsConfig>,
    base: Option<&Path>,
    entry: Option<&CaseEntry>,
    recorded: bool,
) -> Result<(Vec<Problem>, Option<bool>)> {
    let run = run_case(command, repo, &spec.case, timeout, effects, base, false)?;
    // A case `app record` wrote reads wildcards only where it made them; a legacy or hand-written
    // case reads them everywhere, as it always did.
    let wild_in = |field: &str| wild_in(entry, field);
    let mut problems = Vec::new();
    let status_ok = match (&spec.status, &run.status) {
        (Expect::Code(e), Status::Code(a)) => e == a,
        (Expect::Failed, Status::Code(a)) => *a != 0,
        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
        _ => false,
    };
    if !status_ok {
        let expected = match &spec.status {
            Expect::Code(c) => format!("exit code {c}"),
            Expect::Failed => "a non-zero exit code".to_string(),
            Expect::Killed => "killed by a signal".to_string(),
            Expect::Skip => String::new(),
        };
        let short = |s: &str| s.trim_start_matches("exit code ").to_string();
        let kind = match &spec.status {
            Expect::Failed => "non-zero".to_string(),
            Expect::Killed => "killed".to_string(),
            _ => short(&expected),
        } + "→"
            + &match run.status {
                Status::Killed => "killed".to_string(),
                Status::Timeout => "timeout".to_string(),
                Status::Code(c) => c.to_string(),
            };
        problems.push(
            Problem::new(
                "status",
                format!("expected {expected}, got {}\n", run.status),
            )
            .at(crate::mismatch::At::new(&kind)),
        );
    }
    let no_effects = Vec::new();
    for field in CLI_TEXT_FIELDS {
        let actual = match field {
            "stdout" => &run.stdout,
            "stderr" => &run.stderr,
            crate::effects::EXT => run.effects.as_ref().unwrap_or(&no_effects),
            other => bail!("no run output named `{other}` to compare"),
        };
        let unordered = norm.unordered(&spec.name, field);
        let wild = wild_in(field);
        if let Some(expected) = spec.texts.get(field)
            && let Some(detail) = compare_with(norm, expected, actual, spec.binary, unordered, wild)
        {
            problems.push(Problem::new(field, detail).at(locate_with(
                norm,
                expected,
                actual,
                spec.binary,
                unordered,
                wild,
            )));
        }
    }
    if spec.removed.is_none() && recorded && !run.removed.is_empty() {
        problems.push(
            Problem::new(
                "removed files",
                format!(
                    "the original removed no file here, the build removed:\n{}",
                    run.removed
                        .iter()
                        .map(|p| format!("  {}\n", p.display()))
                        .collect::<String>()
                ),
            )
            .at(crate::mismatch::At {
                expected_len: Some(0),
                actual_len: Some(run.removed.len()),
                ..crate::mismatch::At::new("value")
            }),
        );
    }
    if let Some(failure) = run
        .effects
        .as_deref()
        .and_then(crate::effects::dump_failure)
    {
        problems.push(
            Problem::new(
                crate::effects::EXT,
                format!("{failure}: the database state was not compared\n"),
            )
            .at(crate::mismatch::At::new("db dump failed")),
        );
    }
    if let Some(expected) = &spec.removed
        && *expected != run.removed
    {
        let list = |paths: &[PathBuf]| -> String {
            paths
                .iter()
                .map(|p| format!("  {}\n", p.display()))
                .collect()
        };
        problems.push(
            Problem::new(
                "removed files",
                format!(
                    "expected removed:\n{}got removed:\n{}",
                    list(expected),
                    list(&run.removed)
                ),
            )
            .at(crate::mismatch::At {
                expected_len: Some(expected.len()),
                actual_len: Some(run.removed.len()),
                ..crate::mismatch::At::new("value")
            }),
        );
    }
    let mut paired: BTreeSet<PathBuf> = BTreeSet::new();
    if let Some(out_dir) = &spec.out_dir {
        let recorded = read_files(out_dir);
        let pairs = norm.pair_files(recorded.keys(), run.files.keys());
        for (path, expected) in recorded {
            let field = file_field(&path);
            if let Some(other) = pairs.get(&path) {
                paired.insert(other.clone());
            }
            match pairs.get(&path).and_then(|other| run.files.get(other)) {
                None => problems.push(
                    Problem::new(field, "not written\n")
                        .at(crate::mismatch::At::new("not written")),
                ),
                Some(actual) => {
                    let unordered = norm.unordered(&spec.name, &field);
                    let width = norm.float_file(&path);
                    let detail = match width {
                        Some(width) => {
                            compare_floats(&expected, actual, width, norm.float_tolerance)
                        }
                        None => {
                            compare_with(norm, &expected, actual, false, unordered, wild_in(&field))
                        }
                    };
                    if let Some(detail) = detail {
                        let at = match width {
                            Some(_) => crate::mismatch::At::new("value"),
                            None => locate_with(
                                norm,
                                &expected,
                                actual,
                                false,
                                unordered,
                                wild_in(&field),
                            ),
                        };
                        problems.push(Problem::new(field, detail).at(at));
                    }
                }
            }
        }
    }
    // What the original did not write, the build must not write either: a case that has no `.out/`
    // is one where the original wrote nothing.
    if recorded {
        for path in run
            .written(&spec.case)
            .keys()
            .filter(|p| !paired.contains(*p))
        {
            problems.push(
                Problem::new(
                    format!("file {}", path.display()),
                    "written by the build, and the original did not write it\n",
                )
                .at(crate::mismatch::At::new("unexpected file")),
            );
        }
    }
    Ok((problems, run.fallback))
}

pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
    stable_paths(&report_body(outcome))
}

/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
/// same file and CI can commit it and fail on `git diff --exit-code`.
pub(crate) fn stable_paths(text: &str) -> String {
    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let tmp = std::env::temp_dir();
    let tmp = tmp.to_string_lossy();
    let tmp = tmp.trim_end_matches(['/', '\\']);
    let text = if tmp.len() > 1 {
        text.replace(tmp, "$TMPDIR")
    } else {
        text.to_string()
    };
    SANDBOX
        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
        .replace_all(&text, "rust-anything-app-$1")
        .into_owned()
}

fn report_body(outcome: &ReplayOutcome) -> String {
    let mut out = String::from("# App replay\n\n");
    out += &format!(
        "Build: `{}`\n\n",
        outcome
            .build
            .iter()
            .map(|w| shell_quote(w))
            .collect::<Vec<_>>()
            .join(" ")
    );
    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
    if outcome.skipped > 0 {
        out += &format!("Skipped: {}\n\n", outcome.skipped);
    }
    out += &match &outcome.fallback {
        Some(f) => format!(
            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
            f.rate * 100.0,
            f.cases,
            f.total
        ),
        None => "Fallback rate: not reported by this build\n\n".to_string(),
    };
    if outcome.failures.is_empty() {
        out += "Every case matches.\n";
        return out;
    }
    if !outcome.groups.is_empty() {
        out += "## Distinct differences\n\n| Cases | Id | Where | Kind |\n| ---: | --- | --- | --- |\n";
        for g in &outcome.groups {
            let place = match &g.path {
                Some(path) => format!("{} {path}", g.channel),
                None => g.channel.clone(),
            };
            out += &format!(
                "| {} | `{}` | `{}` | {} |\n",
                g.cases,
                g.id,
                place.replace('`', "'").replace('|', "\\|"),
                g.kind
            );
        }
        out += "\n";
    }
    out += "## Failing cases\n";
    for f in &outcome.failures {
        out += &format!(
            "\n### {}\n\nArguments: `{}`\n",
            f.case,
            f.args
                .iter()
                .map(|w| shell_quote(w))
                .collect::<Vec<_>>()
                .join(" ")
        );
        for p in &f.problems {
            if let Some(at) = &p.at {
                out += &format!("\n{}\n", at.describe().replace("```", "`\u{200b}``"));
            }
            out += &format!(
                "\n{}:\n\n```diff\n{}```\n",
                p.field,
                p.detail.replace("```", "`\u{200b}``")
            );
        }
    }
    out
}

fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
        .with_context(|| {
            format!(
                "no cases in {}: run `rust-anything app record` first",
                dir.display()
            )
        })?
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
        .collect();
    paths.sort();
    let specs = paths
        .iter()
        .map(|p| load_spec(dir, p))
        .collect::<Result<Vec<_>>>()?;
    ensure!(
        !specs.is_empty(),
        "no cases in {}: run `rust-anything app record` first",
        dir.display()
    );
    Ok(specs)
}

pub(crate) struct CasePreview {
    pub name: String,
    pub args: Vec<String>,
    pub stdout: Option<Vec<u8>>,
}

pub(crate) fn case_previews(dir: &Path) -> Result<Vec<CasePreview>> {
    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
        .with_context(|| format!("reading {}", dir.display()))?
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
        .collect();
    paths.sort();
    paths
        .iter()
        .map(|p| {
            load_spec(dir, p).map(|mut s| CasePreview {
                stdout: s.texts.remove("stdout"),
                name: s.name,
                args: s.case.args,
            })
        })
        .collect()
}

/// The recorded cases' arguments, each with whether the original exited 0.
pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
    Ok(load_specs(&cases_dir(repo))?
        .into_iter()
        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
        .collect())
}

/// What a recorded CLI case expects of the exit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RecordedStatus {
    Code(i32),
    Failed,
    Interrupted,
    Skipped,
}

/// A recorded CLI case, as much as the obligation ledger reads of it: the top of its `.toml`,
/// nothing else (no `fs.base`, no `.stdin`, no `.out` folder).
#[derive(Debug, Clone)]
pub(crate) struct RecordedCase {
    pub name: String,
    pub args: Vec<String>,
    /// The variables the case adds to the environment (`env.add`), with their values; a value
    /// that is not a string is empty.
    pub env_add: BTreeMap<String, String>,
    pub status: RecordedStatus,
    /// Where the case's stdin is: the text in the `.toml` or the file `<name>.stdin`. The file is
    /// read by whoever needs it, under the repository's guard.
    pub stdin: RecordedStdin,
}

/// The stdin of a recorded CLI case, as `replay` finds it (`expected_source`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RecordedStdin {
    Inline(String),
    /// The file `<name>.stdin` next to the `.toml`, when it exists; the name is the file's name.
    File(String),
}

/// The case `name` from the text of its `.toml`; an error when the text is not a case.
pub(crate) fn recorded_case(name: &str, text: &str) -> Result<RecordedCase> {
    let label = Path::new(name);
    let doc: DocumentMut = text
        .parse()
        .with_context(|| format!("parsing {}", label.display()))?;
    let header = case_header(&doc, label)?;
    Ok(RecordedCase {
        name: name.to_string(),
        args: header.args,
        env_add: header.env,
        status: match header.status {
            Expect::Code(c) => RecordedStatus::Code(c),
            Expect::Failed => RecordedStatus::Failed,
            Expect::Killed => RecordedStatus::Interrupted,
            Expect::Skip => RecordedStatus::Skipped,
        },
        stdin: match expected_source(&doc, name, "stdin") {
            ExpectedSource::Inline(text) => RecordedStdin::Inline(text),
            ExpectedSource::File(file) => RecordedStdin::File(file),
        },
    })
}

/// A line of `--inputs` as the tests read it: name, arguments, stdin.
#[cfg(test)]
pub(crate) type TestInput = (Option<String>, Vec<String>, Option<Vec<u8>>);

/// `read_inputs` for the tests of the fallback journal: the lines it writes must be ones
/// `app record --inputs` reads. Each is the name, the arguments and the stdin.
#[cfg(test)]
pub(crate) fn read_inputs_for_test(path: &Path) -> Result<Vec<TestInput>> {
    Ok(read_inputs(path)?
        .into_iter()
        .map(|(name, case)| (name, case.args, case.stdin))
        .collect())
}

pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
    write_report(replay_unwritten(opts)?)
}

/// `replay` with `--redact`: the report is only ever written as shapes.
pub fn replay_redacted(opts: &ReplayOptions) -> Result<ReplayOutcome> {
    redacted(replay_unwritten(opts)?)
}

/// Writes the outcome's report (`replay-report.md`).
pub(crate) fn write_report(outcome: ReplayOutcome) -> Result<ReplayOutcome> {
    std::fs::write(&outcome.report, report_markdown(&outcome))
        .with_context(|| format!("writing {}", outcome.report.display()))?;
    Ok(outcome)
}

/// The outcome as shapes only (`--redact`), its report written again from them.
pub fn redacted(mut outcome: ReplayOutcome) -> Result<ReplayOutcome> {
    crate::mismatch::redact_replay(&mut outcome);
    write_report(outcome)
}

/// The outcome with its distinct differences counted.
pub(crate) fn grouped(mut outcome: ReplayOutcome) -> ReplayOutcome {
    outcome.groups = crate::mismatch::replay_groups(&outcome.failures);
    outcome
}

/// `replay` without writing the report, for a caller that must leave the last one in place.
pub(crate) fn replay_unwritten(opts: &ReplayOptions) -> Result<ReplayOutcome> {
    replay_cases(opts).map(grouped)
}

fn replay_cases(opts: &ReplayOptions) -> Result<ReplayOutcome> {
    check_timeout(opts.timeout_secs)?;
    let repo = crate::walk::resolve_root(opts.repo)?;
    let dir = cases_dir(&repo);
    let config = Config::load(&repo)?;
    if config.is_none()
        && let Ok(state) = crate::front_door::State::load(&repo)
        && state.kind == crate::front_door::AppKind::Library
    {
        ensure!(
            opts.build.is_none(),
            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
            state.name
        );
        return crate::library::replay_unwritten(&repo, &state, opts.case);
    }
    let command = match (opts.build, &config) {
        (Some(build), _) => shell_split(build)?,
        (None, Some(c)) => c.run.clone(),
        (None, None) => bail!(
            "no {} in {}: run `rust-anything app record` first, or pass --build",
            CONFIG_FILE,
            dir.display()
        ),
    };
    ensure!(!command.is_empty(), "the build command is empty");
    let config = config.unwrap_or_else(|| Config::new("app"));
    let norm = Normalizers::new(&config)?;
    let timeout_secs = opts.timeout_secs.unwrap_or(config.timeout_secs);
    ensure!(
        timeout_secs >= 1,
        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
    );
    let timeout = Duration::from_secs(timeout_secs);
    ensure!(
        opts.port.is_none() || config.http.is_some(),
        "--port is for server recordings (`app record --http`), but the recording in {} is a CLI's",
        dir.display()
    );
    if config.http.is_some() {
        return crate::http::replay(
            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
        );
    }
    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
    let effects = config.effects.as_ref();
    let base = if config.fresh.is_empty() {
        None
    } else {
        let base = dir.join(FRESH_DIR);
        ensure!(
            base.is_dir(),
            "no {}: record again to snapshot the fresh files",
            base.display()
        );
        Some(base)
    };
    // What `app record` wrote: which cases were edited since, which fields hold its wildcards.
    let meta = CaseMeta::load(&dir)?;
    let mut edited: BTreeMap<String, &str> = BTreeMap::new();
    let mut legacy: Vec<&str> = Vec::new();
    for spec in &specs {
        match meta.as_ref().and_then(|m| m.cases.get(&spec.name)) {
            Some(entry) => {
                if case_digest(&dir, &spec.name) != entry.digest {
                    edited.insert(
                        spec.name.clone(),
                        "the case's files differ from what `app record` wrote (edited by hand?): record again, or delete its entry from rust-anything.cases.json to accept the edit",
                    );
                }
            }
            None => {
                let in_files = spec.out_dir.as_deref().is_some_and(|d| {
                    read_files(d)
                        .values()
                        .any(|b| has_wildcard_text(&String::from_utf8_lossy(b)))
                });
                if in_files
                    || spec
                        .texts
                        .values()
                        .any(|t| has_wildcard_text(&String::from_utf8_lossy(t)))
                {
                    legacy.push(&spec.name);
                }
            }
        }
    }
    if config.recorded.is_empty() {
        // Hand-written cases or a build-only replay: nothing was recorded to compare with.
    } else if meta.is_none() {
        note_once(
            "note: legacy recording: it has no rust-anything.cases.json, so edited, skipped or removed cases cannot be told from the recording and `[..]` / `...` lines are read as wildcards. Record again to fix both.",
        );
    } else if !legacy.is_empty() {
        let (verb, their) = if legacy.len() == 1 {
            ("is", "its")
        } else {
            ("are", "their")
        };
        let mut names = legacy
            .iter()
            .take(5)
            .copied()
            .collect::<Vec<_>>()
            .join(", ");
        if legacy.len() > 5 {
            names.push_str(&format!(" and {} more", legacy.len() - 5));
        }
        note_once(&format!(
            "note: {} {verb} not in rust-anything.cases.json (written by hand or by an older recording): {names}; {their} `[..]` and `...` lines are read as wildcards.",
            crate::report::count(legacy.len(), "case")
        ));
    }
    let check_one = |spec: &Spec| {
        if matches!(spec.status, Expect::Skip) {
            return Ok((Vec::new(), None));
        }
        let entry = meta.as_ref().and_then(|m| m.cases.get(&spec.name));
        check(
            &norm,
            &command,
            &repo,
            spec,
            timeout,
            effects,
            base.as_deref(),
            entry,
            entry.is_some() || config.recorded.contains(&spec.name),
        )
    };
    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
        specs.iter().map(check_one).collect()
    } else {
        par_map(&specs, check_one)
    };
    let mut outcome = ReplayOutcome {
        build: command.clone(),
        passed: 0,
        total: 0,
        skipped: 0,
        failures: Vec::new(),
        fallback: None,
        report: dir.join(REPORT_FILE),
        groups: Vec::new(),
    };
    let (mut reported, mut fell_back) = (false, Vec::new());
    for (spec, result) in specs.iter().zip(results) {
        if matches!(spec.status, Expect::Skip) {
            // A skipped case is a case that was not checked: it counts as one that did not pass,
            // so neither the count nor `app lift` can read it as green.
            outcome.skipped += 1;
            outcome.total += 1;
            outcome.failures.push(Failure {
                case: spec.name.clone(),
                args: spec.case.args.clone(),
                problems: vec![
                    Problem::new(
                        "recording",
                        "the case says `status = \"skipped\"`, so it was not run: remove the case or its `skipped` status\n",
                    )
                    .at(crate::mismatch::At::new("skipped")),
                ],
            });
            continue;
        }
        let (mut problems, fallback) = result?;
        if let Some(why) = edited.get(&spec.name) {
            problems.push(
                Problem::new("recording", format!("{why}\n"))
                    .at(crate::mismatch::At::new("edited")),
            );
        }
        outcome.total += 1;
        reported |= fallback.is_some();
        if fallback == Some(true) {
            fell_back.push(spec.name.clone());
        }
        if problems.is_empty() {
            outcome.passed += 1;
        } else {
            outcome.failures.push(Failure {
                case: spec.name.clone(),
                args: spec.case.args.clone(),
                problems,
            });
        }
    }
    if opts.case.is_none()
        && let Some(meta) = &meta
    {
        for name in meta.cases.keys() {
            if specs.iter().any(|s| &s.name == name) {
                continue;
            }
            outcome.total += 1;
            outcome.failures.push(Failure {
                case: name.clone(),
                args: Vec::new(),
                problems: vec![
                    Problem::new(
                        "recording",
                        "the case was recorded and its files are gone: record again, or delete its entry from rust-anything.cases.json to drop it\n",
                    )
                    .at(crate::mismatch::At::new("removed")),
                ],
            });
        }
    }
    if reported {
        outcome.fallback = Some(Fallback {
            cases: fell_back.len(),
            total: outcome.total,
            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
            names: fell_back,
        });
    }
    Ok(outcome)
}

#[cfg(test)]
mod tests {
    #[cfg(unix)]
    struct KillOnDrop(u32);

    #[cfg(unix)]
    impl Drop for KillOnDrop {
        fn drop(&mut self) {
            let _ = std::process::Command::new("kill")
                .args(["-9", &self.0.to_string()])
                .status();
        }
    }

    #[cfg(unix)]
    fn wait_until_gone(pid: u32) -> bool {
        let start = Instant::now();
        while start.elapsed() < Duration::from_secs(3) {
            let alive = std::process::Command::new("kill")
                .args(["-0", &pid.to_string()])
                .status()
                .map(|status| status.success())
                .unwrap_or(false);
            if !alive {
                return true;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        false
    }

    use super::*;

    #[test]
    fn recording_lock_repairs_missing_ignore_rules_on_retry() {
        let repo = temp_dir("record-lock-ignore").unwrap();
        let ignore = repo.join("rust/.app-record/.gitignore");
        let rules = b"/.gitignore\n/app-record.lock\n/.gitignore.rust-anything.[0-9]*.[0-9]*.tmp\n";
        drop(AppRecordLock::take(&repo).unwrap());
        assert_eq!(std::fs::read(&ignore).unwrap(), rules);
        for (before, after) in [
            (&b""[..], &rules[..]),
            (b"/app-record.lock", b"/app-record.lock\n/.gitignore\n/.gitignore.rust-anything.[0-9]*.[0-9]*.tmp\n"),
            (
                b"# mine\r\n/.gitignore.rust-anything.[0-9]*.[0-9]*.tmp\r\n/app-record.lock\r\n/.gitignore",
                b"# mine\r\n/.gitignore.rust-anything.[0-9]*.[0-9]*.tmp\r\n/app-record.lock\r\n/.gitignore",
            ),
        ] {
            std::fs::write(&ignore, before).unwrap();
            drop(AppRecordLock::take(&repo).unwrap());
            assert_eq!(std::fs::read(&ignore).unwrap(), after);
        }
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn recording_lock_leaves_a_symlinked_ignore_file_alone() {
        let repo = temp_dir("record-lock-symlink").unwrap();
        let dir = repo.join("rust/.app-record");
        std::fs::create_dir_all(&dir).unwrap();
        let target = repo.join("custom");
        std::fs::write(&target, "custom\n").unwrap();
        std::os::unix::fs::symlink(&target, dir.join(".gitignore")).unwrap();
        assert!(AppRecordLock::take(&repo).is_err());
        assert_eq!(std::fs::read(&target).unwrap(), b"custom\n");
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn a_snapshot_that_cannot_be_put_in_place_keeps_the_last_one() {
        let dir = temp_dir("snapshot-commit").unwrap();
        let dest = dir.join("files");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("seed.json"), "{}").unwrap();
        let snapshot = PendingSnapshot {
            dir: Some(dir.join("files.pending")),
            dest: dest.clone(),
        };
        let committed = snapshot.commit();
        let kept = std::fs::read_to_string(dest.join("seed.json")).ok();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(committed.is_err());
        assert_eq!(kept.as_deref(), Some("{}"));
    }

    #[test]
    fn a_swap_puts_the_staged_folder_where_the_old_one_was() {
        let dir = temp_dir("swap-ok").unwrap();
        let dest = dir.join("files");
        let staged = dir.join("files.pending");
        let old = dir.join("files.old");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("seed.json"), "old").unwrap();
        std::fs::create_dir_all(&staged).unwrap();
        std::fs::write(staged.join("seed.json"), "new").unwrap();
        let swapped = swap_in(&staged, &dest, &old);
        let kept = std::fs::read_to_string(dest.join("seed.json")).ok();
        // The previous folder is handed back rather than removed, so a later step can put it back.
        let handed_back = swapped.as_ref().ok().cloned().flatten();
        let staged_left = staged.exists();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(swapped.is_ok(), "{swapped:?}");
        assert_eq!(kept.as_deref(), Some("new"));
        assert_eq!(
            handed_back.as_deref(),
            Some(old.as_path()),
            "the previous folder comes back to the caller"
        );
        assert!(!staged_left, "the staged folder is not left behind");
    }

    #[test]
    fn a_failed_swap_puts_the_previous_folder_back_and_drops_the_staged_one() {
        let dir = temp_dir("swap-back").unwrap();
        let dest = dir.join("files");
        let staged = dir.join("files.pending");
        let old = dir.join("files.old");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("seed.json"), "old").unwrap();
        // No staged folder: the swap cannot happen.
        let swapped = swap_in(&staged, &dest, &old);
        let kept = std::fs::read_to_string(dest.join("seed.json")).ok();
        let leftover = old.exists() || staged.exists();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(swapped.is_err(), "a swap with nothing staged has to fail");
        assert_eq!(kept.as_deref(), Some("old"), "the previous folder is back");
        assert!(!leftover, "neither folder is left behind");
    }

    #[test]
    fn a_first_swap_with_no_previous_folder_reports_the_failure() {
        let dir = temp_dir("swap-first").unwrap();
        let dest = dir.join("files");
        let staged = dir.join("files.pending");
        let old = dir.join("files.old");
        // Neither exists: `moved` is false, so there is nothing to put back.
        let swapped = swap_in(&staged, &dest, &old);
        let _ = std::fs::remove_dir_all(&dir);
        let err = format!("{:#}", swapped.unwrap_err());
        assert!(err.contains("replacing"), "{err}");
        assert!(!err.contains("holds neither"), "{err}");
    }

    #[test]
    fn a_byte_order_mark_at_the_start_of_an_inputs_file_is_skipped() {
        // Windows PowerShell 5 (`-Encoding utf8`) and older Notepad save a UTF-8 file with one.
        let path =
            std::env::temp_dir().join(format!("ra-app-inputs-bom-{}.jsonl", std::process::id()));
        std::fs::write(&path, "\u{feff}{\"name\": \"hi\", \"args\": [\"a\"]}\n").unwrap();
        let read = read_inputs(&path);
        std::fs::remove_file(&path).unwrap();
        let cases = read.unwrap();
        assert_eq!(cases.len(), 1);
        assert_eq!(cases[0].0.as_deref(), Some("hi"));
    }

    #[test]
    fn removed_paths_are_written_with_forward_slashes() {
        let paths = vec![
            PathBuf::from("top.txt"),
            Path::new("stale").join("nested").join("old.txt"),
        ];
        assert_eq!(removed_list(&paths), "top.txt\nstale/nested/old.txt\n");
    }

    #[test]
    fn shell_quote_leaves_plain_words_and_quotes_the_rest() {
        for plain in [
            "cargo",
            "./target/release/app",
            "a=b",
            "--flag",
            "user@host:1,2+3%",
        ] {
            assert_eq!(shell_quote(plain), plain);
        }
        assert_eq!(shell_quote(""), "''");
        assert_eq!(shell_quote("my app/bin"), "'my app/bin'");
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
        assert_eq!(shell_quote("$HOME"), "'$HOME'");
        assert_eq!(shell_quote("*.rs"), "'*.rs'");
        assert_eq!(shell_quote("a;b"), "'a;b'");
        assert_eq!(
            shell_quote("--node-arg=--import=tsx"),
            "--node-arg=--import=tsx"
        );
        assert_eq!(shell_quote("$(x)"), "'$(x)'");
    }

    #[test]
    fn the_case_folder_is_redacted_where_a_program_escapes_its_backslashes() {
        let work = r"C:\Users\me\AppData\Local\Temp\rust-anything-app-run-4242-7\cwd";
        let forms = with_escaped_backslashes(vec![work.to_string()]);
        // Node's ENOENT error: the message has the plain path, the `path` field the escaped one.
        let stderr = format!(
            "Error: ENOENT: no such file or directory, open '{work}\\notes.txt'\n  path: '{}\\\\notes.txt'\n",
            work.replace('\\', r"\\")
        );
        assert_eq!(
            redact_cwd(stderr, &forms),
            "Error: ENOENT: no such file or directory, open '[CWD]\\notes.txt'\n  path: '[CWD]\\\\notes.txt'\n"
        );
        let json = format!("{{\"cwd\":\"{}\"}}", work.replace('\\', r"\\"));
        assert_eq!(redact_cwd(json, &forms), r#"{"cwd":"[CWD]"}"#);
        // Another folder that only shares a prefix with the case folder stays.
        let other = r"C:\Users\me\AppData\Local\Temp\other".to_string();
        assert_eq!(redact_cwd(other.clone(), &forms), other);

        let posix = "/tmp/rust-anything-app-run-4242-7/cwd";
        let forms = with_escaped_backslashes(vec![posix.to_string()]);
        assert_eq!(forms, [posix]);
        assert_eq!(
            redact_cwd(format!("open '{posix}/notes.txt'"), &forms),
            "open '[CWD]/notes.txt'"
        );
    }

    #[test]
    fn a_case_folder_with_a_backslash_is_redacted_plain_and_doubled() {
        let root = temp_dir("cwd-forms").unwrap();
        // Nested folders on Windows, one folder whose name holds a backslash elsewhere: either
        // way the path has a `\` to double.
        let work = root.join(r"case\cwd");
        std::fs::create_dir_all(&work).unwrap();
        let forms = cwd_forms(&work);
        let shown = work.canonical().unwrap().to_string_lossy().into_owned();
        let doubled = shown.replace('\\', r"\\");
        let redacted = redact_cwd(format!("{shown}\n{{\"cwd\":\"{doubled}\"}}\n"), &forms);
        std::fs::remove_dir_all(&root).unwrap();
        assert_eq!(redacted, "[CWD]\n{\"cwd\":\"[CWD]\"}\n");
    }

    #[test]
    fn given_names_keep_their_tail() {
        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
        assert_ne!(a, b);
        assert_eq!(
            a,
            "tests-format-typescript-conformance-types-never-never-ts"
        );
        assert_eq!(slug(&a).len(), 23);
    }

    #[test]
    fn a_path_in_a_hint_survives_being_pasted() {
        let cli_word = |word, windows| super::cli_word(word, windows, HintWord::BarePath);
        // Linux and macOS: `shell_quote`.
        assert_eq!(cli_word("rust/slug-rs", false), "rust/slug-rs");
        assert_eq!(
            cli_word("/home/me/my project/rust/slug-rs", false),
            "'/home/me/my project/rust/slug-rs'"
        );
        // Native Windows: ordinary drive paths use double quotes. A PowerShell interpolation
        // or a trailing backslash in a quoted path needs a literal string.
        assert_eq!(
            cli_word(r"C:\Users\me\AppData\Local\Temp\x-rs", true),
            r#""C:\Users\me\AppData\Local\Temp\x-rs""#
        );
        assert_eq!(cli_word("rust/slug-rs", true), "rust/slug-rs");
        assert_eq!(
            cli_word(r"C:\Users\First Last\My Projects\rust\slug-rs", true),
            r#""C:\Users\First Last\My Projects\rust\slug-rs""#
        );
        assert_eq!(cli_word(r"C:\pay$\x", true), r#"C:\pay$"\x""#);
        assert_eq!(cli_word(r"C:\100%\x", true), r#""C:\100%\x""#);
        assert_eq!(cli_word(r"C:\it's $tax\x", true), r#"C:\it"'s "$"tax\x""#);
        assert_eq!(cli_word(r"C:\ notes$team", true), r#"C:"\ notes"$"team""#);
        assert_eq!(cli_word(r"\ notes$team", true), r#"\."\ notes"$"team""#);
        assert_eq!(
            super::cli_word("$math.ts", true, HintWord::Argument),
            r#"$"math.ts""#
        );
        assert_eq!(
            super::cli_word(" math$team.ts", true, HintWord::Argument),
            "' math$team.ts'"
        );
        assert_eq!(cli_word(r"C:\Projects\demo", false), r"'C:\Projects\demo'");
        assert_eq!(cli_word(r"\\server\share", false), r"'\\server\share'");
        assert_eq!(cli_word(r"C:\my dir\", true), r#""C:\my dir\.""#);
        assert_eq!(cli_word(r"C:\it's here\x", true), r#""C:\it's here\x""#);
        for plain in [r"C:\repo\version`2", r"C:\repo\“Beta”"] {
            assert_eq!(cli_word(plain, true), plain);
            assert_eq!(
                super::cli_word(plain, true, HintWord::QuotedPath),
                format!("'{plain}'")
            );
        }
        for quoted in [
            r"C:\my docs\version`2",
            r"C:\docs&notes\“Beta”",
            r"C:\$repo\“Beta”",
        ] {
            assert_eq!(cli_word(quoted, true), format!("'{quoted}'"));
        }
        // A pasted hint is split the way `app record` splits a command line.
        for windows in [false, true] {
            let hint = format!(
                "rust-anything record {}",
                cli_word("/home/me/my project/rust/x", windows)
            );
            assert_eq!(
                shell_split(&hint).unwrap(),
                ["rust-anything", "record", "/home/me/my project/rust/x"],
                "{hint}"
            );
        }
    }

    #[test]
    fn reports_do_not_carry_sandbox_paths() {
        let tmp = std::env::temp_dir();
        let line = format!(
            "-cwd {}\n",
            tmp.join("rust-anything-app-run-4242-7")
                .join("cwd")
                .display()
        );
        let stable = stable_paths(&line);
        assert!(!stable.contains("4242"), "{stable}");
        assert!(stable.contains("$TMPDIR"), "{stable}");
        assert_eq!(
            stable,
            stable_paths(&line.replace("4242-7", "99-0")),
            "{stable}"
        );
    }

    fn text_matches_exact(e: &str, a: &str) -> bool {
        text_matches(e, a, None)
    }

    fn norm_with_tolerance(tol: Option<f64>) -> Normalizers {
        Normalizers::new(&Config {
            schema: SCHEMA.to_string(),
            name: "app".to_string(),
            run: Vec::new(),
            normalize: Vec::new(),
            normalizers: BTreeMap::new(),
            timeout_secs: default_timeout(),
            http: None,
            float_tolerance: tol,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::new(),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        })
        .unwrap()
    }

    #[test]
    fn unordered_lines_pair_up_by_value_within_the_tolerance() {
        let norm = norm_with_tolerance(Some(1e-9));
        // `2.0` meets `2.0` and `10.0` meets `9.999999999999999`, but `10.0` sorts before `2.0`
        // as text, so pairing the sorted lines by position compared `10.0` against `2.0`.
        let expected = b"n 2.0\nn 10.0\n";
        let actual = b"n 2.0\nn 9.999999999999999\n";
        assert!(compare(&norm, expected, actual, false, false).is_none());
        assert!(compare(&norm, expected, actual, false, true).is_none());
        // A line that is genuinely different is still reported.
        let changed = b"n 2.0\nn 11.0\n";
        assert!(compare(&norm, expected, changed, false, true).is_some());
        // The order the lines arrive in does not matter.
        let swapped = b"n 9.999999999999999\nn 2.0\n";
        assert!(compare(&norm, expected, swapped, false, true).is_none());
    }

    #[test]
    fn unordered_lines_pair_up_around_a_wildcard() {
        let norm = norm_with_tolerance(Some(1e-9));
        // `[..]` takes the line the numeric pairing does not want, so a tolerance and a wildcard
        // in the same output do not fight over the ordering.
        let expected = b"n 10.0\nn [..]\n";
        assert!(compare(&norm, expected, b"n 10.0\nn 2.0\n", false, true).is_none());
        assert!(compare(&norm, expected, b"n 2.0\nn 10.0\n", false, true).is_none());
        assert!(
            compare(
                &norm,
                expected,
                b"n 2.0\nn 9.999999999999999\n",
                false,
                true
            )
            .is_none()
        );
        // Nothing to take the 10.0: both actual lines are far from it.
        assert!(compare(&norm, expected, b"n 2.0\nn 3.0\n", false, true).is_some());
    }

    #[test]
    fn unordered_lines_keep_a_plain_permutation_matching() {
        let norm = norm_with_tolerance(Some(1e-9));
        // The same lines in another order match whatever the numbers look like, and a value
        // written two ways stays a difference rather than becoming one by being re-sorted.
        assert!(compare(&norm, b"n 2\nn 2.0\n", b"n 2.0\nn 2\n", false, true).is_none());
        assert!(compare(&norm, b"n 2\nn 2\n", b"n 2.0\nn 2.0\n", false, true).is_some());
    }

    #[test]
    fn unordered_lines_without_a_tolerance_still_compare_as_text() {
        let norm = norm_with_tolerance(None);
        let expected = b"b\na\n";
        assert!(compare(&norm, expected, b"a\nb\n", false, true).is_none());
        assert!(compare(&norm, expected, b"a\nc\n", false, true).is_some());
        assert!(compare(&norm, expected, b"a\n", false, true).is_some());
        // Without a tolerance a number is text like any other, so this stays a mismatch.
        let numeric = b"n 10.0\nn 2.0\n";
        assert!(compare(&norm, numeric, b"n 2.0\nn 9.999999999999999\n", false, true).is_some());
    }

    #[cfg(unix)]
    #[test]
    fn a_cancelled_call_stops_its_cases_on_every_worker() {
        let dir = temp_dir("app-cancel").unwrap();
        let started = dir.join("started");
        let pidfile = dir.join("pids");
        let call = crate::mcp::as_call();
        let cancel = call.canceller();
        let watched = started.clone();
        let canceller = std::thread::spawn(move || {
            while !watched.exists() {
                std::thread::sleep(Duration::from_millis(5));
            }
            cancel();
        });
        let command = [
            "/bin/sh".into(),
            "-c".into(),
            format!(
                "sleep 30 & echo $! >> '{}'; touch '{}'; wait",
                pidfile.display(),
                started.display()
            ),
        ];
        let start = Instant::now();
        let runs = par_map(&[0, 1], |_| {
            run_case(
                &command,
                Path::new("."),
                &Case::new(Vec::new()),
                Duration::from_secs(60),
                None,
                None,
                false,
            )
        });
        canceller.join().unwrap();
        drop(call);
        let pids: Vec<u32> = std::fs::read_to_string(&pidfile)
            .unwrap()
            .lines()
            .map(|line| line.trim().parse().unwrap())
            .collect();
        let _reap: Vec<KillOnDrop> = pids.iter().copied().map(KillOnDrop).collect();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "{:?}",
            start.elapsed()
        );
        assert!(runs.iter().all(Result::is_err));
        for pid in pids {
            assert!(wait_until_gone(pid), "descendant {pid} is still running");
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_cancelled_call_does_not_wait_for_a_detached_child_holding_stdout() {
        let dir = temp_dir("app-cancel-detached").unwrap();
        let started = dir.join("started");
        let pidfile = dir.join("pid");
        let call = crate::mcp::as_call();
        let cancel = call.canceller();
        let watched = started.clone();
        let canceller = std::thread::spawn(move || {
            while !watched.exists() {
                std::thread::sleep(Duration::from_millis(5));
            }
            std::thread::sleep(Duration::from_millis(100));
            cancel();
        });
        let command = [
            "/bin/sh".into(),
            "-c".into(),
            format!(
                "perl -e 'setpgrp(0,0); sleep 15' & echo $! > '{}'; touch '{}'; exit 0",
                pidfile.display(),
                started.display()
            ),
        ];
        let start = Instant::now();
        let run = run_case(
            &command,
            Path::new("."),
            &Case::new(Vec::new()),
            Duration::from_secs(60),
            None,
            None,
            false,
        );
        canceller.join().unwrap();
        drop(call);
        let pid = std::fs::read_to_string(&pidfile)
            .unwrap()
            .trim()
            .parse::<u32>()
            .unwrap();
        let _reap = KillOnDrop(pid);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "{:?}",
            start.elapsed()
        );
        assert!(run.is_err());
    }

    #[cfg(unix)]
    #[test]
    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
            let command = ["/bin/sh".into(), "-c".into(), script.into()];
            let start = Instant::now();
            let run = run_case(
                &command,
                Path::new("."),
                &Case::new(Vec::new()),
                Duration::from_millis(200),
                None,
                None,
                false,
            )
            .unwrap();
            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_descendant_closing_stdout_after_the_child_is_captured() {
        let command = [
            "/bin/sh".into(),
            "-c".into(),
            "(sleep 0.7; echo late) & exit 0".into(),
        ];
        let start = Instant::now();
        let run = run_case(
            &command,
            Path::new("."),
            &Case::new(Vec::new()),
            Duration::from_secs(5),
            None,
            None,
            false,
        )
        .unwrap();
        assert!(
            start.elapsed() < Duration::from_secs(3),
            "{:?}",
            start.elapsed()
        );
        assert_eq!(run.status, Status::Code(0));
        assert_eq!(run.stdout, b"late\n");
    }

    #[cfg(unix)]
    #[test]
    fn replay_deadline_covers_a_daemon_that_left_the_process_group() {
        if Command::new("python3").arg("--version").output().is_err() {
            return;
        }
        let command = [
            "python3".into(),
            "-c".into(),
            "import os, time\nif os.fork() == 0:\n    os.setsid()\n    time.sleep(8)\n".into(),
        ];
        let start = Instant::now();
        let run = run_case(
            &command,
            Path::new("."),
            &Case::new(Vec::new()),
            Duration::from_millis(300),
            None,
            None,
            false,
        )
        .unwrap();
        assert!(
            start.elapsed() < Duration::from_secs(4),
            "{:?}",
            start.elapsed()
        );
        assert!(run.status == Status::Timeout, "{}", run.status);
    }

    #[cfg(unix)]
    #[test]
    fn temp_folders_of_runs_that_are_gone_are_swept() {
        let mut done = Command::new("true").spawn().unwrap();
        let dead = done.id();
        done.wait().unwrap();
        let base = std::env::temp_dir();
        let gone = base.join(format!("rust-anything-app-sweep-check-{dead}-0"));
        let ours = base.join(format!(
            "rust-anything-app-sweep-check-{}-0",
            std::process::id()
        ));
        for dir in [&gone, &ours] {
            std::fs::create_dir_all(dir).unwrap();
        }
        sweep_temp_dirs("sweep-check");
        let (gone_left, ours_left) = (gone.exists(), ours.exists());
        let _ = std::fs::remove_dir_all(&gone);
        let _ = std::fs::remove_dir_all(&ours);
        assert!(!gone_left, "the folder of a finished run stayed");
        assert!(ours_left, "the folder of this run was removed");
    }

    #[test]
    fn matching_follows_trycmd() {
        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
        assert!(text_matches_exact(
            "head\n...\ntail\n",
            "head\n1\n2\ntail\n"
        ));
        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
        // The final newline, a `\r` and a blank line are output too.
        assert!(!text_matches_exact("a\r\nb", "a\nb\n"));
        assert!(!text_matches_exact("a\nb\n", "a\nb"));
        assert!(!text_matches_exact("a\nb\n", "a\r\nb\n"));
        assert!(!text_matches_exact("", "\n"));
        assert!(!text_matches_exact("\n", ""));
        assert!(text_matches_exact("a\n\nb\n", "a\n\nb\n"));
    }

    #[test]
    fn text_the_original_printed_is_not_a_wildcard() {
        let norm = norm_with_tolerance(None);
        let original = b"Loading\n...\nDone\npattern: src/[..]/x\n";
        let wrong = b"Loading\nGARBAGE\nMORE GARBAGE\nDone\npattern: src/WHATEVER/x\n";
        // The legacy reading: the recording's text is its own wildcards.
        assert!(compare_with(&norm, original, wrong, false, false, true).is_none());
        // A case `app record` wrote names its wildcard fields: this one has none.
        assert!(compare_with(&norm, original, wrong, false, false, false).is_some());
        assert!(compare_with(&norm, original, original, false, false, false).is_none());
        let at = locate_with(&norm, original, wrong, false, false, false);
        assert_eq!(at.line, Some(2), "{at:?}");
        // The message shows the text as printed, not the code that kept it apart.
        let detail = compare_with(&norm, original, wrong, false, false, false).unwrap();
        assert!(
            detail.contains("- ...") && detail.contains("src/[..]/x"),
            "{detail}"
        );
        assert!(!detail.contains('\u{e000}'), "{detail}");
        // A real private-use character in the output is not mistaken for a code.
        let tricky = "[\u{e000}1\u{e000}]\n";
        assert!(
            compare_with(
                &norm,
                tricky.as_bytes(),
                tricky.as_bytes(),
                false,
                false,
                false
            )
            .is_none()
        );
        assert!(compare_with(&norm, b"[..]\n", tricky.as_bytes(), false, false, false).is_some());
    }

    #[test]
    fn a_line_with_another_number_of_tokens_keeps_what_it_shares() {
        assert_eq!(
            merge_line("result: w w w", "result: w w"),
            "result: w w[..]"
        );
        assert_eq!(merge_line("n=1 total", "n=22 33 total"), "n=[..] total");
        assert_eq!(merge_line("one", "two words"), "[..]");
        let merged = merge_noise("result: a b c\ndone\n", "result: a b\ndone\n");
        assert!(!text_matches_exact(
            &merged,
            "COMPLETELY DIFFERENT GARBAGE\ndone\n"
        ));
        assert!(text_matches_exact(&merged, "result: a b c d\ndone\n"));
    }

    #[test]
    fn numbers_match_within_the_tolerance() {
        let e = "step 1\nenergy 0.3\nat [..]\n";
        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
        assert!(!text_matches(e, a, None));
        assert!(text_matches(e, a, Some(1e-9)));
        assert!(!text_matches(
            e,
            "step 2\nenergy 0.3\nat 12:00\n",
            Some(1e-9)
        ));
        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
    }

    #[cfg(unix)]
    #[test]
    fn binary_capture_replays_its_text_companion_byte_for_byte() {
        let repo = temp_dir("binary-stream-pair").unwrap();
        let run = [
            "/bin/sh".to_string(),
            "-c".to_string(),
            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
        ];
        let recorded = record(&RecordOptions {
            repo: &repo,
            run: &run,
            inputs: None,
            normalize: &["timestamps".into()],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        })
        .unwrap();
        assert_eq!(recorded.cases, 1);
        let replayed = replay(&ReplayOptions {
            repo: &repo,
            build: None,
            timeout_secs: None,
            port: None,
            case: None,
        })
        .unwrap();
        assert_eq!(
            (replayed.passed, replayed.total),
            (1, 1),
            "{:?}",
            replayed.failures
        );
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[test]
    fn noise_is_classified() {
        let norm = Normalizers::new(&Config {
            schema: SCHEMA.to_string(),
            name: "app".to_string(),
            run: Vec::new(),
            normalize: Vec::new(),
            normalizers: BTreeMap::new(),
            timeout_secs: 30,
            http: None,
            float_tolerance: None,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::new(),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        })
        .unwrap();
        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
    }

    #[test]
    fn unordered_output_matches_in_any_order_but_not_other_lines() {
        let norm = Normalizers::new(&Config {
            schema: SCHEMA.to_string(),
            name: "app".to_string(),
            run: Vec::new(),
            normalize: Vec::new(),
            normalizers: BTreeMap::new(),
            timeout_secs: 30,
            http: None,
            float_tolerance: None,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        })
        .unwrap();
        assert!(norm.unordered("c", "stdout"));
        assert!(!norm.unordered("c", "stderr"));
        let e = b"x=1\ny=2\n";
        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
    }

    #[test]
    fn the_wildcard_definition_agrees_with_what_compare_does() {
        let norm = norm_with_tolerance(None);
        let expected = b"first\n...\nlast\n";
        let actual = b"first\nmiddle one\nmiddle two\nlast\n";
        // The definition says `compare` reads the `...` line, and it does: the lines in between
        // are not the same, and the text still matches.
        assert!(has_line_wildcard("first\n...\nlast\n"));
        assert!(reads_line_wildcards(false, false));
        assert!(compare(&norm, expected, actual, false, false).is_none());
        // Binary text and unordered lines are compared without it, and the definition says so.
        assert!(!reads_line_wildcards(true, false));
        assert!(compare(&norm, expected, actual, true, false).is_some());
        assert!(!reads_line_wildcards(false, true));
        assert!(compare(&norm, expected, actual, false, true).is_some());
        // Only a line that is exactly `...` is one; `[..]` and longer lines are not.
        assert!(!has_line_wildcard("a ...\n....\n [..]\n"));
        // A `\r` is part of the line since `lines` keeps it, so `...\r` is text, for both.
        assert!(!has_line_wildcard("a\r\n...\r\n"));
        assert!(
            compare(
                &norm,
                b"a\r\n...\r\nz\r\n",
                b"a\r\nb\r\nz\r\n",
                false,
                false
            )
            .is_some()
        );
    }

    #[test]
    fn timestamps_cover_javascript_date_strings() {
        let re = Regex::new(TIMESTAMP).unwrap();
        let line = "Generated on Sat Nov 21 2026 01:30:12 GMT+0300 (Türkiye Standard Time) - ok";
        assert_eq!(re.replace_all(line, "[..]"), "Generated on [..] - ok");
        assert_eq!(
            re.replace_all("Mon Jan 05 2026 09:00:00 GMT-0800", "[..]"),
            "[..]"
        );
        assert_eq!(re.replace_all("at 2026-11-16T10:00:00Z", "[..]"), "at [..]");
        assert_eq!(re.replace_all("Saturday 12", "[..]"), "Saturday 12");
    }

    #[test]
    fn noise_becomes_wildcards() {
        assert_eq!(
            merge_noise(
                "start\nnow: 2026-11-16 10:00:01\nend\n",
                "start\nnow: 2026-11-16 10:00:02\nend\n"
            ),
            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
        );
        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
        // Issue #680: two random ids that happen to share a separator must not keep it, or a replay
        // fails on an id without one.
        assert_eq!(
            merge_line("x-id: k2Pq_x9Lm4", "x-id: Zt7w_bR3nV"),
            "x-id: [..]"
        );
        assert_eq!(merge_line("abc_def", "abc_xyz"), "abc_[..]");
        assert_eq!(merge_line("k2Pq_x9Lm4", "Zt7w_bR3nV"), "[..]");
        let merged = merge_noise("x 1\n", "x 2\n");
        assert!(text_matches_exact(&merged, "x 3\n"));
    }

    #[test]
    fn normalizers_by_name() {
        let mut config = Config {
            schema: SCHEMA.to_string(),
            name: "app".to_string(),
            run: Vec::new(),
            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
            timeout_secs: 30,
            http: None,
            float_tolerance: None,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::new(),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        };
        let norm = Normalizers::new(&config).unwrap();
        assert_eq!(
            norm.apply(
                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
            ),
            "at [..] id [..] [..]"
        );
        assert_eq!(
            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
        );
        let paths = |names: &[&str]| names.iter().map(PathBuf::from).collect::<Vec<_>>();
        let recorded = paths(&["a.txt", "req-1.log", "req-2.log", "gone.txt"]);
        let written = paths(&["a.txt", "req-8.log", "req-9.log", "new.txt"]);
        assert_eq!(
            norm.pair_files(recorded.iter(), written.iter()),
            BTreeMap::from([
                (PathBuf::from("a.txt"), PathBuf::from("a.txt")),
                (PathBuf::from("req-1.log"), PathBuf::from("req-8.log")),
                (PathBuf::from("req-2.log"), PathBuf::from("req-9.log")),
            ])
        );
        // A case counts when a file it wrote is named by a normalized value, at any depth;
        // what it printed does not matter.
        let repo = temp_dir("normalized-names").unwrap();
        let dir = cases_dir(&repo);
        for (file, text) in [
            ("named.out/logs/req-7.log", "x"),
            ("plain.out/result.txt", "x"),
            ("plain.out/at 2026-11-16T10:00:00Z.txt", "x"),
            ("stdout-only.stdout", "req-9\n"),
        ] {
            let path = dir.join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
        let found = cases_with_normalized_file_names(&repo, &config).unwrap();
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(found, ["named", "plain"]);
        config.normalize.push("nope".into());
        assert!(Normalizers::new(&config).is_err());
    }

    #[test]
    fn record_refuses_a_normalizer_that_would_match_everywhere() {
        let refused = |spec: &str| custom_normalizer(spec).unwrap_err().to_string();
        for spec in ["id=", r"id=\d*"] {
            let e = refused(spec);
            assert!(e.contains("normalizer `id`"), "{e}");
            assert!(e.contains("match everywhere"), "{e}");
        }
        assert!(refused("=abc").contains("has no name"));
        assert!(refused("timestamps=x").contains("`timestamps` is a built-in normalizer"));
        assert_eq!(custom_normalizer(r"id=\d+").unwrap(), Some(("id", r"\d+")));
        assert_eq!(custom_normalizer("uuids").unwrap(), None);
        // The check runs before the app does, so nothing is written.
        let repo = temp_dir("normalize-empty-match").unwrap();
        let err = record(&RecordOptions {
            repo: &repo,
            run: &["no-such-program-rust-anything".to_string()],
            inputs: None,
            normalize: &["id=".into()],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        })
        .unwrap_err()
        .to_string();
        let wrote = repo.join("rust").exists();
        std::fs::remove_dir_all(&repo).unwrap();
        assert!(err.contains("matches the empty string"), "{err}");
        assert!(!wrote);
    }

    #[test]
    fn a_normalizer_across_lines_leaves_its_cases_to_replay() {
        assert!(spans_lines(
            r"Traceback \(most recent call last\):\n(?:  [^\n]*\n)*"
        ));
        assert!(spans_lines(r"[^x]+"));
        assert!(spans_lines(r"\s+"));
        assert!(!spans_lines(TIMESTAMP));
        assert!(!spans_lines(r"id-[0-9]+"));
        assert!(!spans_lines(r".*"));
        let repo = temp_dir("across-lines").unwrap();
        let dir = cases_dir(&repo);
        std::fs::create_dir_all(&dir).unwrap();
        for (file, text) in [
            ("crash.toml", "bin.name = \"tool\"\n"),
            ("crash.stderr", "[..]ValueError: bad\n"),
            ("noise.toml", "bin.name = \"tool\"\n"),
            ("noise.stdout", "took [..] ms\n"),
            ("plain.toml", "bin.name = \"tool\"\n"),
            ("plain.stdout", "42\n"),
            ("plain.stderr", ""),
            // Expected output inline in the case file, as a hand-written case may have it.
            (
                "inline.toml",
                "bin.name = \"tool\"\nstdout = \"[..]ValueError: bad\\n\"\n",
            ),
            // A written file the normalizer folded is compared by trycmd as well.
            ("report.toml", "bin.name = \"tool\"\n"),
            ("report.out/log.txt", "[..]done\n"),
        ] {
            let path = dir.join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
        let mut config = Config {
            schema: SCHEMA.to_string(),
            name: "app".to_string(),
            run: Vec::new(),
            normalize: vec!["timestamps".into()],
            normalizers: BTreeMap::from([("id".to_string(), r"id-[0-9]+".to_string())]),
            timeout_secs: 30,
            http: None,
            float_tolerance: None,
            float_files: BTreeMap::new(),
            unordered: BTreeMap::new(),
            across_lines: None,
            effects: None,
            fresh: Vec::new(),
            recorded: Vec::new(),
        };
        assert!(cases_normalized_across_lines(&repo, &config).is_empty());
        config.normalizers.insert(
            "traceback".into(),
            r"Traceback \(most recent call last\):\n(?:  [^\n]*\n)*".into(),
        );
        // A recording made before the list was kept: every case with a `[..]` is skipped.
        let old = cases_normalized_across_lines(&repo, &config);
        // A new one names the outputs a match crossed a line break in: `noise` stays in trycmd.
        config.recorded = ["crash", "noise", "plain", "report"]
            .map(String::from)
            .to_vec();
        config.across_lines = Some(BTreeMap::from([
            ("crash".to_string(), vec!["stderr".to_string()]),
            ("report".to_string(), vec!["file log.txt".to_string()]),
        ]));
        let listed = cases_normalized_across_lines(&repo, &config);
        std::fs::remove_dir_all(&repo).unwrap();
        assert_eq!(old, ["crash", "inline", "noise", "report"]);
        // `inline` was written by hand, so it keeps the scan.
        assert_eq!(listed, ["crash", "inline", "report"]);
    }

    #[test]
    fn a_match_that_holds_a_line_break_is_tracked_per_output() {
        let config = |normalizers: &[(&str, &str)]| Config {
            normalizers: normalizers
                .iter()
                .map(|(n, p)| (n.to_string(), p.to_string()))
                .collect(),
            normalize: vec!["timestamps".to_string()],
            ..Config::new("app")
        };
        let norm = Normalizers::new(&config(&[("id", "id=[^ ]+")])).unwrap();
        assert_eq!(
            norm.apply_tracked("id=abc done\n"),
            ("[..] done\n".into(), false)
        );
        assert_eq!(
            norm.apply_tracked("id=abc\nnext x\n"),
            ("[..] x\n".into(), true)
        );
        assert!(!norm.crosses_lines(b"id=a b\n", b"id=c d\n"));
        assert!(norm.crosses_lines(b"id=a b\n", b"id=c\nd e\n"));
        assert!(!norm.crosses_lines(&[0xff, b'\n'], b"2024-01-02T03:04:05Z\n"));
        let builtin = Normalizers::new(&config(&[])).unwrap();
        assert!(!builtin.crosses_lines(b"at 2024-01-02T03:04:05Z\n", b"x\n"));
    }

    #[test]
    fn a_written_file_that_is_binary_in_one_run_is_not_tracked_across_lines() {
        let norm = Normalizers::new(&Config {
            normalizers: [("id".to_string(), "id=[^ ]+".to_string())]
                .into_iter()
                .collect(),
            ..Config::new("app")
        })
        .unwrap();
        let run = |file: &[u8]| Run {
            stdout: Vec::new(),
            stderr: Vec::new(),
            status: Status::Code(0),
            files: [(PathBuf::from("out.txt"), file.to_vec())]
                .into_iter()
                .collect(),
            removed: Vec::new(),
            fallback: None,
            effects: None,
        };
        let case = Case::new(Vec::new());
        let text = run(b"id=abc\nnext x\n");
        let other = run(b"id=def\nnext x\n");
        let binary = run(&[0xff, b'\n']);
        assert_eq!(settle(&norm, &case, &text, &other).across, ["file out.txt"]);
        assert!(settle(&norm, &case, &text, &binary).across.is_empty());
        assert!(settle(&norm, &case, &binary, &text).across.is_empty());
    }

    #[test]
    fn a_partial_recording_keeps_the_list_of_the_cases_it_kept() {
        let spanning = [("id".to_string(), "id=[^ ]+".to_string())];
        let list = |names: &[&str]| {
            Some(
                names
                    .iter()
                    .map(|n| (n.to_string(), vec!["stdout".to_string()]))
                    .collect::<BTreeMap<_, _>>(),
            )
        };
        let previous = |across: Option<BTreeMap<String, Vec<String>>>| Config {
            normalizers: spanning.iter().cloned().collect(),
            recorded: vec!["old".to_string(), "gone".to_string()],
            across_lines: across,
            ..Config::new("app")
        };
        let mut outcome = RecordOutcome {
            trycmd_test: None,
            dir: PathBuf::new(),
            run: Vec::new(),
            cases: 1,
            examples: 0,
            inputs: 0,
            duplicate_inputs: Vec::new(),
            no_args: 0,
            traps: 0,
            traps_dropped: 0,
            noisy: Vec::new(),
            noise: Vec::new(),
            unstable: Vec::new(),
            same_failure: None,
            timed_out: Vec::new(),
            recorded: vec!["new".to_string()],
            skipped_examples: Vec::new(),
            stale: Vec::new(),
            kept: Vec::new(),
        };
        let found = || BTreeMap::from([("new".to_string(), vec!["stderr".to_string()])]);
        let keep = |before: &Config, recorded: &[&str]| {
            let mut now = Config {
                recorded: recorded.iter().map(|n| n.to_string()).collect(),
                ..previous(None)
            };
            keep_across_lines(&mut now, Some(before), &outcome, found());
            now.across_lines
        };

        let mut expected = list(&["old"]).unwrap();
        expected.insert("new".to_string(), vec!["stderr".to_string()]);
        // `old` came from the earlier recording and answered before: its entry stays.
        assert_eq!(
            keep(&previous(list(&["old"])), &["new", "old"]),
            Some(expected)
        );
        // `old` came from a recording with no list: nothing says what it holds.
        assert_eq!(keep(&previous(None), &["new", "old"]), None);
        // A full recording needs nothing from the old list.
        assert_eq!(keep(&previous(None), &["new"]), Some(found()));
        outcome.recorded.clear();
        // Without a normalizer that spans lines the list is not kept.
        let mut plain = Config::new("app");
        keep_across_lines(&mut plain, None, &outcome, found());
        assert_eq!(plain.across_lines, None);
    }

    #[test]
    fn examples_become_cases() {
        let repo = temp_dir("examples").unwrap();
        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
        std::fs::write(
            repo.join("README.md"),
            "# tool\n\n```console\n$ tool count in.txt\n3\n$ echo \"a b\" | tool words\n$ git status\n```\n\n```sh\nLANG=C tool upper 'x y'\ntool sort < in.txt\ntool a | grep b\n```\n",
        )
        .unwrap();
        let names = vec!["tool".to_string()];
        let cases = find_examples(&repo, &names);
        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
        assert_eq!(
            args,
            [
                vec!["count", "in.txt"],
                vec!["words"],
                vec!["upper", "x y"],
                vec!["sort"],
            ]
        );
        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
        assert_eq!(cases[2].env["LANG"], "C");
        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn examples_continued_with_a_backslash_are_joined() {
        let repo = temp_dir("continued-examples").unwrap();
        std::fs::write(
            repo.join("README.md"),
            "```console\n$ tool upper \\\n    --loud \\\n    'x y'\n$ tool path C:\\\\\n$ tool count in.txt\n$ tool upper --mode=lo\\\nud\n$ tool echo a\\ \n$ tool count b.txt\n```\n",
        )
        .unwrap();
        std::fs::write(
            repo.join("demo.sh"),
            "tool sort \\\n  --reverse\n# tool hidden \\\ntool count c.txt\n",
        )
        .unwrap();
        let names = vec!["tool".to_string()];
        let args: Vec<Vec<String>> = find_examples(&repo, &names)
            .iter()
            .map(|c| c.args.clone())
            .collect();
        std::fs::remove_dir_all(&repo).unwrap();
        // Not continuations: a doubled backslash (a literal one), a backslash followed by a space,
        // and a backslash at the end of a comment. Joining adds no space of its own (`--mode=loud`).
        assert_eq!(
            args,
            [
                vec!["upper", "--loud", "x y"],
                vec!["path", "C:\\"],
                vec!["count", "in.txt"],
                vec!["upper", "--mode=loud"],
                vec!["echo", "a "],
                vec!["count", "b.txt"],
                vec!["sort", "--reverse"],
                vec!["count", "c.txt"],
            ]
        );
    }

    #[test]
    fn traps_keep_the_shape_of_the_case() {
        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
        base.stdin = Some(b"{\"a\":1}".to_vec());
        let (traps, dropped) = trap_cases(&[base]);
        assert_eq!(dropped, 0);
        assert!(traps.iter().all(|c| c.args[0] == "div"));
        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
        assert!(
            traps
                .iter()
                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
        );
        let (text, dropped_text) = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
        assert_eq!(dropped_text, 0);
        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
    }

    #[test]
    fn traps_spread_round_robin_deduplicate_before_truncating_and_count_dropped() {
        // 40 distinct commands, each with an int and a string arg -> > 300 unique traps.
        let mut bases: Vec<Case> = (0..40)
            .map(|i| Case::new(vec![format!("cmd{i:02}"), "7".into(), "hi".into()]))
            .collect();
        let (unique_traps, unique_dropped) = trap_cases(&bases);
        // Adding a duplicate base whose traps all collide must not change the kept traps or
        // inflate `dropped`.
        bases.push(bases[0].clone());
        let (traps, dropped) = trap_cases(&bases);

        assert_eq!(unique_traps.len(), MAX_TRAPS);
        assert!(unique_dropped > 0);
        assert_eq!(traps.len(), MAX_TRAPS);
        assert_eq!(dropped, unique_dropped);

        // Every single one of the 40 commands gets traps (not just the first few).
        for i in 0..40 {
            let cmd = format!("cmd{i:02}");
            let count = unique_traps.iter().filter(|c| c.args[0] == cmd).count();
            assert!(
                count >= 7,
                "{cmd} only got {count} traps out of {MAX_TRAPS}"
            );
        }

        // Many bases with colliding traps (> 300 raw traps, < 300 unique) must deduplicate
        // before truncating so nothing is dropped and unique traps from later bases survive.
        let mut dup_bases: Vec<Case> = (1..=40)
            .map(|i| Case::new(vec!["dup".into(), i.to_string()]))
            .collect();
        dup_bases.push(Case::new(vec!["tail".into(), "hello".into()]));
        let (dup_traps, dup_dropped) = trap_cases(&dup_bases);
        assert_eq!(dup_dropped, 0);
        assert!(dup_traps.iter().any(|c| c.args[0] == "tail"));
        let keys: BTreeSet<_> = dup_traps.iter().map(Case::key).collect();
        assert_eq!(keys.len(), dup_traps.len());
    }

    #[cfg(unix)]
    #[test]
    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
        let repo = temp_dir("case-name-collisions").unwrap();
        let inputs = repo.join("cases.jsonl");
        std::fs::write(
            &inputs,
            concat!(
                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
            ),
        )
        .unwrap();
        let recorded = record(&RecordOptions {
            repo: &repo,
            run: &["/bin/echo".into()],
            inputs: Some(&inputs),
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: None,
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        })
        .unwrap();
        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
        assert_eq!(recorded.cases, 3);
        assert_eq!(read("x.stdout"), "one\n");
        assert_eq!(read("x-3.stdout"), "two\n");
        assert_eq!(read("x-4.stdout"), "three\n");
        std::fs::remove_dir_all(repo).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn a_new_run_command_renames_an_inferred_name_but_keeps_a_given_one() {
        let repo = temp_dir("rename-on-new-run").unwrap();
        std::fs::write(repo.join("one.sh"), "echo one\n").unwrap();
        std::fs::write(repo.join("two.sh"), "echo two\n").unwrap();
        let rec = |script: &str, name: Option<&str>| {
            let run = ["/bin/sh".to_string(), script.to_string()];
            record(&RecordOptions {
                repo: &repo,
                run: &run,
                inputs: None,
                normalize: &[],
                name,
                traps: false,
                timeout_secs: None,
                http: None,
                server_args: None,
                fresh: None,
                pace_ms: None,
                port: None,
                float_tolerance: None,
                float_files: &[],
                effects: None,
                ready_secs: None,
                ready_request: None,
                sandbox: false,
            })
            .unwrap();
            Config::load(&repo).unwrap().unwrap().name
        };
        assert_eq!(rec("one.sh", None), "one");
        assert_eq!(rec("two.sh", None), "two");
        assert_eq!(rec("two.sh", Some("mytool")), "mytool");
        assert_eq!(rec("one.sh", None), "mytool");
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn names_come_from_the_run_command_and_manifests() {
        let repo = temp_dir("names").unwrap();
        std::fs::create_dir_all(repo.join("out")).unwrap();
        std::fs::write(
            repo.join("package.json"),
            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
        )
        .unwrap();
        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
        std::fs::remove_dir_all(&repo).unwrap();
    }

    #[test]
    fn python_program_names_are_case_insensitive() {
        assert!(is_python_program("PYTHON"));
        assert!(is_python_program("/tools/Python3.exe"));
        assert!(is_python_program("Py.cmd"));
        assert!(!is_python_program("pythonw.exe"));
    }

    #[test]
    fn shell_words() {
        assert_eq!(
            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
        );
        assert!(shell_split("a | b").is_err());
        assert!(shell_tokens("echo $(date)").is_none());
        assert!(shell_tokens("echo `date`").is_none());
        assert_eq!(
            shell_split(r"echo \$(date) \`date\`").unwrap(),
            ["echo", "$(date)", "`date`"]
        );
        #[cfg(windows)]
        assert_eq!(
            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
            [r"C:\tools\rust-anything\app.exe", "--flag"]
        );
        #[cfg(windows)]
        assert_eq!(
            shell_split(r"run C:\$cache\tool.exe").unwrap(),
            ["run", r"C:\$cache\tool.exe"]
        );
        #[cfg(windows)]
        assert_eq!(
            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
            [r"\\server\share\tool.exe", "--flag"]
        );
        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
    }

    #[test]
    fn record_and_replay_reject_zero_timeout_and_leave_cases_untouched() {
        let repo = temp_dir("zero-timeout").unwrap();
        let dir = cases_dir(&repo);
        std::fs::create_dir_all(&dir).unwrap();
        let sentinel_cfg = format!(
            r#"{{"schema":"{SCHEMA}","name":"app","run":["echo","ok"],"timeout_secs":30,"recorded":["no-args"]}}"#
        );
        let cfg_path = dir.join(CONFIG_FILE);
        let case_path = dir.join("no-args.toml");
        std::fs::write(&cfg_path, &sentinel_cfg).unwrap();
        std::fs::write(&case_path, "stdout = \"ok\\n\"\n").unwrap();

        let rec_err = record(&RecordOptions {
            repo: &repo,
            run: &["definitely-not-run".to_string()],
            inputs: None,
            normalize: &[],
            name: None,
            traps: false,
            timeout_secs: Some(0),
            http: None,
            server_args: None,
            fresh: None,
            pace_ms: None,
            port: None,
            float_tolerance: None,
            float_files: &[],
            effects: None,
            ready_secs: None,
            ready_request: None,
            sandbox: false,
        })
        .unwrap_err();
        let rec_msg = format!("{rec_err:#}");
        assert!(
            rec_msg.contains("--timeout") && rec_msg.contains("1 second"),
            "{rec_msg}"
        );

        let rep_err = replay(&ReplayOptions {
            repo: &repo,
            build: None,
            timeout_secs: Some(0),
            port: None,
            case: None,
        })
        .unwrap_err();
        let rep_msg = format!("{rep_err:#}");
        assert!(
            rep_msg.contains("--timeout") && rep_msg.contains("1 second"),
            "{rep_msg}"
        );

        assert_eq!(std::fs::read_to_string(&cfg_path).unwrap(), sentinel_cfg);
        assert_eq!(
            std::fs::read_to_string(&case_path).unwrap(),
            "stdout = \"ok\\n\"\n"
        );

        let zero_cfg = sentinel_cfg.replace(r#""timeout_secs":30"#, r#""timeout_secs":0"#);
        std::fs::write(&cfg_path, &zero_cfg).unwrap();
        let saved_zero_err = replay(&ReplayOptions {
            repo: &repo,
            build: None,
            timeout_secs: None,
            port: None,
            case: None,
        })
        .unwrap_err();
        let saved_msg = format!("{saved_zero_err:#}");
        assert!(
            saved_msg.contains("--timeout") && saved_msg.contains("1 second"),
            "{saved_msg}"
        );

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

    fn f64s(values: &[f64]) -> Vec<u8> {
        values.iter().flat_map(|v| v.to_le_bytes()).collect()
    }

    #[test]
    fn float_width_knows_f32le_and_f64le() {
        assert_eq!(float_width("f32le").unwrap(), 4);
        assert_eq!(float_width("f64le").unwrap(), 8);
        let err = float_width("f16le").unwrap_err().to_string();
        assert!(err.contains("`f16le`"), "{err}");
        assert!(err.contains("f32le") && err.contains("f64le"), "{err}");
    }

    #[test]
    fn compare_floats_matches_equal_values_and_nan() {
        let same = f64s(&[1.0, -2.5, 1e300]);
        assert_eq!(compare_floats(&same, &same, 8, None), None);
        let nan = f64s(&[f64::NAN, 3.0]);
        assert_eq!(compare_floats(&nan, &nan, 8, None), None);
    }

    #[test]
    fn compare_floats_names_the_first_difference_unless_the_tolerance_covers_it() {
        let expected = f64s(&[1.0, 2.0, 3.0]);
        let actual = f64s(&[1.0, 2.5, 3.0]);
        let line = compare_floats(&expected, &actual, 8, None).unwrap();
        assert!(line.starts_with("1 of 3 values differ"), "{line}");
        assert!(
            line.contains("first at index 1: 2 expected, 2.5 got"),
            "{line}"
        );
        assert!(line.contains("max abs diff 5e-1"), "{line}");
        assert!(line.contains("max rel diff 2e-1"), "{line}");
        assert_eq!(compare_floats(&expected, &actual, 8, Some(0.3)), None);
        assert!(compare_floats(&expected, &actual, 8, Some(0.1)).is_some());
    }

    #[test]
    fn compare_floats_reads_f32le() {
        let f32s = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
        let expected = f32s(&[1.5, -0.25]);
        assert_eq!(compare_floats(&expected, &expected, 4, None), None);
        let line = compare_floats(&expected, &f32s(&[1.5, 0.25]), 4, None).unwrap();
        assert!(line.starts_with("1 of 2 values differ"), "{line}");
        assert!(
            line.contains("first at index 1: -0.25 expected, 0.25 got"),
            "{line}"
        );
    }

    #[test]
    fn compare_floats_reports_a_length_mismatch() {
        let two = f64s(&[1.0, 2.0]);
        assert_eq!(
            compare_floats(&two, &two[..8], 8, None).as_deref(),
            Some("2 values expected, 8 bytes got (8 bytes per value)\n")
        );
        // A partial value in the expected file is a mismatch too, even against itself.
        assert!(compare_floats(&two[..12], &two[..12], 8, None).is_some());
    }
}