Skip to main content

rust_anything/
app.rs

1//! App-level record and replay for CLIs, in any language: the program is a black box.
2//!
3//! `record` runs the original on cases (the app's own examples, an inputs file, semantic traps)
4//! twice, marks what differs between the two runs as noise, and writes each case as trycmd files
5//! in `rust/app-cases/`. `replay` runs any build against those files and reports what differs.
6
7use crate::walk::Canonical;
8use std::collections::{BTreeMap, BTreeSet, HashMap};
9use std::io::{Read, Write};
10use std::path::{Component, Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Mutex;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::time::{Duration, Instant};
15
16use anyhow::{Context, Result, bail, ensure};
17use regex::Regex;
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use toml_edit::{DocumentMut, Item, Table, value};
21
22pub const CASES_DIR: &str = "rust/app-cases";
23pub const CONFIG_FILE: &str = "rust-anything.json";
24pub const REPORT_FILE: &str = "replay-report.md";
25pub const FALLBACK_ENV: &str = "RUST_ANYTHING_FALLBACK_LOG";
26pub const BUILTIN_NORMALIZERS: [&str; 3] = ["timestamps", "uuids", "key-order"];
27pub(crate) const SCHEMA: &str = "rust-anything/app-cases@1";
28pub(crate) const MAX_TRAPS: usize = 300;
29pub(crate) const FRESH_DIR: &str = "files";
30const REMOVED_EXT: &str = "removed";
31const MAX_INPUT_FILE: u64 = 1 << 20;
32const 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";
33const UUID: &str =
34    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";
35
36pub(crate) const INT_TRAPS: [&str; 8] = [
37    "-7",
38    "0",
39    "-1",
40    "2147483648",
41    "9007199254740993",
42    "9223372036854775807",
43    "-9223372036854775808",
44    "18446744073709551616",
45];
46pub(crate) const FLOAT_TRAPS: [&str; 7] = [
47    "-0.0",
48    "0.1",
49    "0.30000000000000004",
50    "1e21",
51    "1e-7",
52    "5e-324",
53    "1.7976931348623157e308",
54];
55pub(crate) const STRING_TRAPS: [&str; 10] = [
56    "héllo wörld",
57    "👍🏽 thumbs",
58    "日本語",
59    "",
60    "e\u{301}",
61    "İstanbul",
62    "straße",
63    "ılık ırmak",
64    "👨\u{200D}👩\u{200D}👧 family",
65    "a\u{00A0}b",
66];
67pub(crate) const STDIN_TRAPS: [&str; 4] = [
68    "naïve café 👍🏽\nsecond line\n",
69    "",
70    "日本語 テキスト\r\nline two\r\n",
71    "  spaced   out  \n\n",
72];
73pub(crate) const JSON_TRAPS: [&str; 2] = [
74    r#"{"zebra":1,"apple":2,"10":3,"2":4,"é":5,"Apple":6}"#,
75    r#"{"n":9007199254740993,"f":1e21,"t":0.1,"neg":-7}"#,
76];
77const NOT_APP_NAMES: [&str; 29] = [
78    "node", "nodejs", "python", "python3", "py", "ruby", "java", "go", "deno", "bun", "tsx",
79    "ts-node", "sh", "bash", "zsh", "cargo", "npx", "npm", "pnpm", "yarn", "uv", "poetry",
80    "bundle", "run", "exec", "env", "sudo", "php", "dotnet",
81];
82
83/// `rust/app-cases/rust-anything.json`: how to run the original, and the normalizers.
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct Config {
86    pub schema: String,
87    pub name: String,
88    pub run: Vec<String>,
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub normalize: Vec<String>,
91    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
92    pub normalizers: BTreeMap<String, String>,
93    #[serde(default = "default_timeout")]
94    pub timeout_secs: u64,
95    /// Set when the app is a server: cases are requests, in `http/`.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub http: Option<crate::http::HttpConfig>,
98    /// Numbers in the output match within this relative tolerance.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub float_tolerance: Option<f64>,
101    /// Written files holding raw floats, by path: compared value by value (`f32le`, `f64le`).
102    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
103    pub float_files: BTreeMap<String, String>,
104    /// Outputs whose line order the original's own runs disagreed on, by case: their lines must
105    /// match in any order.
106    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
107    pub unordered: BTreeMap<String, Vec<String>>,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub effects: Option<crate::effects::EffectsConfig>,
110    /// CLIs: repository paths copied (from the snapshot in `files/`) into the working directory
111    /// before every case; a path ending in `/` gives its contents.
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub fresh: Vec<String>,
114    /// The cases the last `app record` wrote, so the next one can remove those it no longer
115    /// writes without touching cases written by hand.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    pub recorded: Vec<String>,
118}
119
120pub(crate) fn default_timeout() -> u64 {
121    30
122}
123
124pub(crate) fn check_timeout(timeout_secs: Option<u64>) -> Result<()> {
125    ensure!(
126        timeout_secs != Some(0),
127        "--timeout must be at least 1 second"
128    );
129    Ok(())
130}
131
132impl Config {
133    pub fn load(repo: &Path) -> Result<Option<Config>> {
134        let path = cases_dir(repo).join(CONFIG_FILE);
135        if !path.exists() {
136            return Ok(None);
137        }
138        let text = std::fs::read_to_string(&path)
139            .with_context(|| format!("reading {}", path.display()))?;
140        Ok(Some(
141            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
142        ))
143    }
144}
145
146pub fn cases_dir(repo: &Path) -> PathBuf {
147    repo.join(CASES_DIR)
148}
149
150/// One line of an `--inputs` file.
151#[derive(Debug, Clone, Default, Deserialize)]
152#[serde(deny_unknown_fields)]
153pub struct Input {
154    #[serde(default)]
155    pub name: Option<String>,
156    #[serde(default)]
157    pub args: Vec<String>,
158    #[serde(default)]
159    pub stdin: Option<String>,
160    #[serde(default)]
161    pub env: BTreeMap<String, String>,
162    #[serde(default)]
163    pub files: BTreeMap<String, String>,
164    #[serde(default)]
165    pub remove: Vec<String>,
166}
167
168#[derive(Debug, Clone)]
169struct Case {
170    args: Vec<String>,
171    stdin: Option<Vec<u8>>,
172    env: BTreeMap<String, String>,
173    env_remove: Vec<String>,
174    inherit_env: bool,
175    files: BTreeMap<PathBuf, Vec<u8>>,
176    remove: Vec<PathBuf>,
177}
178
179impl Case {
180    fn new(args: Vec<String>) -> Self {
181        Case {
182            args,
183            stdin: None,
184            env: BTreeMap::new(),
185            env_remove: Vec::new(),
186            inherit_env: true,
187            files: BTreeMap::new(),
188            remove: Vec::new(),
189        }
190    }
191
192    fn key(&self) -> String {
193        serde_json::json!([self.args, self.stdin, self.env, self.files, self.remove]).to_string()
194    }
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198enum Status {
199    Code(i32),
200    Killed,
201    Timeout,
202}
203
204impl std::fmt::Display for Status {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        match self {
207            Status::Code(c) => write!(f, "exit code {c}"),
208            Status::Killed => write!(f, "killed by a signal"),
209            Status::Timeout => write!(f, "timed out"),
210        }
211    }
212}
213
214struct Run {
215    stdout: Vec<u8>,
216    stderr: Vec<u8>,
217    status: Status,
218    files: BTreeMap<PathBuf, Vec<u8>>,
219    removed: Vec<PathBuf>,
220    fallback: Option<bool>,
221    effects: Option<Vec<u8>>,
222}
223
224impl Run {
225    fn written(&self, case: &Case) -> BTreeMap<PathBuf, Vec<u8>> {
226        self.files
227            .iter()
228            .filter(|(path, bytes)| case.files.get(*path) != Some(*bytes))
229            .map(|(p, b)| (p.clone(), b.clone()))
230            .collect()
231    }
232}
233
234pub(crate) struct Normalizers {
235    patterns: Vec<Regex>,
236    key_order: bool,
237    float_tolerance: Option<f64>,
238    float_files: BTreeMap<PathBuf, usize>,
239    unordered: BTreeMap<String, Vec<String>>,
240}
241
242impl Normalizers {
243    pub(crate) fn new(config: &Config) -> Result<Self> {
244        let mut sources: Vec<(&str, &str)> = Vec::new();
245        let mut key_order = false;
246        for name in &config.normalize {
247            match name.as_str() {
248                "timestamps" => sources.push((name, TIMESTAMP)),
249                "uuids" => sources.push((name, UUID)),
250                "key-order" => key_order = true,
251                other => bail!(
252                    "unknown normalizer `{other}`: use {} or define it as `name=regex`",
253                    BUILTIN_NORMALIZERS.join(", ")
254                ),
255            }
256        }
257        sources.extend(
258            config
259                .normalizers
260                .iter()
261                .map(|(n, p)| (n.as_str(), p.as_str())),
262        );
263        let patterns = sources
264            .iter()
265            .map(|(name, pattern)| {
266                Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))
267            })
268            .collect::<Result<Vec<_>>>()?;
269        let float_tolerance = config
270            .float_tolerance
271            .map(crate::tolerance::check)
272            .transpose()?;
273        let float_files = config
274            .float_files
275            .iter()
276            .map(|(path, format)| Ok((PathBuf::from(path), float_width(format)?)))
277            .collect::<Result<_>>()?;
278        Ok(Normalizers {
279            patterns,
280            key_order,
281            float_tolerance,
282            float_files,
283            unordered: config.unordered.clone(),
284        })
285    }
286
287    /// Whether the original's runs disagreed on the line order of this case's `field`.
288    pub(crate) fn unordered(&self, case: &str, field: &str) -> bool {
289        self.unordered
290            .get(case)
291            .is_some_and(|fields| fields.iter().any(|f| f == field))
292    }
293
294    pub(crate) fn apply(&self, text: &str) -> String {
295        let mut out = text.to_string();
296        for p in &self.patterns {
297            out = p.replace_all(&out, "[..]").into_owned();
298        }
299        out
300    }
301
302    fn canonical(&self, text: &str) -> String {
303        if self.key_order {
304            sort_json_text(text)
305        } else {
306            text.to_string()
307        }
308    }
309}
310
311fn sort_value(v: Value) -> Value {
312    match v {
313        Value::Object(map) => {
314            let sorted: BTreeMap<String, Value> =
315                map.into_iter().map(|(k, v)| (k, sort_value(v))).collect();
316            Value::Object(sorted.into_iter().collect())
317        }
318        Value::Array(items) => Value::Array(items.into_iter().map(sort_value).collect()),
319        other => other,
320    }
321}
322
323fn sort_json_text(text: &str) -> String {
324    let trimmed = text.trim();
325    if trimmed.starts_with(['{', '['])
326        && let Ok(v) = serde_json::from_str::<Value>(trimmed)
327    {
328        return serde_json::to_string_pretty(&sort_value(v)).unwrap_or_default() + "\n";
329    }
330    text.split('\n')
331        .map(|line| {
332            let t = line.trim();
333            if t.starts_with(['{', '['])
334                && let Ok(v) = serde_json::from_str::<Value>(t)
335            {
336                return sort_value(v).to_string();
337            }
338            line.to_string()
339        })
340        .collect::<Vec<_>>()
341        .join("\n")
342}
343
344pub(crate) fn temp_dir(tag: &str) -> Result<PathBuf> {
345    static NEXT: AtomicUsize = AtomicUsize::new(0);
346    let dir = std::env::temp_dir().join(format!(
347        "rust-anything-app-{tag}-{}-{}",
348        std::process::id(),
349        NEXT.fetch_add(1, Ordering::SeqCst)
350    ));
351    let _ = std::fs::remove_dir_all(&dir);
352    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
353    Ok(dir)
354}
355
356pub(crate) fn resolve_word(repo: &Path, word: &str) -> String {
357    if word.starts_with('-') {
358        return word.to_string();
359    }
360    let path = repo.join(word);
361    let looks_like_path = word.contains('/') || word.contains('\\') || path.is_file();
362    if looks_like_path && path.exists() {
363        return path
364            .canonical()
365            .unwrap_or(path)
366            .to_string_lossy()
367            .into_owned();
368    }
369    word.to_string()
370}
371
372#[cfg(any(windows, test))]
373fn is_python_program(program: &str) -> bool {
374    Path::new(program)
375        .file_stem()
376        .and_then(|name| name.to_str())
377        .is_some_and(|name| {
378            ["python", "python3", "py"]
379                .iter()
380                .any(|candidate| name.eq_ignore_ascii_case(candidate))
381        })
382}
383
384fn run_case(
385    command: &[String],
386    repo: &Path,
387    case: &Case,
388    timeout: Duration,
389    effects: Option<&crate::effects::EffectsConfig>,
390    base: Option<&Path>,
391) -> Result<Run> {
392    let sandbox = temp_dir("run")?;
393    let result = run_in(command, repo, case, timeout, &sandbox, effects, base);
394    let _ = std::fs::remove_dir_all(&sandbox);
395    result
396}
397
398fn run_in(
399    command: &[String],
400    repo: &Path,
401    case: &Case,
402    timeout: Duration,
403    sandbox: &Path,
404    effects: Option<&crate::effects::EffectsConfig>,
405    base: Option<&Path>,
406) -> Result<Run> {
407    let work = sandbox.join("cwd");
408    std::fs::create_dir_all(&work)?;
409    if let Some(base) = base {
410        crate::http::copy_tree(base, &work)?;
411    }
412    for path in &case.remove {
413        let target = work.join(path);
414        if target.is_dir() {
415            std::fs::remove_dir_all(&target)?;
416        } else if target.exists() {
417            std::fs::remove_file(&target)?;
418        }
419    }
420    for (path, bytes) in &case.files {
421        let target = work.join(path);
422        if let Some(parent) = target.parent() {
423            std::fs::create_dir_all(parent)?;
424        }
425        std::fs::write(&target, bytes)?;
426    }
427    // The database lives where the case runs, so reset it there, before taking the snapshot that
428    // tells the case's own writes apart.
429    let sinks = effects
430        .map(|config| -> Result<_> {
431            let sinks = crate::effects::Sinks::start(config)?;
432            sinks.reset(&work, repo)?;
433            Ok(sinks)
434        })
435        .transpose()?;
436    let before: BTreeMap<PathBuf, FileStamp> = walk_files(&work)
437        .into_iter()
438        .filter_map(|path| {
439            let stamp = FileStamp::of(&path)?;
440            Some((path.strip_prefix(&work).ok()?.to_path_buf(), stamp))
441        })
442        .collect();
443    let log = sandbox.join("fallback.log");
444    let (program, rest) = command.split_first().context("empty command")?;
445    let mut cmd = Command::new(resolve_word(repo, program));
446    cmd.args(rest.iter().map(|w| resolve_word(repo, w)))
447        .args(&case.args)
448        .current_dir(&work)
449        .stdin(Stdio::piped())
450        .stdout(Stdio::piped())
451        .stderr(Stdio::piped());
452    if !case.inherit_env {
453        cmd.env_clear();
454    }
455    #[cfg(windows)]
456    if is_python_program(program)
457        && (!case.inherit_env || std::env::var_os("PYTHONIOENCODING").is_none())
458    {
459        // Python otherwise inherits the legacy Windows console code page even though its stdio
460        // is piped. UTF-8 keeps generated Unicode traps recordable; a case can still override it.
461        cmd.env("PYTHONIOENCODING", "utf-8");
462    }
463    for key in &case.env_remove {
464        cmd.env_remove(key);
465    }
466    if let Some(sinks) = &sinks {
467        cmd.envs(sinks.env());
468    }
469    cmd.envs(&case.env).env(FALLBACK_ENV, &log);
470    #[cfg(unix)]
471    {
472        use std::os::unix::process::CommandExt as _;
473        cmd.process_group(0);
474    }
475    let mut child = cmd
476        .spawn()
477        .with_context(|| format!("running `{}`", command.join(" ")))?;
478    let stdin = child.stdin.take();
479    let input = case.stdin.clone().unwrap_or_default();
480    let writer = std::thread::spawn(move || {
481        if let Some(mut pipe) = stdin {
482            let _ = pipe.write_all(&input);
483        }
484    });
485    let mut out_pipe = child.stdout.take().context("no stdout pipe")?;
486    let mut err_pipe = child.stderr.take().context("no stderr pipe")?;
487    let out_reader = std::thread::spawn(move || {
488        let mut buf = Vec::new();
489        let _ = out_pipe.read_to_end(&mut buf);
490        buf
491    });
492    let err_reader = std::thread::spawn(move || {
493        let mut buf = Vec::new();
494        let _ = err_pipe.read_to_end(&mut buf);
495        buf
496    });
497    let start = Instant::now();
498    let status = loop {
499        if let Some(s) = child.try_wait()? {
500            #[cfg(unix)]
501            let pipes_done =
502                writer.is_finished() && out_reader.is_finished() && err_reader.is_finished();
503            #[cfg(not(unix))]
504            let pipes_done = true;
505            if pipes_done {
506                break s.code().map_or(Status::Killed, Status::Code);
507            }
508        }
509        if start.elapsed() > timeout {
510            #[cfg(unix)]
511            {
512                let _ = Command::new("/bin/kill")
513                    .args(["-KILL", "--", &format!("-{}", child.id())])
514                    .stderr(Stdio::null())
515                    .status();
516            }
517            let _ = child.kill();
518            let _ = child.wait();
519            break Status::Timeout;
520        }
521        std::thread::sleep(Duration::from_millis(2));
522    };
523    let _ = writer.join();
524    let stdout = out_reader.join().unwrap_or_default();
525    let stderr = err_reader.join().unwrap_or_default();
526
527    let mut cwd_forms = vec![work.to_string_lossy().into_owned()];
528    if let Ok(real) = work.canonical() {
529        cwd_forms.insert(0, real.to_string_lossy().into_owned());
530    }
531    let redact = |bytes: Vec<u8>| -> Vec<u8> {
532        match String::from_utf8(bytes) {
533            Ok(mut text) => {
534                for form in &cwd_forms {
535                    text = text.replace(form.as_str(), "[CWD]");
536                }
537                text.into_bytes()
538            }
539            Err(e) => e.into_bytes(),
540        }
541    };
542    let mut files = BTreeMap::new();
543    let mut present = BTreeSet::new();
544    for path in walk_files(&work) {
545        let rel = path.strip_prefix(&work).unwrap_or(&path).to_path_buf();
546        present.insert(rel.clone());
547        let stamp = before.get(&rel);
548        if stamp.is_some() && stamp == FileStamp::of(&path).as_ref() {
549            continue;
550        }
551        let bytes = std::fs::read(&path).unwrap_or_default();
552        if stamp.is_some()
553            && !case.files.contains_key(&rel)
554            && let Some(base) = base
555            && std::fs::read(base.join(&rel)).is_ok_and(|b| b == bytes)
556        {
557            continue;
558        }
559        files.insert(rel, redact(bytes));
560    }
561    let removed = before
562        .keys()
563        .filter(|rel| !present.contains(*rel))
564        .cloned()
565        .collect();
566    let fallback = std::fs::metadata(&log).ok().map(|m| m.len() > 0);
567    let effects = sinks.map(|s| redact(s.take(&work, repo)));
568    Ok(Run {
569        stdout: redact(stdout),
570        stderr: redact(stderr),
571        status,
572        files,
573        removed,
574        fallback,
575        effects,
576    })
577}
578
579#[derive(PartialEq, Eq)]
580struct FileStamp {
581    len: u64,
582    modified: Option<std::time::SystemTime>,
583}
584
585impl FileStamp {
586    fn of(path: &Path) -> Option<Self> {
587        let meta = std::fs::metadata(path).ok()?;
588        Some(FileStamp {
589            len: meta.len(),
590            modified: meta.modified().ok(),
591        })
592    }
593}
594
595fn walk_files(root: &Path) -> Vec<PathBuf> {
596    let mut out = Vec::new();
597    let mut stack = vec![root.to_path_buf()];
598    while let Some(dir) = stack.pop() {
599        let Ok(entries) = std::fs::read_dir(&dir) else {
600            continue;
601        };
602        for entry in entries.flatten() {
603            let Ok(kind) = entry.file_type() else {
604                continue;
605            };
606            if kind.is_dir() {
607                stack.push(entry.path());
608            } else if kind.is_file() {
609                out.push(entry.path());
610            }
611        }
612    }
613    out.sort();
614    out
615}
616
617fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
618    let threads = std::thread::available_parallelism()
619        .map_or(4, |n| n.get())
620        .clamp(1, 8);
621    let next = AtomicUsize::new(0);
622    let results: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
623    std::thread::scope(|s| {
624        for _ in 0..threads {
625            s.spawn(|| {
626                loop {
627                    let i = next.fetch_add(1, Ordering::SeqCst);
628                    let Some(item) = items.get(i) else { break };
629                    let r = f(item);
630                    if let Ok(mut slot) = results[i].lock() {
631                        *slot = Some(r);
632                    }
633                }
634            });
635        }
636    });
637    results
638        .into_iter()
639        .filter_map(|m| m.into_inner().ok().flatten())
640        .collect()
641}
642
643#[derive(Debug, Clone, PartialEq, Eq)]
644pub(crate) struct Tok {
645    pub(crate) text: String,
646    pub(crate) op: bool,
647}
648
649pub(crate) fn shell_tokens(line: &str) -> Option<Vec<Tok>> {
650    let mut toks = Vec::new();
651    let mut cur = String::new();
652    let mut in_tok = false;
653    let mut chars = line.chars().peekable();
654    let flush = |toks: &mut Vec<Tok>, cur: &mut String, in_tok: &mut bool| {
655        if *in_tok {
656            toks.push(Tok {
657                text: std::mem::take(cur),
658                op: false,
659            });
660            *in_tok = false;
661        }
662    };
663    while let Some(c) = chars.next() {
664        match c {
665            ' ' | '\t' => flush(&mut toks, &mut cur, &mut in_tok),
666            '\'' => {
667                in_tok = true;
668                loop {
669                    match chars.next()? {
670                        '\'' => break,
671                        x => cur.push(x),
672                    }
673                }
674            }
675            '"' => {
676                in_tok = true;
677                loop {
678                    match chars.next()? {
679                        '"' => break,
680                        '\\' => match chars.next()? {
681                            x @ ('"' | '\\' | '$' | '`') => cur.push(x),
682                            x => {
683                                cur.push('\\');
684                                cur.push(x);
685                            }
686                        },
687                        '`' => return None,
688                        '$' if chars.peek() == Some(&'(') => return None,
689                        x => cur.push(x),
690                    }
691                }
692            }
693            '\\' => {
694                in_tok = true;
695                let mut following = chars.clone();
696                let next = following.next();
697                let after_next = following.next();
698                let escaped_substitution = next == Some('$') && after_next == Some('(');
699                let unc_prefix = cur.is_empty()
700                    && next == Some('\\')
701                    && after_next
702                        .is_some_and(|c| !c.is_whitespace() && !"'\"\\|<>&;$`".contains(c));
703                if cfg!(windows)
704                    && (unc_prefix
705                        || (!escaped_substitution
706                            && !chars
707                                .peek()
708                                .is_some_and(|c| c.is_whitespace() || "'\"\\|<>&;`".contains(*c))))
709                {
710                    cur.push('\\');
711                } else if let Some(x) = chars.next() {
712                    cur.push(x);
713                }
714            }
715            '|' | '<' | '>' | ';' | '&' => {
716                flush(&mut toks, &mut cur, &mut in_tok);
717                let mut op = c.to_string();
718                while let Some(&n) = chars.peek() {
719                    if !"|<>&".contains(n) {
720                        break;
721                    }
722                    op.push(n);
723                    chars.next();
724                }
725                toks.push(Tok { text: op, op: true });
726            }
727            '#' if !in_tok => break,
728            '`' => return None,
729            '$' if chars.peek() == Some(&'(') => return None,
730            _ => {
731                in_tok = true;
732                cur.push(c);
733            }
734        }
735    }
736    flush(&mut toks, &mut cur, &mut in_tok);
737    Some(toks)
738}
739
740/// Splits a command line into words, shell-style quoting, no shell operators.
741pub fn shell_split(line: &str) -> Result<Vec<String>> {
742    let toks = shell_tokens(line).with_context(|| format!("cannot split `{line}`"))?;
743    if let Some(op) = toks.iter().find(|t| t.op) {
744        bail!(
745            "`{line}` uses the shell operator `{}`: put the pipeline in a script and give its path",
746            op.text
747        );
748    }
749    Ok(toks.into_iter().map(|t| t.text).collect())
750}
751
752pub(crate) fn shell_quote(word: &str) -> String {
753    let plain = !word.is_empty()
754        && word
755            .chars()
756            .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
757    if plain {
758        word.to_string()
759    } else {
760        format!("'{}'", word.replace('\'', r"'\''"))
761    }
762}
763
764fn lines(text: &str) -> Vec<&str> {
765    let text = text.strip_suffix('\n').unwrap_or(text);
766    if text.is_empty() {
767        return Vec::new();
768    }
769    text.split('\n')
770        .map(|l| l.strip_suffix('\r').unwrap_or(l))
771        .collect()
772}
773
774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
775enum Op {
776    Equal(usize, usize),
777    Delete(usize),
778    Insert(usize),
779}
780
781fn diff_ops<A, B>(a: &[A], b: &[B], eq: impl Fn(&A, &B) -> bool) -> Vec<Op> {
782    let mut head = 0;
783    while head < a.len() && head < b.len() && eq(&a[head], &b[head]) {
784        head += 1;
785    }
786    let mut tail = 0;
787    while tail < a.len() - head
788        && tail < b.len() - head
789        && eq(&a[a.len() - 1 - tail], &b[b.len() - 1 - tail])
790    {
791        tail += 1;
792    }
793    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);
794    let mut ops: Vec<Op> = (0..head).map(|i| Op::Equal(i, i)).collect();
795    let (n, m) = (am.len(), bm.len());
796    if n * m <= 4_000_000 {
797        let mut lcs = vec![vec![0u32; m + 1]; n + 1];
798        for i in (0..n).rev() {
799            for j in (0..m).rev() {
800                lcs[i][j] = if eq(&am[i], &bm[j]) {
801                    lcs[i + 1][j + 1] + 1
802                } else {
803                    lcs[i + 1][j].max(lcs[i][j + 1])
804                };
805            }
806        }
807        let (mut i, mut j) = (0, 0);
808        while i < n || j < m {
809            if i < n && j < m && eq(&am[i], &bm[j]) {
810                ops.push(Op::Equal(head + i, head + j));
811                i += 1;
812                j += 1;
813            } else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
814                ops.push(Op::Delete(head + i));
815                i += 1;
816            } else {
817                ops.push(Op::Insert(head + j));
818                j += 1;
819            }
820        }
821    } else {
822        ops.extend((0..n).map(|i| Op::Delete(head + i)));
823        ops.extend((0..m).map(|j| Op::Insert(head + j)));
824    }
825    ops.extend((0..tail).map(|k| Op::Equal(a.len() - tail + k, b.len() - tail + k)));
826    ops
827}
828
829pub(crate) fn line_matches(expected: &str, actual: &str) -> bool {
830    if !expected.contains("[..]") {
831        return expected == actual;
832    }
833    let parts: Vec<&str> = expected.split("[..]").collect();
834    let (first, last) = (parts[0], parts[parts.len() - 1]);
835    let Some(rest) = actual.strip_prefix(first) else {
836        return false;
837    };
838    let Some(mut rest) = rest.strip_suffix(last) else {
839        return false;
840    };
841    for mid in &parts[1..parts.len() - 1] {
842        match rest.find(mid) {
843            Some(i) => rest = &rest[i + mid.len()..],
844            None => return false,
845        }
846    }
847    true
848}
849
850/// Whether a line can match a line it is not equal to: `[..]` stands for any text, and with a
851/// tolerance a number can meet a nearby number. Any other line matches its own text and nothing
852/// else, so comparing the sorted sides already settles those.
853fn can_match_beyond_its_text(line: &str, tol: Option<f64>) -> bool {
854    line.contains("[..]") || (tol.is_some() && line.bytes().any(|b| b.is_ascii_digit()))
855}
856
857/// Expected lines against actual lines in any order: every expected line paired with a distinct
858/// actual line. Sorting both sides and pairing by position cannot do this once a line matches
859/// more than its own text, because no order agrees with a match that is not transitive -- `10.0`
860/// has to meet `9.999999999999999` while sorting before `2.0`. So identical lines are paired off
861/// first, and the lines that are left get a search that gives a line up when another line needs
862/// it.
863fn lines_match_in_any_order(expected: &[&str], actual: &[&str], tol: Option<f64>) -> bool {
864    if expected.len() != actual.len() {
865        return false;
866    }
867    let (mut sorted_e, mut sorted_a) = (expected.to_vec(), actual.to_vec());
868    sorted_e.sort_unstable();
869    sorted_a.sort_unstable();
870    if sorted_e == sorted_a {
871        return true;
872    }
873    if !expected.iter().any(|l| can_match_beyond_its_text(l, tol)) {
874        return false;
875    }
876    let mut spare: HashMap<&str, usize> = HashMap::new();
877    for line in actual {
878        *spare.entry(*line).or_default() += 1;
879    }
880    let mut rest_expected = Vec::new();
881    for line in expected {
882        match spare.get_mut(line) {
883            Some(count) if *count > 0 => *count -= 1,
884            _ => rest_expected.push(*line),
885        }
886    }
887    let rest_actual: Vec<&str> = spare
888        .into_iter()
889        .flat_map(|(line, count)| std::iter::repeat_n(line, count))
890        .collect();
891    let mut holder: Vec<Option<usize>> = vec![None; rest_actual.len()];
892    for want in 0..rest_expected.len() {
893        let mut tried = vec![false; rest_actual.len()];
894        if !take_a_line(
895            want,
896            &rest_expected,
897            &rest_actual,
898            tol,
899            &mut tried,
900            &mut holder,
901        ) {
902            return false;
903        }
904    }
905    true
906}
907
908/// One augmenting step: find a line for `want`, moving the expected lines that already hold one
909/// along to another line they also match.
910fn take_a_line(
911    want: usize,
912    expected: &[&str],
913    actual: &[&str],
914    tol: Option<f64>,
915    tried: &mut [bool],
916    holder: &mut [Option<usize>],
917) -> bool {
918    for i in 0..actual.len() {
919        if tried[i] || !line_matches_within(expected[want], actual[i], tol) {
920            continue;
921        }
922        tried[i] = true;
923        if holder[i].is_none_or(|held| take_a_line(held, expected, actual, tol, tried, holder)) {
924            holder[i] = Some(want);
925            return true;
926        }
927    }
928    false
929}
930
931/// A line within the float tolerance, for lines without wildcards.
932fn line_matches_within(expected: &str, actual: &str, tol: Option<f64>) -> bool {
933    line_matches(expected, actual)
934        || tol.is_some_and(|t| {
935            !expected.contains("[..]") && crate::tolerance::line_close(expected, actual, t)
936        })
937}
938
939/// trycmd's matching: `[..]` is any text within a line, a `...` line is any number of lines.
940fn text_matches(expected: &str, actual: &str, tol: Option<f64>) -> bool {
941    let (e, a) = (lines(expected), lines(actual));
942    let m = a.len();
943    let mut next = vec![false; m + 1];
944    next[m] = true;
945    for line in e.iter().rev() {
946        let mut cur = vec![false; m + 1];
947        for j in (0..=m).rev() {
948            cur[j] = if *line == "..." {
949                next[j] || (j < m && cur[j + 1])
950            } else {
951                j < m && line_matches_within(line, a[j], tol) && next[j + 1]
952            };
953        }
954        next = cur;
955    }
956    next[0]
957}
958
959fn render_diff(expected: &str, actual: &str, tol: Option<f64>) -> String {
960    let (e, a) = (lines(expected), lines(actual));
961    let ops = diff_ops(&e, &a, |x, y| line_matches_within(x, y, tol));
962    let changed: Vec<bool> = ops.iter().map(|op| !matches!(op, Op::Equal(..))).collect();
963    let near = |k: usize| {
964        let lo = k.saturating_sub(3);
965        let hi = (k + 4).min(ops.len());
966        changed[lo..hi].iter().any(|c| *c)
967    };
968    let mut out = String::new();
969    let mut skipped = false;
970    for (k, op) in ops.iter().enumerate() {
971        match op {
972            Op::Equal(_, j) if near(k) => {
973                skipped = false;
974                out += &format!("  {}\n", a[*j]);
975            }
976            Op::Equal(..) => {
977                if !skipped {
978                    out += "  ⋮\n";
979                    skipped = true;
980                }
981            }
982            Op::Delete(i) => {
983                skipped = false;
984                out += &format!("- {}\n", e[*i]);
985            }
986            Op::Insert(j) => {
987                skipped = false;
988                out += &format!("+ {}\n", a[*j]);
989            }
990        }
991    }
992    let trail = |s: &str| s.ends_with('\n') || s.is_empty();
993    if out.is_empty() || trail(expected) != trail(actual) {
994        out += &format!(
995            "(trailing newline: expected {}, got {})\n",
996            trail(expected),
997            trail(actual)
998        );
999    }
1000    out
1001}
1002
1003fn tokens(line: &str) -> Vec<&str> {
1004    let mut out = Vec::new();
1005    let mut start = None;
1006    for (i, c) in line.char_indices() {
1007        if c.is_alphanumeric() {
1008            start.get_or_insert(i);
1009        } else {
1010            if let Some(s) = start.take() {
1011                out.push(&line[s..i]);
1012            }
1013            out.push(&line[i..i + c.len_utf8()]);
1014        }
1015    }
1016    if let Some(s) = start {
1017        out.push(&line[s..]);
1018    }
1019    out
1020}
1021
1022pub(crate) fn merge_line(a: &str, b: &str) -> String {
1023    let (ta, tb) = (tokens(a), tokens(b));
1024    if ta.len() != tb.len() {
1025        return "[..]".to_string();
1026    }
1027    let mut out = String::new();
1028    for (x, y) in ta.iter().zip(&tb) {
1029        if x == y {
1030            out += x;
1031        } else if !out.ends_with("[..]") {
1032            out += "[..]";
1033        }
1034    }
1035    out
1036}
1037
1038/// Two runs of the original: what they agree on stays, what differs becomes a wildcard.
1039fn merge_noise(a: &str, b: &str) -> String {
1040    if a == b {
1041        return a.to_string();
1042    }
1043    let (la, lb): (Vec<&str>, Vec<&str>) = (a.split('\n').collect(), b.split('\n').collect());
1044    let ops = diff_ops(&la, &lb, |x, y| x == y);
1045    let mut out: Vec<String> = Vec::new();
1046    let (mut dels, mut ins): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
1047    let flush = |out: &mut Vec<String>, dels: &mut Vec<&str>, ins: &mut Vec<&str>| {
1048        if dels.is_empty() && ins.is_empty() {
1049            return;
1050        }
1051        if dels.len() == ins.len() {
1052            for (x, y) in dels.iter().zip(ins.iter()) {
1053                out.push(merge_line(x, y));
1054            }
1055        } else if out.last().map(String::as_str) != Some("...") {
1056            out.push("...".to_string());
1057        }
1058        dels.clear();
1059        ins.clear();
1060    };
1061    for op in ops {
1062        match op {
1063            Op::Equal(i, _) => {
1064                flush(&mut out, &mut dels, &mut ins);
1065                out.push(la[i].to_string());
1066            }
1067            Op::Delete(i) => dels.push(la[i]),
1068            Op::Insert(j) => ins.push(lb[j]),
1069        }
1070    }
1071    flush(&mut out, &mut dels, &mut ins);
1072    out.join("\n")
1073}
1074
1075fn stem(word: &str) -> String {
1076    Path::new(word)
1077        .file_stem()
1078        .map(|s| s.to_string_lossy().to_lowercase())
1079        .unwrap_or_default()
1080}
1081
1082/// Names the app is invoked by, most specific first.
1083fn app_names(repo: &Path, run: &[String], explicit: Option<&str>) -> Vec<String> {
1084    let mut names: Vec<String> = Vec::new();
1085    let mut add = |name: &str| {
1086        let name = name.rsplit('/').next().unwrap_or(name).to_lowercase();
1087        if !name.is_empty() && !NOT_APP_NAMES.contains(&name.as_str()) && !names.contains(&name) {
1088            names.push(name);
1089        }
1090    };
1091    if let Some(name) = explicit {
1092        add(name);
1093    }
1094    for word in run {
1095        let path = repo.join(word);
1096        if word.starts_with('-') || path.is_dir() || Path::new(word).is_dir() {
1097            continue;
1098        }
1099        add(&stem(word));
1100    }
1101    if let Ok(text) = std::fs::read_to_string(repo.join("package.json"))
1102        && let Ok(pkg) = serde_json::from_str::<Value>(&text)
1103    {
1104        match &pkg["bin"] {
1105            Value::String(_) => add(pkg["name"].as_str().unwrap_or_default()),
1106            Value::Object(map) => map.keys().for_each(|k| add(k)),
1107            _ => {}
1108        }
1109    }
1110    if let Ok(text) = std::fs::read_to_string(repo.join("pyproject.toml"))
1111        && let Ok(doc) = text.parse::<DocumentMut>()
1112    {
1113        for table in [
1114            doc.get("project").and_then(|p| p.get("scripts")),
1115            doc.get("tool")
1116                .and_then(|t| t.get("poetry"))
1117                .and_then(|p| p.get("scripts")),
1118        ]
1119        .into_iter()
1120        .flatten()
1121        {
1122            if let Some(t) = table.as_table_like() {
1123                t.iter().for_each(|(k, _)| add(k));
1124            }
1125        }
1126    }
1127    for (dir, dirs_only) in [("cmd", true), ("bin", false), ("exe", false)] {
1128        let Ok(entries) = std::fs::read_dir(repo.join(dir)) else {
1129            continue;
1130        };
1131        let mut found: Vec<String> = entries
1132            .flatten()
1133            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir() == dirs_only))
1134            .map(|e| stem(&e.file_name().to_string_lossy()))
1135            .collect();
1136        found.sort();
1137        found.iter().for_each(|n| add(n));
1138    }
1139    names
1140}
1141
1142fn safe_relative(arg: &str) -> bool {
1143    let p = Path::new(arg);
1144    !arg.is_empty()
1145        && !arg.starts_with('-')
1146        && p.components().all(|c| matches!(c, Component::Normal(_)))
1147}
1148
1149fn read_input_file(candidates: &[PathBuf]) -> Option<Vec<u8>> {
1150    candidates
1151        .iter()
1152        .find(|p| p.is_file() && std::fs::metadata(p).is_ok_and(|m| m.len() <= MAX_INPUT_FILE))
1153        .and_then(|p| std::fs::read(p).ok())
1154}
1155
1156fn parse_example(line: &str, names: &[String], repo: &Path, doc_dir: &Path) -> Option<Case> {
1157    let toks = shell_tokens(line)?;
1158    let ops: Vec<usize> = (0..toks.len()).filter(|&i| toks[i].op).collect();
1159    let words = |range: &[Tok]| -> Vec<String> { range.iter().map(|t| t.text.clone()).collect() };
1160    let lookup = |arg: &str| -> Option<Vec<u8>> {
1161        if !safe_relative(arg) {
1162            return None;
1163        }
1164        read_input_file(&[repo.join(arg), doc_dir.join(arg)])
1165    };
1166    let (main, stdin): (Vec<String>, Option<Vec<u8>>) = match ops.as_slice() {
1167        [] => (words(&toks), None),
1168        [i] if toks[*i].text == "|" => {
1169            let feed = words(&toks[..*i]);
1170            let stdin = match feed.first().map(String::as_str) {
1171                Some("echo") => {
1172                    let newline = feed.get(1).map(String::as_str) != Some("-n");
1173                    let text: Vec<&str> = feed[1..]
1174                        .iter()
1175                        .map(String::as_str)
1176                        .filter(|w| !matches!(*w, "-n" | "-e"))
1177                        .collect();
1178                    let mut text = text.join(" ");
1179                    if newline {
1180                        text.push('\n');
1181                    }
1182                    text.into_bytes()
1183                }
1184                Some("printf") if feed.len() == 2 => feed[1]
1185                    .replace("\\n", "\n")
1186                    .replace("\\t", "\t")
1187                    .into_bytes(),
1188                Some("cat") if feed.len() == 2 => lookup(&feed[1])?,
1189                _ => return None,
1190            };
1191            (words(&toks[*i + 1..]), Some(stdin))
1192        }
1193        [i] if toks[*i].text == "<" && *i + 2 == toks.len() => {
1194            (words(&toks[..*i]), Some(lookup(&toks[*i + 1].text)?))
1195        }
1196        _ => return None,
1197    };
1198    let mut env = BTreeMap::new();
1199    let mut rest = main.as_slice();
1200    while let Some((first, tail)) = rest.split_first() {
1201        let Some((k, v)) = first.split_once('=') else {
1202            break;
1203        };
1204        if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1205            break;
1206        }
1207        env.insert(k.to_string(), v.to_string());
1208        rest = tail;
1209    }
1210    let (prog, args) = rest.split_first()?;
1211    if !names.contains(&stem(prog)) {
1212        return None;
1213    }
1214    let mut case = Case::new(args.to_vec());
1215    case.env = env;
1216    case.stdin = stdin;
1217    for arg in args {
1218        if let Some(bytes) = lookup(arg) {
1219            case.files.insert(PathBuf::from(arg), bytes);
1220        }
1221    }
1222    Some(case)
1223}
1224
1225fn find_examples(repo: &Path, names: &[String]) -> Vec<Case> {
1226    if names.is_empty() {
1227        return Vec::new();
1228    }
1229    scan_examples(repo, |line, doc_dir| {
1230        parse_example(line, names, repo, doc_dir)
1231    })
1232}
1233
1234/// The documented examples no recorded case runs, as the command line the docs show.
1235pub(crate) fn unrecorded_examples(repo: &Path, config: &Config) -> Result<Vec<String>> {
1236    if config.http.is_some() {
1237        return crate::http::unrecorded_examples(repo);
1238    }
1239    let recorded: BTreeSet<String> = load_specs(&cases_dir(repo))?
1240        .iter()
1241        .map(|s| s.case.key())
1242        .collect();
1243    let mut seen = BTreeSet::new();
1244    Ok(
1245        find_examples(repo, &app_names(repo, &config.run, Some(&config.name)))
1246            .into_iter()
1247            .filter(|case| !recorded.contains(&case.key()) && seen.insert(case.key()))
1248            .map(|case| {
1249                std::iter::once(config.name.as_str())
1250                    .chain(case.args.iter().map(String::as_str))
1251                    .map(shell_quote)
1252                    .collect::<Vec<_>>()
1253                    .join(" ")
1254            })
1255            .collect(),
1256    )
1257}
1258
1259/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
1260/// with the folder of the file it came from.
1261pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
1262    let skip = ["node_modules", "target", "vendor", ".git"];
1263    let walker = crate::walk::filtered(repo, move |e| {
1264        let name = e.file_name().to_string_lossy();
1265        !skip.contains(&name.as_ref())
1266    })
1267    .max_depth(Some(4))
1268    .sort_by_file_name(|a, b| a.cmp(b))
1269    .build();
1270    let rust_dir = repo.join("rust");
1271    let mut out = Vec::new();
1272    for entry in walker.flatten() {
1273        let path = entry.path();
1274        if path.starts_with(&rust_dir) || !path.is_file() {
1275            continue;
1276        }
1277        let ext = path
1278            .extension()
1279            .map(|e| e.to_string_lossy().to_lowercase())
1280            .unwrap_or_default();
1281        let markdown = matches!(ext.as_str(), "md" | "markdown");
1282        if !markdown && ext != "sh" {
1283            continue;
1284        }
1285        let Ok(text) = std::fs::read_to_string(path) else {
1286            continue;
1287        };
1288        let doc_dir = path.parent().unwrap_or(repo);
1289        let mut fence: Option<String> = None;
1290        // A command wrapped with trailing backslashes, joined so far.
1291        let mut pending = String::new();
1292        for raw in text.lines() {
1293            let line = raw.trim();
1294            let candidate = if markdown {
1295                if line.starts_with("```") || line.starts_with("~~~") {
1296                    pending.clear();
1297                    fence = match fence {
1298                        Some(_) => None,
1299                        None => Some(
1300                            line.trim_start_matches(['`', '~'])
1301                                .split_whitespace()
1302                                .next()
1303                                .unwrap_or_default()
1304                                .to_lowercase(),
1305                        ),
1306                    };
1307                    continue;
1308                }
1309                let Some(lang) = &fence else { continue };
1310                // Continuation lines carry no `$ ` prompt, and keep their indentation: it is what
1311                // separates them from the previous word, as the shell adds no space when joining.
1312                if !pending.is_empty() {
1313                    raw
1314                } else {
1315                    let start = raw.trim_start();
1316                    match start.strip_prefix("$ ") {
1317                        Some(rest) => rest,
1318                        None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => start,
1319                        None => continue,
1320                    }
1321                }
1322            } else if !pending.is_empty() {
1323                raw
1324            } else {
1325                let start = raw.trim_start();
1326                start.strip_prefix("$ ").unwrap_or(start)
1327            };
1328            // The line's end is untrimmed, so `\ ` (an escaped space) does not continue.
1329            if !ends_in_comment(candidate)
1330                && let Some(head) = continued(candidate)
1331            {
1332                pending.push_str(head);
1333                continue;
1334            }
1335            pending.push_str(candidate);
1336            let command = std::mem::take(&mut pending);
1337            if let Some(case) = parse(&command, doc_dir) {
1338                out.push(case);
1339            }
1340        }
1341    }
1342    out
1343}
1344
1345/// Whether a shell line ends inside a comment: an unquoted `#` that starts a word. A `\` at the
1346/// end of a comment is part of the comment, not a continuation.
1347fn ends_in_comment(line: &str) -> bool {
1348    let (mut single, mut double, mut escaped, mut word_start) = (false, false, false, true);
1349    for c in line.chars() {
1350        if escaped {
1351            escaped = false;
1352            word_start = false;
1353            continue;
1354        }
1355        match c {
1356            '\\' if !single => escaped = true,
1357            '\'' if !double => single = !single,
1358            '"' if !single => double = !double,
1359            '#' if word_start && !single && !double => return true,
1360            _ => {}
1361        }
1362        word_start = c.is_whitespace() && !single && !double;
1363    }
1364    false
1365}
1366
1367/// The line without its trailing `\` when the shell would join it with the next line. An even
1368/// number of trailing backslashes ends in a literal one (`C:\\`), not a continuation.
1369fn continued(line: &str) -> Option<&str> {
1370    let head = line.strip_suffix('\\')?;
1371    let escaped = (head.len() - head.trim_end_matches('\\').len()) % 2 == 1;
1372    (!escaped).then_some(head)
1373}
1374
1375fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1376    let text =
1377        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1378    let mut out = Vec::new();
1379    for (n, line) in text.lines().enumerate() {
1380        if line.trim().is_empty() {
1381            continue;
1382        }
1383        let input: Input = serde_json::from_str(line)
1384            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1385        let mut case = Case::new(input.args);
1386        case.stdin = input.stdin.map(String::into_bytes);
1387        case.env = input.env;
1388        for (file, content) in input.files {
1389            ensure!(
1390                safe_relative(&file),
1391                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1392                path.display(),
1393                n + 1
1394            );
1395            case.files.insert(PathBuf::from(file), content.into_bytes());
1396        }
1397        for file in input.remove {
1398            ensure!(
1399                safe_relative(&file),
1400                "{}:{}: removed `{file}` must be a relative path inside the sandbox",
1401                path.display(),
1402                n + 1
1403            );
1404            case.remove.push(PathBuf::from(file));
1405        }
1406        out.push((input.name, case));
1407    }
1408    Ok(out)
1409}
1410
1411pub(crate) fn is_word(arg: &str) -> bool {
1412    let mut chars = arg.chars();
1413    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1414        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1415}
1416
1417pub(crate) fn interleave<T>(groups: Vec<Vec<T>>) -> Vec<T> {
1418    let mut queues: Vec<std::collections::VecDeque<T>> =
1419        groups.into_iter().map(Into::into).collect();
1420    let mut out = Vec::new();
1421    loop {
1422        let mut progressed = false;
1423        for q in &mut queues {
1424            if let Some(item) = q.pop_front() {
1425                out.push(item);
1426                progressed = true;
1427            }
1428        }
1429        if !progressed {
1430            break;
1431        }
1432    }
1433    out
1434}
1435
1436/// Spreads traps round-robin across bases, deduplicating against `existing` and earlier traps
1437/// before capping at `limit`. `reserved` traps (such as the unknown-route probe) are always kept
1438/// first. Returns `(kept, dropped)` where `dropped` counts unique traps excluded by `limit`.
1439pub(crate) fn spread_traps<T, K, F>(
1440    per_base: Vec<Vec<T>>,
1441    reserved: Vec<T>,
1442    existing: &BTreeSet<K>,
1443    key: F,
1444    limit: usize,
1445) -> (Vec<T>, usize)
1446where
1447    K: Ord + Clone,
1448    F: Fn(&T) -> K,
1449{
1450    let mut seen = existing.clone();
1451    let mut out = Vec::new();
1452    let mut dropped = 0usize;
1453    for item in reserved {
1454        if seen.insert(key(&item)) {
1455            if out.len() < limit {
1456                out.push(item);
1457            } else {
1458                dropped += 1;
1459            }
1460        }
1461    }
1462    let mut queues: Vec<std::collections::VecDeque<T>> =
1463        per_base.into_iter().map(Into::into).collect();
1464    loop {
1465        let mut any = false;
1466        for q in &mut queues {
1467            while let Some(item) = q.pop_front() {
1468                if seen.insert(key(&item)) {
1469                    if out.len() < limit {
1470                        out.push(item);
1471                    } else {
1472                        dropped += 1;
1473                    }
1474                    any = true;
1475                    break;
1476                }
1477            }
1478        }
1479        if !any {
1480            break;
1481        }
1482    }
1483    (out, dropped)
1484}
1485
1486fn trap_cases(bases: &[Case]) -> (Vec<Case>, usize) {
1487    let mut per_base = Vec::with_capacity(bases.len());
1488    for base in bases {
1489        let mut slots: Vec<Vec<Case>> = Vec::new();
1490        for (i, arg) in base.args.iter().enumerate() {
1491            if i == 0 && is_word(arg) {
1492                continue;
1493            }
1494            let number = arg.parse::<f64>().is_ok();
1495            if arg.starts_with('-') && !number {
1496                continue;
1497            }
1498            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1499                INT_TRAPS.to_vec()
1500            } else if number && arg.contains(['.', 'e', 'E']) {
1501                FLOAT_TRAPS.to_vec()
1502            } else if base.files.contains_key(Path::new(arg)) {
1503                vec!["missing-input.txt"]
1504            } else {
1505                STRING_TRAPS.to_vec()
1506            };
1507            let slot: Vec<Case> = values
1508                .into_iter()
1509                .filter(|v| v != arg)
1510                .map(|v| {
1511                    let mut case = base.clone();
1512                    case.args[i] = v.to_string();
1513                    case
1514                })
1515                .collect();
1516            if !slot.is_empty() {
1517                slots.push(slot);
1518            }
1519        }
1520        if let Some(stdin) = &base.stdin {
1521            let json = std::str::from_utf8(stdin)
1522                .ok()
1523                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1524                .is_some_and(|v| v.is_object() || v.is_array());
1525            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1526            slots.push(
1527                values
1528                    .iter()
1529                    .map(|v| {
1530                        let mut case = base.clone();
1531                        case.stdin = Some(v.as_bytes().to_vec());
1532                        case
1533                    })
1534                    .collect(),
1535            );
1536        }
1537        per_base.push(interleave(slots));
1538    }
1539    let existing: BTreeSet<_> = bases.iter().map(Case::key).collect();
1540    spread_traps(per_base, Vec::new(), &existing, Case::key, MAX_TRAPS)
1541}
1542
1543pub(crate) fn slug(text: &str) -> String {
1544    slug_max(text, 24)
1545}
1546
1547/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
1548/// only past the 24th character stay apart.
1549pub(crate) fn given_slug(text: &str) -> String {
1550    slug_max(text, 96)
1551}
1552
1553fn slug_max(text: &str, max: usize) -> String {
1554    let mut out = String::new();
1555    for c in text.chars() {
1556        if c.is_ascii_alphanumeric() {
1557            out.push(c.to_ascii_lowercase());
1558        } else if !out.ends_with('-') && !out.is_empty() {
1559            out.push('-');
1560        }
1561    }
1562    out.truncate(max);
1563    out.trim_end_matches('-').to_string()
1564}
1565
1566pub struct RecordOptions<'a> {
1567    pub repo: &'a Path,
1568    /// The command that runs the original; taken from the saved config when empty.
1569    pub run: &'a [String],
1570    pub inputs: Option<&'a Path>,
1571    /// Built-in normalizer names, or `name=regex` for your own.
1572    pub normalize: &'a [String],
1573    pub name: Option<&'a str>,
1574    pub traps: bool,
1575    pub timeout_secs: Option<u64>,
1576    /// `Some(true)` records as a server, `Some(false)` drops any saved server setting and records
1577    /// as a CLI, and `None` keeps the saved mode (or enables server mode if server-only options
1578    /// such as `port`, non-empty `server_args`, or `pace_ms` are given).
1579    pub http: Option<bool>,
1580    /// The port a server always listens on (implies `http`); unset keeps the saved port, `Some(0)`
1581    /// removes it so the server gets a free port through `PORT` and `{port}`.
1582    pub port: Option<u16>,
1583    /// Servers: arguments every start gets after its command, the original's and every build's
1584    /// (non-empty implies `http`); `None` keeps the saved list, `Some(&[])` clears it.
1585    pub server_args: Option<&'a [String]>,
1586    /// Repository files or folders copied into a fresh working directory before every case (CLIs)
1587    /// or start (servers); `None` keeps the saved list, `Some(&[])` clears it.
1588    pub fresh: Option<&'a [String]>,
1589    /// Servers: milliseconds to wait after each response, for work the server does after
1590    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
1591    pub pace_ms: Option<u64>,
1592    /// Numbers in the output match within this tolerance; kept from the last recording when
1593    /// `None`, removed with 0.
1594    pub float_tolerance: Option<f64>,
1595    /// Written files of raw floats, `path=f32le` or `path=f64le`; kept from the last recording
1596    /// when empty.
1597    pub float_files: &'a [String],
1598    pub effects: Option<crate::effects::EffectsConfig>,
1599    /// Servers: seconds to wait for the port before giving up; kept from the last recording when
1600    /// `None`; 0 restores the default, a minute.
1601    pub ready_secs: Option<u64>,
1602}
1603
1604fn is_zero(n: &usize) -> bool {
1605    *n == 0
1606}
1607
1608#[derive(Debug, Serialize)]
1609pub struct RecordOutcome {
1610    pub dir: PathBuf,
1611    pub run: Vec<String>,
1612    pub cases: usize,
1613    pub examples: usize,
1614    pub inputs: usize,
1615    pub traps: usize,
1616    /// Unique traps dropped after hitting `MAX_TRAPS`.
1617    #[serde(default, skip_serializing_if = "is_zero")]
1618    pub traps_dropped: usize,
1619    /// Cases where the two runs of the original differed.
1620    pub noisy: Vec<String>,
1621    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1622    /// in any order, `lines` became a `...` that matches anything.
1623    pub noise: Vec<Noise>,
1624    /// Cases whose exit code or written files differed between the two runs.
1625    pub unstable: Vec<String>,
1626    /// Cases not written: the original timed out or did not answer.
1627    pub timed_out: Vec<String>,
1628    /// The cases this recording wrote.
1629    pub recorded: Vec<String>,
1630    /// Cases the last recording in this folder wrote and this one did not (a timeout included):
1631    /// removed, apart from files a case that stays reads (`fs.base`).
1632    pub stale: Vec<String>,
1633    /// Cases in the folder that no recording wrote (by hand, or before the list was kept):
1634    /// left in place.
1635    pub kept: Vec<String>,
1636}
1637
1638/// What each case's files are called after its name.
1639const CASE_FILES: [&str; 9] = [
1640    "toml",
1641    "stdin",
1642    "stdout",
1643    "stderr",
1644    REMOVED_EXT,
1645    crate::effects::EXT,
1646    "body",
1647    "in",
1648    "out",
1649];
1650
1651/// Removes the cases the last recording in this folder wrote (`previous`) that this one did not
1652/// write, and names the cases in the folder that did not come from a recording, which it keeps.
1653/// Only `previous` marks a case as a recording's: a case written by hand stays even when an input
1654/// of its name timed out now. Files a case that stays reads through `fs.base` (that folder, or one
1655/// inside it) stay too.
1656pub(crate) fn drop_stale(outcome: &mut RecordOutcome, previous: &[String]) -> Result<()> {
1657    let written: BTreeSet<&str> = outcome.recorded.iter().map(String::as_str).collect();
1658    let ours: BTreeSet<&str> = previous
1659        .iter()
1660        .map(String::as_str)
1661        .filter(|name| !written.contains(name))
1662        .collect();
1663    let read = bases_read(&outcome.dir, &ours);
1664    let mut stale = Vec::new();
1665    for name in &ours {
1666        if outcome.dir.join(format!("{name}.toml")).is_file() {
1667            stale.push((*name).to_string());
1668        }
1669        for ext in CASE_FILES {
1670            let path = outcome.dir.join(format!("{name}.{ext}"));
1671            // A folder a case that stays reads, holds one it reads, or is on the way to it as
1672            // written: `two.in/sub`, `../app-cases/two.in/sub` (resolved) and `two.in/../shared`
1673            // (on Unix only found while `two.in` exists) all keep `two.in`.
1674            let resolved = path.canonicalize().ok();
1675            if any_base_reads(&read, &path, resolved.as_deref()) {
1676                continue;
1677            }
1678            if path.is_dir() {
1679                std::fs::remove_dir_all(&path)
1680                    .with_context(|| format!("removing {}", path.display()))?;
1681            } else if path.is_file() {
1682                std::fs::remove_file(&path)
1683                    .with_context(|| format!("removing {}", path.display()))?;
1684            }
1685        }
1686    }
1687    let mut kept: Vec<String> = std::fs::read_dir(&outcome.dir)?
1688        .flatten()
1689        .filter_map(|entry| {
1690            let name = entry.file_name().to_string_lossy().into_owned();
1691            name.strip_suffix(".toml").map(str::to_string)
1692        })
1693        .filter(|name| !written.contains(name.as_str()))
1694        .collect();
1695    kept.sort();
1696    outcome.stale = stale;
1697    outcome.kept = kept;
1698    Ok(())
1699}
1700
1701fn any_base_reads(read: &BTreeSet<PathBuf>, path: &Path, resolved: Option<&Path>) -> bool {
1702    read.iter()
1703        .any(|base| base.starts_with(path) || resolved.is_some_and(|r| base.starts_with(r)))
1704}
1705
1706/// The `fs.base` folders that the cases in `dir` other than `going` read, each as written (joined
1707/// to `dir`) and, when it exists, resolved.
1708fn bases_read(dir: &Path, going: &BTreeSet<&str>) -> BTreeSet<PathBuf> {
1709    let Ok(entries) = std::fs::read_dir(dir) else {
1710        return BTreeSet::new();
1711    };
1712    entries
1713        .flatten()
1714        .map(|entry| entry.path())
1715        .filter(|path| {
1716            path.extension().is_some_and(|e| e == "toml")
1717                && path
1718                    .file_stem()
1719                    .and_then(|s| s.to_str())
1720                    .is_some_and(|stem| !going.contains(stem))
1721        })
1722        .filter_map(|path| std::fs::read_to_string(path).ok())
1723        .filter_map(|text| text.parse::<DocumentMut>().ok())
1724        .filter_map(|doc| {
1725            doc.get("fs")
1726                .and_then(|f| f.get("base"))
1727                .and_then(Item::as_str)
1728                .map(|base| dir.join(base))
1729        })
1730        .flat_map(|base| {
1731            let resolved = base.canonicalize().ok();
1732            std::iter::once(base).chain(resolved)
1733        })
1734        .collect()
1735}
1736
1737struct Recorded {
1738    stdout: Vec<u8>,
1739    stderr: Vec<u8>,
1740    effects: Option<Vec<u8>>,
1741    status: Status,
1742    written: BTreeMap<PathBuf, Vec<u8>>,
1743    removed: Vec<PathBuf>,
1744    binary: bool,
1745    noise: Vec<(String, NoiseKind)>,
1746    unstable: bool,
1747}
1748
1749/// How two runs of the original disagreed.
1750#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1751#[serde(rename_all = "lowercase")]
1752pub enum NoiseKind {
1753    /// Values within lines changed (times, ids): those parts are wildcards now.
1754    Values,
1755    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1756    /// in any order, and a port must produce exactly those lines.
1757    Order,
1758    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1759    /// anything. Look at these first.
1760    Lines,
1761}
1762
1763#[derive(Debug, Clone, Serialize)]
1764pub struct Noise {
1765    pub case: String,
1766    pub field: String,
1767    pub kind: NoiseKind,
1768}
1769
1770fn same_lines_any_order(a: &str, b: &str) -> bool {
1771    let (mut la, mut lb) = (lines(a), lines(b));
1772    la.sort_unstable();
1773    lb.sort_unstable();
1774    la == lb
1775}
1776
1777pub(crate) fn settle_text(
1778    norm: &Normalizers,
1779    a: &[u8],
1780    b: &[u8],
1781) -> (Vec<u8>, Option<NoiseKind>, bool) {
1782    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1783        (Ok(a), Ok(b)) => {
1784            let (a, b) = (norm.apply(a), norm.apply(b));
1785            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1786                (a.into_bytes(), None, false)
1787            } else if same_lines_any_order(&a, &b) {
1788                (a.into_bytes(), Some(NoiseKind::Order), false)
1789            } else {
1790                let merged = merge_noise(&a, &b);
1791                let kind = if merged.split('\n').any(|l| l == "...") {
1792                    NoiseKind::Lines
1793                } else {
1794                    NoiseKind::Values
1795                };
1796                (merged.into_bytes(), Some(kind), false)
1797            }
1798        }
1799        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1800    }
1801}
1802
1803fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1804    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1805        .iter()
1806        .any(|bytes| std::str::from_utf8(bytes).is_err());
1807    let settle_stream = |a: &[u8], b: &[u8]| {
1808        if binary {
1809            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1810        } else {
1811            let (bytes, noise, _) = settle_text(norm, a, b);
1812            (bytes, noise)
1813        }
1814    };
1815    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1816    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1817    let (effects, fx_noise) = match (&one.effects, &two.effects) {
1818        (Some(a), Some(b)) => {
1819            let (bytes, noise, _) = settle_text(norm, a, b);
1820            (Some(bytes), noise)
1821        }
1822        _ => (None, None),
1823    };
1824    let (w1, w2) = (one.written(case), two.written(case));
1825    let mut unstable = one.status != two.status
1826        || one.removed != two.removed
1827        || !w1.keys().eq(w2.keys())
1828        || (binary && (out_noise.is_some() || err_noise.is_some()));
1829    let mut noise: Vec<(String, NoiseKind)> = [
1830        ("stdout", out_noise),
1831        ("stderr", err_noise),
1832        (crate::effects::EXT, fx_noise),
1833    ]
1834    .into_iter()
1835    .filter_map(|(f, k)| Some((f.to_string(), k?)))
1836    .collect();
1837    let mut written = BTreeMap::new();
1838    for (path, a) in &w1 {
1839        let b = w2.get(path).unwrap_or(a);
1840        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1841        unstable |= file_bin && file_noise.is_some();
1842        if let Some(kind) = file_noise {
1843            noise.push((format!("file {}", path.display()), kind));
1844        }
1845        written.insert(path.clone(), bytes);
1846    }
1847    Recorded {
1848        stdout,
1849        stderr,
1850        effects,
1851        status: one.status.clone(),
1852        written,
1853        removed: one.removed.clone(),
1854        binary,
1855        noise,
1856        unstable,
1857    }
1858}
1859
1860fn dotted() -> Table {
1861    let mut t = Table::new();
1862    t.set_dotted(true);
1863    t
1864}
1865
1866fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1867    for ext in [
1868        "stdin",
1869        "stdout",
1870        "stderr",
1871        REMOVED_EXT,
1872        crate::effects::EXT,
1873    ] {
1874        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1875    }
1876    for ext in ["in", "out"] {
1877        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1878    }
1879    let mut doc = DocumentMut::new();
1880    let mut bin_t = dotted();
1881    bin_t["name"] = value(bin);
1882    doc["bin"] = Item::Table(bin_t);
1883    let mut args = toml_edit::Array::new();
1884    for a in &case.args {
1885        args.push(a.as_str());
1886    }
1887    doc["args"] = value(args);
1888    if !case.env.is_empty() {
1889        let mut add = dotted();
1890        for (k, v) in &case.env {
1891            add[k.as_str()] = value(v.as_str());
1892        }
1893        let mut env = dotted();
1894        env.insert("add", Item::Table(add));
1895        doc["env"] = Item::Table(env);
1896    }
1897    match rec.status {
1898        Status::Code(code) => {
1899            let mut status = dotted();
1900            status["code"] = value(i64::from(code));
1901            doc["status"] = Item::Table(status);
1902        }
1903        _ => doc["status"] = value("interrupted"),
1904    }
1905    let mut fs = dotted();
1906    fs["sandbox"] = value(true);
1907    if !case.files.is_empty() {
1908        fs["base"] = value(format!("{name}.in"));
1909    }
1910    if !case.remove.is_empty() {
1911        let mut remove = toml_edit::Array::new();
1912        for path in &case.remove {
1913            remove.push(path.to_string_lossy().as_ref());
1914        }
1915        fs["remove"] = value(remove);
1916    }
1917    doc["fs"] = Item::Table(fs);
1918    if rec.binary {
1919        doc["binary"] = value(true);
1920    }
1921    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1922    if let Some(stdin) = &case.stdin {
1923        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1924    }
1925    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1926    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1927    if !rec.removed.is_empty() {
1928        let list: String = rec
1929            .removed
1930            .iter()
1931            .map(|p| format!("{}\n", p.display()))
1932            .collect();
1933        std::fs::write(dir.join(format!("{name}.{REMOVED_EXT}")), list)?;
1934    }
1935    if let Some(effects) = &rec.effects {
1936        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
1937    }
1938    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1939        for (path, bytes) in files {
1940            let target = dir.join(format!("{name}.{sub}")).join(path);
1941            if let Some(parent) = target.parent() {
1942                std::fs::create_dir_all(parent)?;
1943            }
1944            std::fs::write(&target, bytes)?;
1945        }
1946    }
1947    Ok(())
1948}
1949
1950pub(crate) fn reserve_case_name(
1951    taken: &mut BTreeSet<String>,
1952    base: String,
1953    mut suffix: usize,
1954) -> String {
1955    let mut name = base.clone();
1956    while !taken.insert(name.clone()) {
1957        name = format!("{base}-{suffix}");
1958        suffix += 1;
1959    }
1960    name
1961}
1962
1963pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1964    check_timeout(opts.timeout_secs)?;
1965    let repo = opts
1966        .repo
1967        .canonical()
1968        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1969    let existing = Config::load(&repo)?;
1970    // The names the last recording wrote, and whether it wrote them to `http/` or to the CLI
1971    // folder: they are a recording's only in that folder.
1972    let (previous, previous_http) = existing
1973        .as_ref()
1974        .map(|c| (c.recorded.clone(), c.http.is_some()))
1975        .unwrap_or_default();
1976    let run = if !opts.run.is_empty() {
1977        opts.run.to_vec()
1978    } else if let Some(c) = &existing {
1979        c.run.clone()
1980    } else {
1981        bail!(
1982            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1983        );
1984    };
1985    let mut normalize = existing
1986        .as_ref()
1987        .map(|c| c.normalize.clone())
1988        .unwrap_or_default();
1989    let mut normalizers = existing
1990        .as_ref()
1991        .map(|c| c.normalizers.clone())
1992        .unwrap_or_default();
1993    for n in opts.normalize {
1994        if let Some((name, pattern)) = n.split_once('=') {
1995            normalizers.insert(name.to_string(), pattern.to_string());
1996        } else if !normalize.contains(n) {
1997            normalize.push(n.clone());
1998        }
1999    }
2000    let inferred = |run: &[String]| {
2001        app_names(&repo, run, None)
2002            .into_iter()
2003            .next()
2004            .unwrap_or_else(|| "app".to_string())
2005    };
2006    let explicit = opts.name.map(str::to_string).or_else(|| {
2007        existing
2008            .as_ref()
2009            .filter(|c| opts.run.is_empty() || c.run == opts.run || c.name != inferred(&c.run))
2010            .map(|c| c.name.clone())
2011    });
2012    let names = app_names(&repo, &run, explicit.as_deref());
2013    let timeout_secs = opts
2014        .timeout_secs
2015        .or(existing.as_ref().map(|c| c.timeout_secs))
2016        .unwrap_or_else(default_timeout);
2017    ensure!(
2018        timeout_secs >= 1,
2019        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
2020    );
2021    let mut config = Config {
2022        schema: SCHEMA.to_string(),
2023        name: explicit
2024            .or_else(|| names.first().cloned())
2025            .unwrap_or_else(|| "app".to_string()),
2026        run,
2027        normalize,
2028        normalizers,
2029        timeout_secs,
2030        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts)?,
2031        float_tolerance: match opts.float_tolerance {
2032            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
2033            None => existing.as_ref().and_then(|c| c.float_tolerance),
2034        },
2035        float_files: if opts.float_files.is_empty() {
2036            existing
2037                .as_ref()
2038                .map(|c| c.float_files.clone())
2039                .unwrap_or_default()
2040        } else {
2041            opts.float_files
2042                .iter()
2043                .map(|spec| {
2044                    let (path, format) = spec.rsplit_once('=').with_context(|| {
2045                        format!("--float-file `{spec}`: use PATH=f32le or PATH=f64le")
2046                    })?;
2047                    float_width(format)?;
2048                    Ok((path.to_string(), format.to_string()))
2049                })
2050                .collect::<Result<_>>()?
2051        },
2052        unordered: BTreeMap::new(),
2053        effects: crate::effects::EffectsConfig::merge(
2054            existing.as_ref().and_then(|c| c.effects.clone()),
2055            opts.effects.clone(),
2056        ),
2057        fresh: Vec::new(),
2058        recorded: Vec::new(),
2059    };
2060    if let Some(http) = config.http.as_mut() {
2061        if let Some(fresh) = opts.fresh {
2062            http.fresh = fresh.to_vec();
2063        }
2064    } else if let Some(fresh) = opts.fresh {
2065        config.fresh = fresh.to_vec();
2066    } else if let Some(c) = &existing {
2067        config.fresh = c.fresh.clone();
2068    }
2069    let norm = Normalizers::new(&config)?;
2070    if config.http.is_some() {
2071        let mut outcome = crate::http::record(&repo, &config, &norm, opts)?;
2072        config.unordered = unordered_of(&outcome.noise);
2073        drop_stale(&mut outcome, if previous_http { &previous } else { &[] })?;
2074        config.recorded = outcome.recorded.clone();
2075        std::fs::write(
2076            cases_dir(&repo).join(CONFIG_FILE),
2077            serde_json::to_string_pretty(&config)? + "\n",
2078        )?;
2079        if config.http.as_ref().is_some_and(|h| h.fresh.is_empty()) {
2080            let _ = std::fs::remove_dir_all(
2081                cases_dir(&repo)
2082                    .join(crate::http::HTTP_DIR)
2083                    .join(crate::http::FILES_DIR),
2084            );
2085        }
2086        return Ok(outcome);
2087    }
2088
2089    let examples = find_examples(&repo, &names);
2090    let inputs = match opts.inputs {
2091        Some(path) => read_inputs(path)?,
2092        None => Vec::new(),
2093    };
2094    let mut planned: Vec<(String, Case)> = Vec::new();
2095    let mut seen = BTreeSet::new();
2096    let mut taken = BTreeSet::new();
2097    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
2098        if !seen.insert(case.key()) {
2099            return false;
2100        }
2101        let base_name = match given {
2102            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
2103            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
2104                Some(s) => format!("{prefix}-{n:03}-{s}"),
2105                None => format!("{prefix}-{n:03}"),
2106            },
2107        };
2108        let name = reserve_case_name(&mut taken, base_name, n);
2109        planned.push((name, case));
2110        true
2111    };
2112    let mut bases = Vec::new();
2113    let mut counts = [0usize; 3];
2114    for case in examples {
2115        if push("example", counts[0] + 1, None, case.clone()) {
2116            counts[0] += 1;
2117            bases.push(case);
2118        }
2119    }
2120    for (given, case) in inputs {
2121        if push("input", counts[1] + 1, given, case.clone()) {
2122            counts[1] += 1;
2123            bases.push(case);
2124        }
2125    }
2126    if bases.is_empty() {
2127        let case = Case::new(Vec::new());
2128        push("example", 1, Some("no-args".to_string()), case.clone());
2129        bases.push(case);
2130    }
2131    let mut traps_dropped = 0usize;
2132    if opts.traps {
2133        let (traps, dropped) = trap_cases(&bases);
2134        traps_dropped = dropped;
2135        for case in traps {
2136            if push("trap", counts[2] + 1, None, case) {
2137                counts[2] += 1;
2138            }
2139        }
2140    }
2141
2142    let timeout = Duration::from_secs(config.timeout_secs);
2143    let effects = config.effects.as_ref();
2144    let base = crate::http::snapshot_to(&repo, &config.fresh, &cases_dir(&repo).join(FRESH_DIR))?;
2145    let base = base.as_deref();
2146    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
2147        let one = run_case(&config.run, &repo, case, timeout, effects, base)?;
2148        let two = run_case(&config.run, &repo, case, timeout, effects, base)?;
2149        Ok((one, two))
2150    };
2151    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2152        planned.iter().map(run_twice).collect()
2153    } else {
2154        par_map(&planned, run_twice)
2155    };
2156    let dir = cases_dir(&repo);
2157    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
2158    let mut outcome = RecordOutcome {
2159        dir: dir.clone(),
2160        run: config.run.clone(),
2161        cases: 0,
2162        examples: counts[0],
2163        inputs: counts[1],
2164        traps: counts[2],
2165        traps_dropped,
2166        noisy: Vec::new(),
2167        noise: Vec::new(),
2168        unstable: Vec::new(),
2169        timed_out: Vec::new(),
2170        recorded: Vec::new(),
2171        stale: Vec::new(),
2172        kept: Vec::new(),
2173    };
2174    for ((name, case), runs) in planned.iter().zip(runs) {
2175        let (one, two) = runs?;
2176        if one.status == Status::Timeout || two.status == Status::Timeout {
2177            outcome.timed_out.push(name.clone());
2178            continue;
2179        }
2180        let rec = settle(&norm, case, &one, &two);
2181        write_case(&dir, &config.name, name, case, &rec)?;
2182        outcome.cases += 1;
2183        outcome.recorded.push(name.clone());
2184        if !rec.noise.is_empty() {
2185            outcome.noisy.push(name.clone());
2186        }
2187        outcome
2188            .noise
2189            .extend(rec.noise.iter().map(|(field, kind)| Noise {
2190                case: name.clone(),
2191                field: field.clone(),
2192                kind: *kind,
2193            }));
2194        if rec.unstable {
2195            outcome.unstable.push(name.clone());
2196        }
2197    }
2198    config.unordered = unordered_of(&outcome.noise);
2199    drop_stale(&mut outcome, if previous_http { &[] } else { &previous })?;
2200    config.recorded = outcome.recorded.clone();
2201    std::fs::write(
2202        dir.join(CONFIG_FILE),
2203        serde_json::to_string_pretty(&config)? + "\n",
2204    )?;
2205    if config.fresh.is_empty() {
2206        let fresh_dir = dir.join(FRESH_DIR);
2207        let retained_reads = bases_read(&dir, &BTreeSet::new());
2208        let resolved = fresh_dir.canonicalize().ok();
2209        if !any_base_reads(&retained_reads, &fresh_dir, resolved.as_deref()) {
2210            let _ = std::fs::remove_dir_all(&fresh_dir);
2211        }
2212    }
2213    Ok(outcome)
2214}
2215
2216fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
2217    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
2218    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
2219        out.entry(n.case.clone()).or_default().push(n.field.clone());
2220    }
2221    out
2222}
2223
2224enum Expect {
2225    Code(i32),
2226    Failed,
2227    Killed,
2228    Skip,
2229}
2230
2231struct Spec {
2232    name: String,
2233    case: Case,
2234    stdout: Option<Vec<u8>>,
2235    stderr: Option<Vec<u8>>,
2236    effects: Option<Vec<u8>>,
2237    status: Expect,
2238    out_dir: Option<PathBuf>,
2239    removed: Option<Vec<PathBuf>>,
2240    binary: bool,
2241}
2242
2243fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
2244    walk_files(base)
2245        .into_iter()
2246        .map(|p| {
2247            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
2248            let bytes = std::fs::read(&p).unwrap_or_default();
2249            (rel, bytes)
2250        })
2251        .collect()
2252}
2253
2254fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
2255    let name = path
2256        .file_stem()
2257        .map(|s| s.to_string_lossy().into_owned())
2258        .unwrap_or_default();
2259    let text =
2260        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
2261    let doc: DocumentMut = text
2262        .parse()
2263        .with_context(|| format!("parsing {}", path.display()))?;
2264    let args = match doc.get("args") {
2265        Some(item) if item.as_array().is_some() => item
2266            .as_array()
2267            .into_iter()
2268            .flatten()
2269            .map(|v| {
2270                v.as_str()
2271                    .map(str::to_string)
2272                    .unwrap_or_else(|| v.to_string())
2273            })
2274            .collect(),
2275        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
2276        None => Vec::new(),
2277    };
2278    let mut case = Case::new(args);
2279    let side = |key: &str| -> Result<Option<Vec<u8>>> {
2280        if let Some(s) = doc.get(key).and_then(Item::as_str) {
2281            return Ok(Some(s.as_bytes().to_vec()));
2282        }
2283        let file = dir.join(format!("{name}.{key}"));
2284        Ok(if file.exists() {
2285            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
2286        } else {
2287            None
2288        })
2289    };
2290    case.stdin = side("stdin")?;
2291    if let Some(env) = doc.get("env") {
2292        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
2293        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
2294            for (k, v) in add.iter() {
2295                case.env
2296                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
2297            }
2298        }
2299        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
2300            case.env_remove = remove
2301                .iter()
2302                .filter_map(|v| v.as_str().map(str::to_string))
2303                .collect();
2304        }
2305    }
2306    let base = doc
2307        .get("fs")
2308        .and_then(|f| f.get("base"))
2309        .and_then(Item::as_str)
2310        .map(|b| dir.join(b))
2311        .unwrap_or_else(|| dir.join(format!("{name}.in")));
2312    if base.is_dir() {
2313        case.files = read_files(&base);
2314    }
2315    if let Some(remove) = doc
2316        .get("fs")
2317        .and_then(|f| f.get("remove"))
2318        .and_then(Item::as_array)
2319    {
2320        case.remove = remove
2321            .iter()
2322            .filter_map(|v| v.as_str().map(PathBuf::from))
2323            .collect();
2324    }
2325    let status = match doc.get("status") {
2326        None => Expect::Code(0),
2327        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
2328            (Some("success"), _) => Expect::Code(0),
2329            (Some("failed"), _) => Expect::Failed,
2330            (Some("interrupted"), _) => Expect::Killed,
2331            (Some("skipped"), _) => Expect::Skip,
2332            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
2333            _ => bail!("{}: unknown `status`", path.display()),
2334        },
2335    };
2336    let out_dir = dir.join(format!("{name}.out"));
2337    Ok(Spec {
2338        stdout: side("stdout")?,
2339        stderr: side("stderr")?,
2340        effects: side(crate::effects::EXT)?,
2341        status,
2342        out_dir: out_dir.is_dir().then_some(out_dir),
2343        removed: side(REMOVED_EXT)?.map(|bytes| {
2344            String::from_utf8_lossy(&bytes)
2345                .lines()
2346                .filter(|l| !l.is_empty())
2347                .map(PathBuf::from)
2348                .collect()
2349        }),
2350        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
2351        name,
2352        case,
2353    })
2354}
2355
2356fn float_width(format: &str) -> Result<usize> {
2357    match format {
2358        "f32le" => Ok(4),
2359        "f64le" => Ok(8),
2360        other => bail!("float file format `{other}`: use f32le or f64le"),
2361    }
2362}
2363
2364fn floats(bytes: &[u8], width: usize) -> Vec<f64> {
2365    bytes
2366        .chunks_exact(width)
2367        .map(|c| match c.try_into() {
2368            Ok(b) if width == 4 => f64::from(f32::from_le_bytes(b)),
2369            _ => c.try_into().map_or(f64::NAN, f64::from_le_bytes),
2370        })
2371        .collect()
2372}
2373
2374fn compare_floats(
2375    expected: &[u8],
2376    actual: &[u8],
2377    width: usize,
2378    tol: Option<f64>,
2379) -> Option<String> {
2380    if !expected.len().is_multiple_of(width) || expected.len() != actual.len() {
2381        return Some(format!(
2382            "{} values expected, {} bytes got ({} bytes per value)\n",
2383            expected.len() / width,
2384            actual.len(),
2385            width
2386        ));
2387    }
2388    let (e, a) = (floats(expected, width), floats(actual, width));
2389    let tol = tol.unwrap_or(0.0);
2390    let same =
2391        |x: f64, y: f64| x == y || (x.is_nan() && y.is_nan()) || crate::tolerance::near(x, y, tol);
2392    let off: Vec<usize> = (0..e.len()).filter(|&i| !same(e[i], a[i])).collect();
2393    let first = *off.first()?;
2394    let (mut abs, mut rel) = (0.0f64, 0.0f64);
2395    for &i in &off {
2396        let d = (e[i] - a[i]).abs();
2397        abs = abs.max(d);
2398        rel = rel.max(d / e[i].abs().max(a[i].abs()).max(f64::MIN_POSITIVE));
2399    }
2400    Some(format!(
2401        "{} of {} values differ beyond the tolerance ({tol}); first at index {first}: {} expected, {} got; max abs diff {abs:e}, max rel diff {rel:e}\n",
2402        off.len(),
2403        e.len(),
2404        e[first],
2405        a[first]
2406    ))
2407}
2408
2409pub(crate) fn compare(
2410    norm: &Normalizers,
2411    expected: &[u8],
2412    actual: &[u8],
2413    binary: bool,
2414    unordered: bool,
2415) -> Option<String> {
2416    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
2417    {
2418        let e = norm.canonical(&norm.apply(e));
2419        let a = norm.canonical(&norm.apply(a));
2420        let tol = norm.float_tolerance;
2421        if unordered {
2422            let (mut el, mut al) = (lines(&e), lines(&a));
2423            let same = lines_match_in_any_order(&el, &al, tol);
2424            el.sort_unstable();
2425            al.sort_unstable();
2426            return (!same).then(|| {
2427                format!(
2428                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
2429                    render_diff(&el.join("\n"), &al.join("\n"), tol)
2430                )
2431            });
2432        }
2433        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
2434    }
2435    (expected != actual).then(|| {
2436        format!(
2437            "binary content differs ({} bytes expected, {} bytes got)\n",
2438            expected.len(),
2439            actual.len()
2440        )
2441    })
2442}
2443
2444/// Where `compare` found the outputs to part: the first changed line and the column where its
2445/// literal text stops matching, or the first difference inside JSON; the channel is left to the
2446/// caller.
2447pub(crate) fn locate(
2448    norm: &Normalizers,
2449    expected: &[u8],
2450    actual: &[u8],
2451    binary: bool,
2452    unordered: bool,
2453) -> crate::mismatch::At {
2454    use crate::mismatch::{At, text_at};
2455    let (false, Ok(e), Ok(a)) = (
2456        binary,
2457        std::str::from_utf8(expected),
2458        std::str::from_utf8(actual),
2459    ) else {
2460        return At {
2461            expected_len: Some(expected.len()),
2462            actual_len: Some(actual.len()),
2463            ..At::new("binary")
2464        };
2465    };
2466    let e = norm.canonical(&norm.apply(e));
2467    let a = norm.canonical(&norm.apply(a));
2468    let structured = |v: &serde_json::Value| v.is_object() || v.is_array();
2469    if !unordered
2470        && let (Ok(ej), Ok(aj)) = (
2471            serde_json::from_str::<serde_json::Value>(&e),
2472            serde_json::from_str::<serde_json::Value>(&a),
2473        )
2474        && structured(&ej)
2475        && structured(&aj)
2476    {
2477        return crate::mismatch::locate_in(&ej, &aj);
2478    }
2479    let tol = norm.float_tolerance;
2480    let (mut el, mut al) = (lines(&e), lines(&a));
2481    if unordered {
2482        el.sort_unstable();
2483        al.sort_unstable();
2484    }
2485    let ops = diff_ops(&el, &al, |x, y| line_matches_within(x, y, tol));
2486    let lengths = |at: At| At {
2487        expected_len: Some(e.chars().count()),
2488        actual_len: Some(a.chars().count()),
2489        ..at
2490    };
2491    let changed = ops.iter().position(|op| !matches!(op, Op::Equal(..)));
2492    let Some(first) = changed else {
2493        let trail = |s: &str| s.ends_with('\n') || s.is_empty();
2494        let kind = if trail(&e) == trail(&a) {
2495            "text"
2496        } else {
2497            "trailing newline"
2498        };
2499        return lengths(At {
2500            line: Some(el.len().max(1)),
2501            ..At::new(kind)
2502        });
2503    };
2504    match ops[first] {
2505        Op::Delete(i) => {
2506            let insert = ops[first..]
2507                .iter()
2508                .take_while(|op| !matches!(op, Op::Equal(..)))
2509                .find_map(|op| match op {
2510                    Op::Insert(j) => Some(*j),
2511                    _ => None,
2512                });
2513            let Some(j) = insert else {
2514                return lengths(At {
2515                    line: Some(i + 1),
2516                    ..At::new("lines missing")
2517                });
2518            };
2519            let literal = el[i].split("[..]").next().unwrap_or_default();
2520            let at = text_at("text", literal, al[j]);
2521            let column = at.column.unwrap_or(1);
2522            let before: usize = el[..i].iter().map(|l| l.chars().count() + 1).sum();
2523            let before_bytes: usize = el[..i].iter().map(|l| l.len() + 1).sum();
2524            let offset = at.offset.unwrap_or_default();
2525            lengths(At {
2526                line: Some(i + 1),
2527                column: Some(column),
2528                offset: Some(crate::mismatch::Offset {
2529                    char: before + offset.char,
2530                    byte: before_bytes + offset.byte,
2531                }),
2532                context: at.context,
2533                ..At::new("text")
2534            })
2535        }
2536        Op::Insert(j) | Op::Equal(_, j) => lengths(At {
2537            line: Some(j + 1),
2538            ..At::new("lines added")
2539        }),
2540    }
2541}
2542
2543pub struct ReplayOptions<'a> {
2544    pub repo: &'a Path,
2545    /// Command line of the build to test; the original's command when `None`.
2546    pub build: Option<&'a str>,
2547    pub timeout_secs: Option<u64>,
2548    /// Servers: the port the build listens on, when it is fixed.
2549    pub port: Option<u16>,
2550    /// Replay only this case (a library: only this unit).
2551    pub case: Option<&'a str>,
2552}
2553
2554pub(crate) fn only_case<T>(
2555    items: Vec<T>,
2556    case: Option<&str>,
2557    name: impl Fn(&T) -> &str,
2558) -> Result<Vec<T>> {
2559    let Some(case) = case else {
2560        return Ok(items);
2561    };
2562    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
2563    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
2564    ensure!(
2565        !kept.is_empty(),
2566        "no case named {case}; the cases are: {}",
2567        names.join(", ")
2568    );
2569    Ok(kept)
2570}
2571
2572#[derive(Debug, Serialize)]
2573pub struct Problem {
2574    pub field: String,
2575    pub detail: String,
2576    /// Where the output first differs.
2577    #[serde(skip_serializing_if = "Option::is_none")]
2578    pub at: Option<crate::mismatch::At>,
2579}
2580
2581impl Problem {
2582    pub fn new(field: impl Into<String>, detail: impl Into<String>) -> Problem {
2583        Problem {
2584            field: field.into(),
2585            detail: detail.into(),
2586            at: None,
2587        }
2588    }
2589
2590    /// With the first difference, its channel the field when it has none.
2591    pub fn at(mut self, mut at: crate::mismatch::At) -> Problem {
2592        if at.channel.is_empty() {
2593            at.channel.clone_from(&self.field);
2594        }
2595        self.at = Some(at);
2596        self
2597    }
2598}
2599
2600#[derive(Debug, Serialize)]
2601pub struct Failure {
2602    pub case: String,
2603    pub args: Vec<String>,
2604    pub problems: Vec<Problem>,
2605}
2606
2607/// Cases the build handed to the original: the front door appends a line to the file named by
2608/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
2609#[derive(Debug, Serialize)]
2610pub struct Fallback {
2611    pub cases: usize,
2612    pub total: usize,
2613    pub rate: f64,
2614    /// The cases that fell back.
2615    pub names: Vec<String>,
2616}
2617
2618#[derive(Debug, Serialize)]
2619pub struct ReplayOutcome {
2620    pub build: Vec<String>,
2621    pub passed: usize,
2622    pub total: usize,
2623    pub skipped: usize,
2624    pub failures: Vec<Failure>,
2625    pub fallback: Option<Fallback>,
2626    pub report: PathBuf,
2627    /// The distinct differences among the failing cases, most cases first.
2628    #[serde(skip_serializing_if = "Vec::is_empty")]
2629    pub groups: Vec<crate::mismatch::Group>,
2630}
2631
2632fn check(
2633    norm: &Normalizers,
2634    command: &[String],
2635    repo: &Path,
2636    spec: &Spec,
2637    timeout: Duration,
2638    effects: Option<&crate::effects::EffectsConfig>,
2639    base: Option<&Path>,
2640) -> Result<(Vec<Problem>, Option<bool>)> {
2641    let run = run_case(command, repo, &spec.case, timeout, effects, base)?;
2642    let mut problems = Vec::new();
2643    let status_ok = match (&spec.status, &run.status) {
2644        (Expect::Code(e), Status::Code(a)) => e == a,
2645        (Expect::Failed, Status::Code(a)) => *a != 0,
2646        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
2647        _ => false,
2648    };
2649    if !status_ok {
2650        let expected = match &spec.status {
2651            Expect::Code(c) => format!("exit code {c}"),
2652            Expect::Failed => "a non-zero exit code".to_string(),
2653            Expect::Killed => "killed by a signal".to_string(),
2654            Expect::Skip => String::new(),
2655        };
2656        let short = |s: &str| s.trim_start_matches("exit code ").to_string();
2657        let kind = match &spec.status {
2658            Expect::Failed => "non-zero".to_string(),
2659            Expect::Killed => "killed".to_string(),
2660            _ => short(&expected),
2661        } + "→"
2662            + &match run.status {
2663                Status::Killed => "killed".to_string(),
2664                Status::Timeout => "timeout".to_string(),
2665                Status::Code(c) => c.to_string(),
2666            };
2667        problems.push(
2668            Problem::new(
2669                "status",
2670                format!("expected {expected}, got {}\n", run.status),
2671            )
2672            .at(crate::mismatch::At::new(&kind)),
2673        );
2674    }
2675    let no_effects = Vec::new();
2676    for (field, expected, actual) in [
2677        ("stdout", &spec.stdout, &run.stdout),
2678        ("stderr", &spec.stderr, &run.stderr),
2679        (
2680            crate::effects::EXT,
2681            &spec.effects,
2682            run.effects.as_ref().unwrap_or(&no_effects),
2683        ),
2684    ] {
2685        let unordered = norm.unordered(&spec.name, field);
2686        if let Some(expected) = expected
2687            && let Some(detail) = compare(norm, expected, actual, spec.binary, unordered)
2688        {
2689            problems.push(Problem::new(field, detail).at(locate(
2690                norm,
2691                expected,
2692                actual,
2693                spec.binary,
2694                unordered,
2695            )));
2696        }
2697    }
2698    if let Some(expected) = &spec.removed
2699        && *expected != run.removed
2700    {
2701        let list = |paths: &[PathBuf]| -> String {
2702            paths
2703                .iter()
2704                .map(|p| format!("  {}\n", p.display()))
2705                .collect()
2706        };
2707        problems.push(
2708            Problem::new(
2709                "removed files",
2710                format!(
2711                    "expected removed:\n{}got removed:\n{}",
2712                    list(expected),
2713                    list(&run.removed)
2714                ),
2715            )
2716            .at(crate::mismatch::At {
2717                expected_len: Some(expected.len()),
2718                actual_len: Some(run.removed.len()),
2719                ..crate::mismatch::At::new("value")
2720            }),
2721        );
2722    }
2723    if let Some(out_dir) = &spec.out_dir {
2724        for (path, expected) in read_files(out_dir) {
2725            let field = format!("file {}", path.display());
2726            match run.files.get(&path) {
2727                None => problems.push(
2728                    Problem::new(field, "not written\n")
2729                        .at(crate::mismatch::At::new("not written")),
2730                ),
2731                Some(actual) => {
2732                    let unordered = norm.unordered(&spec.name, &field);
2733                    let width = norm.float_files.get(&path).copied();
2734                    let detail = match width {
2735                        Some(width) => {
2736                            compare_floats(&expected, actual, width, norm.float_tolerance)
2737                        }
2738                        None => compare(norm, &expected, actual, false, unordered),
2739                    };
2740                    if let Some(detail) = detail {
2741                        let at = match width {
2742                            Some(_) => crate::mismatch::At::new("value"),
2743                            None => locate(norm, &expected, actual, false, unordered),
2744                        };
2745                        problems.push(Problem::new(field, detail).at(at));
2746                    }
2747                }
2748            }
2749        }
2750    }
2751    Ok((problems, run.fallback))
2752}
2753
2754pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
2755    stable_paths(&report_body(outcome))
2756}
2757
2758/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
2759/// same file and CI can commit it and fail on `git diff --exit-code`.
2760pub(crate) fn stable_paths(text: &str) -> String {
2761    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
2762    let tmp = std::env::temp_dir();
2763    let tmp = tmp.to_string_lossy();
2764    let tmp = tmp.trim_end_matches(['/', '\\']);
2765    let text = if tmp.len() > 1 {
2766        text.replace(tmp, "$TMPDIR")
2767    } else {
2768        text.to_string()
2769    };
2770    SANDBOX
2771        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
2772        .replace_all(&text, "rust-anything-app-$1")
2773        .into_owned()
2774}
2775
2776fn report_body(outcome: &ReplayOutcome) -> String {
2777    let mut out = String::from("# App replay\n\n");
2778    out += &format!(
2779        "Build: `{}`\n\n",
2780        outcome
2781            .build
2782            .iter()
2783            .map(|w| shell_quote(w))
2784            .collect::<Vec<_>>()
2785            .join(" ")
2786    );
2787    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
2788    if outcome.skipped > 0 {
2789        out += &format!("Skipped: {}\n\n", outcome.skipped);
2790    }
2791    out += &match &outcome.fallback {
2792        Some(f) => format!(
2793            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
2794            f.rate * 100.0,
2795            f.cases,
2796            f.total
2797        ),
2798        None => "Fallback rate: not reported by this build\n\n".to_string(),
2799    };
2800    if outcome.failures.is_empty() {
2801        out += "Every case matches.\n";
2802        return out;
2803    }
2804    if !outcome.groups.is_empty() {
2805        out += "## Distinct differences\n\n| Cases | Id | Where | Kind |\n| ---: | --- | --- | --- |\n";
2806        for g in &outcome.groups {
2807            let place = match &g.path {
2808                Some(path) => format!("{} {path}", g.channel),
2809                None => g.channel.clone(),
2810            };
2811            out += &format!(
2812                "| {} | `{}` | `{}` | {} |\n",
2813                g.cases,
2814                g.id,
2815                place.replace('`', "'").replace('|', "\\|"),
2816                g.kind
2817            );
2818        }
2819        out += "\n";
2820    }
2821    out += "## Failing cases\n";
2822    for f in &outcome.failures {
2823        out += &format!(
2824            "\n### {}\n\nArguments: `{}`\n",
2825            f.case,
2826            f.args
2827                .iter()
2828                .map(|w| shell_quote(w))
2829                .collect::<Vec<_>>()
2830                .join(" ")
2831        );
2832        for p in &f.problems {
2833            if let Some(at) = &p.at {
2834                out += &format!("\n{}\n", at.describe().replace("```", "`\u{200b}``"));
2835            }
2836            out += &format!(
2837                "\n{}:\n\n```diff\n{}```\n",
2838                p.field,
2839                p.detail.replace("```", "`\u{200b}``")
2840            );
2841        }
2842    }
2843    out
2844}
2845
2846fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2847    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2848        .with_context(|| {
2849            format!(
2850                "no cases in {}: run `rust-anything app record` first",
2851                dir.display()
2852            )
2853        })?
2854        .flatten()
2855        .map(|e| e.path())
2856        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2857        .collect();
2858    paths.sort();
2859    let specs = paths
2860        .iter()
2861        .map(|p| load_spec(dir, p))
2862        .collect::<Result<Vec<_>>>()?;
2863    ensure!(
2864        !specs.is_empty(),
2865        "no cases in {}: run `rust-anything app record` first",
2866        dir.display()
2867    );
2868    Ok(specs)
2869}
2870
2871/// The recorded cases' arguments, each with whether the original exited 0.
2872pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
2873    Ok(load_specs(&cases_dir(repo))?
2874        .into_iter()
2875        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
2876        .collect())
2877}
2878
2879pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2880    write_report(replay_unwritten(opts)?)
2881}
2882
2883/// `replay` with `--redact`: the report is only ever written as shapes.
2884pub fn replay_redacted(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2885    redacted(replay_unwritten(opts)?)
2886}
2887
2888/// Writes the outcome's report (`replay-report.md`).
2889pub(crate) fn write_report(outcome: ReplayOutcome) -> Result<ReplayOutcome> {
2890    std::fs::write(&outcome.report, report_markdown(&outcome))
2891        .with_context(|| format!("writing {}", outcome.report.display()))?;
2892    Ok(outcome)
2893}
2894
2895/// The outcome as shapes only (`--redact`), its report written again from them.
2896pub fn redacted(mut outcome: ReplayOutcome) -> Result<ReplayOutcome> {
2897    crate::mismatch::redact_replay(&mut outcome);
2898    write_report(outcome)
2899}
2900
2901/// The outcome with its distinct differences counted.
2902pub(crate) fn grouped(mut outcome: ReplayOutcome) -> ReplayOutcome {
2903    outcome.groups = crate::mismatch::replay_groups(&outcome.failures);
2904    outcome
2905}
2906
2907/// `replay` without writing the report, for a caller that must leave the last one in place.
2908pub(crate) fn replay_unwritten(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2909    replay_cases(opts).map(grouped)
2910}
2911
2912fn replay_cases(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2913    check_timeout(opts.timeout_secs)?;
2914    let repo = opts
2915        .repo
2916        .canonical()
2917        .with_context(|| format!("no folder {}", opts.repo.display()))?;
2918    let dir = cases_dir(&repo);
2919    let config = Config::load(&repo)?;
2920    if config.is_none()
2921        && let Ok(state) = crate::front_door::State::load(&repo)
2922        && state.kind == crate::front_door::AppKind::Library
2923    {
2924        ensure!(
2925            opts.build.is_none(),
2926            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
2927            state.name
2928        );
2929        return crate::library::replay_unwritten(&repo, &state, opts.case);
2930    }
2931    let command = match (opts.build, &config) {
2932        (Some(build), _) => shell_split(build)?,
2933        (None, Some(c)) => c.run.clone(),
2934        (None, None) => bail!(
2935            "no {} in {}: run `rust-anything app record` first, or pass --build",
2936            CONFIG_FILE,
2937            dir.display()
2938        ),
2939    };
2940    ensure!(!command.is_empty(), "the build command is empty");
2941    let config = config.unwrap_or_else(|| Config {
2942        schema: SCHEMA.to_string(),
2943        name: "app".to_string(),
2944        run: Vec::new(),
2945        normalize: Vec::new(),
2946        normalizers: BTreeMap::new(),
2947        timeout_secs: default_timeout(),
2948        http: None,
2949        float_tolerance: None,
2950        float_files: BTreeMap::new(),
2951        unordered: BTreeMap::new(),
2952        effects: None,
2953        fresh: Vec::new(),
2954        recorded: Vec::new(),
2955    });
2956    let norm = Normalizers::new(&config)?;
2957    let timeout_secs = opts.timeout_secs.unwrap_or(config.timeout_secs);
2958    ensure!(
2959        timeout_secs >= 1,
2960        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
2961    );
2962    let timeout = Duration::from_secs(timeout_secs);
2963    if config.http.is_some() {
2964        return crate::http::replay(
2965            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2966        );
2967    }
2968    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2969    let effects = config.effects.as_ref();
2970    let base = if config.fresh.is_empty() {
2971        None
2972    } else {
2973        let base = dir.join(FRESH_DIR);
2974        ensure!(
2975            base.is_dir(),
2976            "no {}: record again to snapshot the fresh files",
2977            base.display()
2978        );
2979        Some(base)
2980    };
2981    let check_one = |spec: &Spec| {
2982        if matches!(spec.status, Expect::Skip) {
2983            return Ok((Vec::new(), None));
2984        }
2985        check(
2986            &norm,
2987            &command,
2988            &repo,
2989            spec,
2990            timeout,
2991            effects,
2992            base.as_deref(),
2993        )
2994    };
2995    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2996        specs.iter().map(check_one).collect()
2997    } else {
2998        par_map(&specs, check_one)
2999    };
3000    let mut outcome = ReplayOutcome {
3001        build: command.clone(),
3002        passed: 0,
3003        total: 0,
3004        skipped: 0,
3005        failures: Vec::new(),
3006        fallback: None,
3007        report: dir.join(REPORT_FILE),
3008        groups: Vec::new(),
3009    };
3010    let (mut reported, mut fell_back) = (false, Vec::new());
3011    for (spec, result) in specs.iter().zip(results) {
3012        if matches!(spec.status, Expect::Skip) {
3013            outcome.skipped += 1;
3014            continue;
3015        }
3016        let (problems, fallback) = result?;
3017        outcome.total += 1;
3018        reported |= fallback.is_some();
3019        if fallback == Some(true) {
3020            fell_back.push(spec.name.clone());
3021        }
3022        if problems.is_empty() {
3023            outcome.passed += 1;
3024        } else {
3025            outcome.failures.push(Failure {
3026                case: spec.name.clone(),
3027                args: spec.case.args.clone(),
3028                problems,
3029            });
3030        }
3031    }
3032    if reported {
3033        outcome.fallback = Some(Fallback {
3034            cases: fell_back.len(),
3035            total: outcome.total,
3036            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
3037            names: fell_back,
3038        });
3039    }
3040    Ok(outcome)
3041}
3042
3043#[cfg(test)]
3044mod tests {
3045    use super::*;
3046
3047    #[test]
3048    fn shell_quote_leaves_plain_words_and_quotes_the_rest() {
3049        for plain in [
3050            "cargo",
3051            "./target/release/app",
3052            "a=b",
3053            "--flag",
3054            "user@host:1,2+3%",
3055        ] {
3056            assert_eq!(shell_quote(plain), plain);
3057        }
3058        assert_eq!(shell_quote(""), "''");
3059        assert_eq!(shell_quote("my app/bin"), "'my app/bin'");
3060        assert_eq!(shell_quote("it's"), r"'it'\''s'");
3061        assert_eq!(shell_quote("$HOME"), "'$HOME'");
3062        assert_eq!(shell_quote("*.rs"), "'*.rs'");
3063        assert_eq!(shell_quote("a;b"), "'a;b'");
3064    }
3065
3066    #[test]
3067    fn given_names_keep_their_tail() {
3068        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
3069        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
3070        assert_ne!(a, b);
3071        assert_eq!(
3072            a,
3073            "tests-format-typescript-conformance-types-never-never-ts"
3074        );
3075        assert_eq!(slug(&a).len(), 23);
3076    }
3077
3078    #[test]
3079    fn reports_do_not_carry_sandbox_paths() {
3080        let tmp = std::env::temp_dir();
3081        let line = format!(
3082            "-cwd {}\n",
3083            tmp.join("rust-anything-app-run-4242-7")
3084                .join("cwd")
3085                .display()
3086        );
3087        let stable = stable_paths(&line);
3088        assert!(!stable.contains("4242"), "{stable}");
3089        assert!(stable.contains("$TMPDIR"), "{stable}");
3090        assert_eq!(
3091            stable,
3092            stable_paths(&line.replace("4242-7", "99-0")),
3093            "{stable}"
3094        );
3095    }
3096
3097    fn text_matches_exact(e: &str, a: &str) -> bool {
3098        text_matches(e, a, None)
3099    }
3100
3101    fn norm_with_tolerance(tol: Option<f64>) -> Normalizers {
3102        Normalizers::new(&Config {
3103            schema: SCHEMA.to_string(),
3104            name: "app".to_string(),
3105            run: Vec::new(),
3106            normalize: Vec::new(),
3107            normalizers: BTreeMap::new(),
3108            timeout_secs: default_timeout(),
3109            http: None,
3110            float_tolerance: tol,
3111            float_files: BTreeMap::new(),
3112            unordered: BTreeMap::new(),
3113            effects: None,
3114            fresh: Vec::new(),
3115            recorded: Vec::new(),
3116        })
3117        .unwrap()
3118    }
3119
3120    #[test]
3121    fn unordered_lines_pair_up_by_value_within_the_tolerance() {
3122        let norm = norm_with_tolerance(Some(1e-9));
3123        // `2.0` meets `2.0` and `10.0` meets `9.999999999999999`, but `10.0` sorts before `2.0`
3124        // as text, so pairing the sorted lines by position compared `10.0` against `2.0`.
3125        let expected = b"n 2.0\nn 10.0\n";
3126        let actual = b"n 2.0\nn 9.999999999999999\n";
3127        assert!(compare(&norm, expected, actual, false, false).is_none());
3128        assert!(compare(&norm, expected, actual, false, true).is_none());
3129        // A line that is genuinely different is still reported.
3130        let changed = b"n 2.0\nn 11.0\n";
3131        assert!(compare(&norm, expected, changed, false, true).is_some());
3132        // The order the lines arrive in does not matter.
3133        let swapped = b"n 9.999999999999999\nn 2.0\n";
3134        assert!(compare(&norm, expected, swapped, false, true).is_none());
3135    }
3136
3137    #[test]
3138    fn unordered_lines_pair_up_around_a_wildcard() {
3139        let norm = norm_with_tolerance(Some(1e-9));
3140        // `[..]` takes the line the numeric pairing does not want, so a tolerance and a wildcard
3141        // in the same output do not fight over the ordering.
3142        let expected = b"n 10.0\nn [..]\n";
3143        assert!(compare(&norm, expected, b"n 10.0\nn 2.0\n", false, true).is_none());
3144        assert!(compare(&norm, expected, b"n 2.0\nn 10.0\n", false, true).is_none());
3145        assert!(
3146            compare(
3147                &norm,
3148                expected,
3149                b"n 2.0\nn 9.999999999999999\n",
3150                false,
3151                true
3152            )
3153            .is_none()
3154        );
3155        // Nothing to take the 10.0: both actual lines are far from it.
3156        assert!(compare(&norm, expected, b"n 2.0\nn 3.0\n", false, true).is_some());
3157    }
3158
3159    #[test]
3160    fn unordered_lines_keep_a_plain_permutation_matching() {
3161        let norm = norm_with_tolerance(Some(1e-9));
3162        // The same lines in another order match whatever the numbers look like, and a value
3163        // written two ways stays a difference rather than becoming one by being re-sorted.
3164        assert!(compare(&norm, b"n 2\nn 2.0\n", b"n 2.0\nn 2\n", false, true).is_none());
3165        assert!(compare(&norm, b"n 2\nn 2\n", b"n 2.0\nn 2.0\n", false, true).is_some());
3166    }
3167
3168    #[test]
3169    fn unordered_lines_without_a_tolerance_still_compare_as_text() {
3170        let norm = norm_with_tolerance(None);
3171        let expected = b"b\na\n";
3172        assert!(compare(&norm, expected, b"a\nb\n", false, true).is_none());
3173        assert!(compare(&norm, expected, b"a\nc\n", false, true).is_some());
3174        assert!(compare(&norm, expected, b"a\n", false, true).is_some());
3175        // Without a tolerance a number is text like any other, so this stays a mismatch.
3176        let numeric = b"n 10.0\nn 2.0\n";
3177        assert!(compare(&norm, numeric, b"n 2.0\nn 9.999999999999999\n", false, true).is_some());
3178    }
3179
3180    #[cfg(unix)]
3181    #[test]
3182    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
3183        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
3184            let command = ["/bin/sh".into(), "-c".into(), script.into()];
3185            let start = Instant::now();
3186            let run = run_case(
3187                &command,
3188                Path::new("."),
3189                &Case::new(Vec::new()),
3190                Duration::from_millis(200),
3191                None,
3192                None,
3193            )
3194            .unwrap();
3195            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
3196            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
3197        }
3198    }
3199
3200    #[test]
3201    fn matching_follows_trycmd() {
3202        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
3203        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
3204        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
3205        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
3206        assert!(text_matches_exact(
3207            "head\n...\ntail\n",
3208            "head\n1\n2\ntail\n"
3209        ));
3210        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
3211        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
3212        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
3213    }
3214
3215    #[test]
3216    fn numbers_match_within_the_tolerance() {
3217        let e = "step 1\nenergy 0.3\nat [..]\n";
3218        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
3219        assert!(!text_matches(e, a, None));
3220        assert!(text_matches(e, a, Some(1e-9)));
3221        assert!(!text_matches(
3222            e,
3223            "step 2\nenergy 0.3\nat 12:00\n",
3224            Some(1e-9)
3225        ));
3226        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
3227    }
3228
3229    #[cfg(unix)]
3230    #[test]
3231    fn binary_capture_replays_its_text_companion_byte_for_byte() {
3232        let repo = temp_dir("binary-stream-pair").unwrap();
3233        let run = [
3234            "/bin/sh".to_string(),
3235            "-c".to_string(),
3236            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
3237        ];
3238        let recorded = record(&RecordOptions {
3239            repo: &repo,
3240            run: &run,
3241            inputs: None,
3242            normalize: &["timestamps".into()],
3243            name: None,
3244            traps: false,
3245            timeout_secs: None,
3246            http: None,
3247            server_args: None,
3248            fresh: None,
3249            pace_ms: None,
3250            port: None,
3251            float_tolerance: None,
3252            float_files: &[],
3253            effects: None,
3254            ready_secs: None,
3255        })
3256        .unwrap();
3257        assert_eq!(recorded.cases, 1);
3258        let replayed = replay(&ReplayOptions {
3259            repo: &repo,
3260            build: None,
3261            timeout_secs: None,
3262            port: None,
3263            case: None,
3264        })
3265        .unwrap();
3266        assert_eq!(
3267            (replayed.passed, replayed.total),
3268            (1, 1),
3269            "{:?}",
3270            replayed.failures
3271        );
3272        std::fs::remove_dir_all(repo).unwrap();
3273    }
3274
3275    #[test]
3276    fn noise_is_classified() {
3277        let norm = Normalizers::new(&Config {
3278            schema: SCHEMA.to_string(),
3279            name: "app".to_string(),
3280            run: Vec::new(),
3281            normalize: Vec::new(),
3282            normalizers: BTreeMap::new(),
3283            timeout_secs: 30,
3284            http: None,
3285            float_tolerance: None,
3286            float_files: BTreeMap::new(),
3287            unordered: BTreeMap::new(),
3288            effects: None,
3289            fresh: Vec::new(),
3290            recorded: Vec::new(),
3291        })
3292        .unwrap();
3293        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
3294        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
3295        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
3296        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
3297        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
3298        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
3299        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
3300    }
3301
3302    #[test]
3303    fn unordered_output_matches_in_any_order_but_not_other_lines() {
3304        let norm = Normalizers::new(&Config {
3305            schema: SCHEMA.to_string(),
3306            name: "app".to_string(),
3307            run: Vec::new(),
3308            normalize: Vec::new(),
3309            normalizers: BTreeMap::new(),
3310            timeout_secs: 30,
3311            http: None,
3312            float_tolerance: None,
3313            float_files: BTreeMap::new(),
3314            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
3315            effects: None,
3316            fresh: Vec::new(),
3317            recorded: Vec::new(),
3318        })
3319        .unwrap();
3320        assert!(norm.unordered("c", "stdout"));
3321        assert!(!norm.unordered("c", "stderr"));
3322        let e = b"x=1\ny=2\n";
3323        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
3324        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
3325        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
3326        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
3327    }
3328
3329    #[test]
3330    fn timestamps_cover_javascript_date_strings() {
3331        let re = Regex::new(TIMESTAMP).unwrap();
3332        let line = "Generated on Sat Nov 21 2026 01:30:12 GMT+0300 (Türkiye Standard Time) - ok";
3333        assert_eq!(re.replace_all(line, "[..]"), "Generated on [..] - ok");
3334        assert_eq!(
3335            re.replace_all("Mon Jan 05 2026 09:00:00 GMT-0800", "[..]"),
3336            "[..]"
3337        );
3338        assert_eq!(re.replace_all("at 2026-11-16T10:00:00Z", "[..]"), "at [..]");
3339        assert_eq!(re.replace_all("Saturday 12", "[..]"), "Saturday 12");
3340    }
3341
3342    #[test]
3343    fn noise_becomes_wildcards() {
3344        assert_eq!(
3345            merge_noise(
3346                "start\nnow: 2026-11-16 10:00:01\nend\n",
3347                "start\nnow: 2026-11-16 10:00:02\nend\n"
3348            ),
3349            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
3350        );
3351        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
3352        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
3353        let merged = merge_noise("x 1\n", "x 2\n");
3354        assert!(text_matches_exact(&merged, "x 3\n"));
3355    }
3356
3357    #[test]
3358    fn normalizers_by_name() {
3359        let mut config = Config {
3360            schema: SCHEMA.to_string(),
3361            name: "app".to_string(),
3362            run: Vec::new(),
3363            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
3364            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
3365            timeout_secs: 30,
3366            http: None,
3367            float_tolerance: None,
3368            float_files: BTreeMap::new(),
3369            unordered: BTreeMap::new(),
3370            effects: None,
3371            fresh: Vec::new(),
3372            recorded: Vec::new(),
3373        };
3374        let norm = Normalizers::new(&config).unwrap();
3375        assert_eq!(
3376            norm.apply(
3377                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
3378            ),
3379            "at [..] id [..] [..]"
3380        );
3381        assert_eq!(
3382            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
3383            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
3384        );
3385        config.normalize.push("nope".into());
3386        assert!(Normalizers::new(&config).is_err());
3387    }
3388
3389    #[test]
3390    fn examples_become_cases() {
3391        let repo = temp_dir("examples").unwrap();
3392        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
3393        std::fs::write(
3394            repo.join("README.md"),
3395            "# 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",
3396        )
3397        .unwrap();
3398        let names = vec!["tool".to_string()];
3399        let cases = find_examples(&repo, &names);
3400        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
3401        assert_eq!(
3402            args,
3403            [
3404                vec!["count", "in.txt"],
3405                vec!["words"],
3406                vec!["upper", "x y"],
3407                vec!["sort"],
3408            ]
3409        );
3410        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
3411        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
3412        assert_eq!(cases[2].env["LANG"], "C");
3413        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
3414        std::fs::remove_dir_all(&repo).unwrap();
3415    }
3416
3417    #[test]
3418    fn examples_continued_with_a_backslash_are_joined() {
3419        let repo = temp_dir("continued-examples").unwrap();
3420        std::fs::write(
3421            repo.join("README.md"),
3422            "```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",
3423        )
3424        .unwrap();
3425        std::fs::write(
3426            repo.join("demo.sh"),
3427            "tool sort \\\n  --reverse\n# tool hidden \\\ntool count c.txt\n",
3428        )
3429        .unwrap();
3430        let names = vec!["tool".to_string()];
3431        let args: Vec<Vec<String>> = find_examples(&repo, &names)
3432            .iter()
3433            .map(|c| c.args.clone())
3434            .collect();
3435        std::fs::remove_dir_all(&repo).unwrap();
3436        // Not continuations: a doubled backslash (a literal one), a backslash followed by a space,
3437        // and a backslash at the end of a comment. Joining adds no space of its own (`--mode=loud`).
3438        assert_eq!(
3439            args,
3440            [
3441                vec!["upper", "--loud", "x y"],
3442                vec!["path", "C:\\"],
3443                vec!["count", "in.txt"],
3444                vec!["upper", "--mode=loud"],
3445                vec!["echo", "a "],
3446                vec!["count", "b.txt"],
3447                vec!["sort", "--reverse"],
3448                vec!["count", "c.txt"],
3449            ]
3450        );
3451    }
3452
3453    #[test]
3454    fn traps_keep_the_shape_of_the_case() {
3455        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
3456        base.stdin = Some(b"{\"a\":1}".to_vec());
3457        let (traps, dropped) = trap_cases(&[base]);
3458        assert_eq!(dropped, 0);
3459        assert!(traps.iter().all(|c| c.args[0] == "div"));
3460        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
3461        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
3462        assert!(
3463            traps
3464                .iter()
3465                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
3466        );
3467        let (text, dropped_text) = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
3468        assert_eq!(dropped_text, 0);
3469        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
3470    }
3471
3472    #[test]
3473    fn traps_spread_round_robin_deduplicate_before_truncating_and_count_dropped() {
3474        // 40 distinct commands, each with an int and a string arg -> > 300 unique traps.
3475        let mut bases: Vec<Case> = (0..40)
3476            .map(|i| Case::new(vec![format!("cmd{i:02}"), "7".into(), "hi".into()]))
3477            .collect();
3478        let (unique_traps, unique_dropped) = trap_cases(&bases);
3479        // Adding a duplicate base whose traps all collide must not change the kept traps or
3480        // inflate `dropped`.
3481        bases.push(bases[0].clone());
3482        let (traps, dropped) = trap_cases(&bases);
3483
3484        assert_eq!(unique_traps.len(), MAX_TRAPS);
3485        assert!(unique_dropped > 0);
3486        assert_eq!(traps.len(), MAX_TRAPS);
3487        assert_eq!(dropped, unique_dropped);
3488
3489        // Every single one of the 40 commands gets traps (not just the first few).
3490        for i in 0..40 {
3491            let cmd = format!("cmd{i:02}");
3492            let count = unique_traps.iter().filter(|c| c.args[0] == cmd).count();
3493            assert!(
3494                count >= 7,
3495                "{cmd} only got {count} traps out of {MAX_TRAPS}"
3496            );
3497        }
3498
3499        // Many bases with colliding traps (> 300 raw traps, < 300 unique) must deduplicate
3500        // before truncating so nothing is dropped and unique traps from later bases survive.
3501        let mut dup_bases: Vec<Case> = (1..=40)
3502            .map(|i| Case::new(vec!["dup".into(), i.to_string()]))
3503            .collect();
3504        dup_bases.push(Case::new(vec!["tail".into(), "hello".into()]));
3505        let (dup_traps, dup_dropped) = trap_cases(&dup_bases);
3506        assert_eq!(dup_dropped, 0);
3507        assert!(dup_traps.iter().any(|c| c.args[0] == "tail"));
3508        let keys: BTreeSet<_> = dup_traps.iter().map(Case::key).collect();
3509        assert_eq!(keys.len(), dup_traps.len());
3510    }
3511
3512    #[cfg(unix)]
3513    #[test]
3514    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
3515        let repo = temp_dir("case-name-collisions").unwrap();
3516        let inputs = repo.join("cases.jsonl");
3517        std::fs::write(
3518            &inputs,
3519            concat!(
3520                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
3521                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
3522                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
3523            ),
3524        )
3525        .unwrap();
3526        let recorded = record(&RecordOptions {
3527            repo: &repo,
3528            run: &["/bin/echo".into()],
3529            inputs: Some(&inputs),
3530            normalize: &[],
3531            name: None,
3532            traps: false,
3533            timeout_secs: None,
3534            http: None,
3535            server_args: None,
3536            fresh: None,
3537            pace_ms: None,
3538            port: None,
3539            float_tolerance: None,
3540            float_files: &[],
3541            effects: None,
3542            ready_secs: None,
3543        })
3544        .unwrap();
3545        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
3546        assert_eq!(recorded.cases, 3);
3547        assert_eq!(read("x.stdout"), "one\n");
3548        assert_eq!(read("x-3.stdout"), "two\n");
3549        assert_eq!(read("x-4.stdout"), "three\n");
3550        std::fs::remove_dir_all(repo).unwrap();
3551    }
3552
3553    #[cfg(unix)]
3554    #[test]
3555    fn a_new_run_command_renames_an_inferred_name_but_keeps_a_given_one() {
3556        let repo = temp_dir("rename-on-new-run").unwrap();
3557        std::fs::write(repo.join("one.sh"), "echo one\n").unwrap();
3558        std::fs::write(repo.join("two.sh"), "echo two\n").unwrap();
3559        let rec = |script: &str, name: Option<&str>| {
3560            let run = ["/bin/sh".to_string(), script.to_string()];
3561            record(&RecordOptions {
3562                repo: &repo,
3563                run: &run,
3564                inputs: None,
3565                normalize: &[],
3566                name,
3567                traps: false,
3568                timeout_secs: None,
3569                http: None,
3570                server_args: None,
3571                fresh: None,
3572                pace_ms: None,
3573                port: None,
3574                float_tolerance: None,
3575                float_files: &[],
3576                effects: None,
3577                ready_secs: None,
3578            })
3579            .unwrap();
3580            Config::load(&repo).unwrap().unwrap().name
3581        };
3582        assert_eq!(rec("one.sh", None), "one");
3583        assert_eq!(rec("two.sh", None), "two");
3584        assert_eq!(rec("two.sh", Some("mytool")), "mytool");
3585        assert_eq!(rec("one.sh", None), "mytool");
3586        std::fs::remove_dir_all(&repo).unwrap();
3587    }
3588
3589    #[test]
3590    fn names_come_from_the_run_command_and_manifests() {
3591        let repo = temp_dir("names").unwrap();
3592        std::fs::create_dir_all(repo.join("out")).unwrap();
3593        std::fs::write(
3594            repo.join("package.json"),
3595            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
3596        )
3597        .unwrap();
3598        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
3599        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
3600        std::fs::remove_dir_all(&repo).unwrap();
3601    }
3602
3603    #[test]
3604    fn python_program_names_are_case_insensitive() {
3605        assert!(is_python_program("PYTHON"));
3606        assert!(is_python_program("/tools/Python3.exe"));
3607        assert!(is_python_program("Py.cmd"));
3608        assert!(!is_python_program("pythonw.exe"));
3609    }
3610
3611    #[test]
3612    fn shell_words() {
3613        assert_eq!(
3614            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
3615            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
3616        );
3617        assert!(shell_split("a | b").is_err());
3618        assert!(shell_tokens("echo $(date)").is_none());
3619        assert!(shell_tokens("echo `date`").is_none());
3620        assert_eq!(
3621            shell_split(r"echo \$(date) \`date\`").unwrap(),
3622            ["echo", "$(date)", "`date`"]
3623        );
3624        #[cfg(windows)]
3625        assert_eq!(
3626            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
3627            [r"C:\tools\rust-anything\app.exe", "--flag"]
3628        );
3629        #[cfg(windows)]
3630        assert_eq!(
3631            shell_split(r"run C:\$cache\tool.exe").unwrap(),
3632            ["run", r"C:\$cache\tool.exe"]
3633        );
3634        #[cfg(windows)]
3635        assert_eq!(
3636            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
3637            [r"\\server\share\tool.exe", "--flag"]
3638        );
3639        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
3640    }
3641
3642    #[test]
3643    fn record_and_replay_reject_zero_timeout_and_leave_cases_untouched() {
3644        let repo = temp_dir("zero-timeout").unwrap();
3645        let dir = cases_dir(&repo);
3646        std::fs::create_dir_all(&dir).unwrap();
3647        let sentinel_cfg = format!(
3648            r#"{{"schema":"{SCHEMA}","name":"app","run":["echo","ok"],"timeout_secs":30,"recorded":["no-args"]}}"#
3649        );
3650        let cfg_path = dir.join(CONFIG_FILE);
3651        let case_path = dir.join("no-args.toml");
3652        std::fs::write(&cfg_path, &sentinel_cfg).unwrap();
3653        std::fs::write(&case_path, "stdout = \"ok\\n\"\n").unwrap();
3654
3655        let rec_err = record(&RecordOptions {
3656            repo: &repo,
3657            run: &["definitely-not-run".to_string()],
3658            inputs: None,
3659            normalize: &[],
3660            name: None,
3661            traps: false,
3662            timeout_secs: Some(0),
3663            http: None,
3664            server_args: None,
3665            fresh: None,
3666            pace_ms: None,
3667            port: None,
3668            float_tolerance: None,
3669            float_files: &[],
3670            effects: None,
3671            ready_secs: None,
3672        })
3673        .unwrap_err();
3674        let rec_msg = format!("{rec_err:#}");
3675        assert!(
3676            rec_msg.contains("--timeout") && rec_msg.contains("1 second"),
3677            "{rec_msg}"
3678        );
3679
3680        let rep_err = replay(&ReplayOptions {
3681            repo: &repo,
3682            build: None,
3683            timeout_secs: Some(0),
3684            port: None,
3685            case: None,
3686        })
3687        .unwrap_err();
3688        let rep_msg = format!("{rep_err:#}");
3689        assert!(
3690            rep_msg.contains("--timeout") && rep_msg.contains("1 second"),
3691            "{rep_msg}"
3692        );
3693
3694        assert_eq!(std::fs::read_to_string(&cfg_path).unwrap(), sentinel_cfg);
3695        assert_eq!(
3696            std::fs::read_to_string(&case_path).unwrap(),
3697            "stdout = \"ok\\n\"\n"
3698        );
3699
3700        let zero_cfg = sentinel_cfg.replace(r#""timeout_secs":30"#, r#""timeout_secs":0"#);
3701        std::fs::write(&cfg_path, &zero_cfg).unwrap();
3702        let saved_zero_err = replay(&ReplayOptions {
3703            repo: &repo,
3704            build: None,
3705            timeout_secs: None,
3706            port: None,
3707            case: None,
3708        })
3709        .unwrap_err();
3710        let saved_msg = format!("{saved_zero_err:#}");
3711        assert!(
3712            saved_msg.contains("--timeout") && saved_msg.contains("1 second"),
3713            "{saved_msg}"
3714        );
3715
3716        std::fs::remove_dir_all(repo).unwrap();
3717    }
3718}