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    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/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
1235/// with the folder of the file it came from.
1236pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
1237    let skip = ["node_modules", "target", "vendor", ".git"];
1238    let walker = crate::walk::filtered(repo, move |e| {
1239        let name = e.file_name().to_string_lossy();
1240        !skip.contains(&name.as_ref())
1241    })
1242    .max_depth(Some(4))
1243    .sort_by_file_name(|a, b| a.cmp(b))
1244    .build();
1245    let rust_dir = repo.join("rust");
1246    let mut out = Vec::new();
1247    for entry in walker.flatten() {
1248        let path = entry.path();
1249        if path.starts_with(&rust_dir) || !path.is_file() {
1250            continue;
1251        }
1252        let ext = path
1253            .extension()
1254            .map(|e| e.to_string_lossy().to_lowercase())
1255            .unwrap_or_default();
1256        let markdown = matches!(ext.as_str(), "md" | "markdown");
1257        if !markdown && ext != "sh" {
1258            continue;
1259        }
1260        let Ok(text) = std::fs::read_to_string(path) else {
1261            continue;
1262        };
1263        let doc_dir = path.parent().unwrap_or(repo);
1264        let mut fence: Option<String> = None;
1265        // A command wrapped with trailing backslashes, joined so far.
1266        let mut pending = String::new();
1267        for raw in text.lines() {
1268            let line = raw.trim();
1269            let candidate = if markdown {
1270                if line.starts_with("```") || line.starts_with("~~~") {
1271                    pending.clear();
1272                    fence = match fence {
1273                        Some(_) => None,
1274                        None => Some(
1275                            line.trim_start_matches(['`', '~'])
1276                                .split_whitespace()
1277                                .next()
1278                                .unwrap_or_default()
1279                                .to_lowercase(),
1280                        ),
1281                    };
1282                    continue;
1283                }
1284                let Some(lang) = &fence else { continue };
1285                // Continuation lines carry no `$ ` prompt, and keep their indentation: it is what
1286                // separates them from the previous word, as the shell adds no space when joining.
1287                if !pending.is_empty() {
1288                    raw
1289                } else {
1290                    let start = raw.trim_start();
1291                    match start.strip_prefix("$ ") {
1292                        Some(rest) => rest,
1293                        None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => start,
1294                        None => continue,
1295                    }
1296                }
1297            } else if !pending.is_empty() {
1298                raw
1299            } else {
1300                let start = raw.trim_start();
1301                start.strip_prefix("$ ").unwrap_or(start)
1302            };
1303            // The line's end is untrimmed, so `\ ` (an escaped space) does not continue.
1304            if !ends_in_comment(candidate)
1305                && let Some(head) = continued(candidate)
1306            {
1307                pending.push_str(head);
1308                continue;
1309            }
1310            pending.push_str(candidate);
1311            let command = std::mem::take(&mut pending);
1312            if let Some(case) = parse(&command, doc_dir) {
1313                out.push(case);
1314            }
1315        }
1316    }
1317    out
1318}
1319
1320/// Whether a shell line ends inside a comment: an unquoted `#` that starts a word. A `\` at the
1321/// end of a comment is part of the comment, not a continuation.
1322fn ends_in_comment(line: &str) -> bool {
1323    let (mut single, mut double, mut escaped, mut word_start) = (false, false, false, true);
1324    for c in line.chars() {
1325        if escaped {
1326            escaped = false;
1327            word_start = false;
1328            continue;
1329        }
1330        match c {
1331            '\\' if !single => escaped = true,
1332            '\'' if !double => single = !single,
1333            '"' if !single => double = !double,
1334            '#' if word_start && !single && !double => return true,
1335            _ => {}
1336        }
1337        word_start = c.is_whitespace() && !single && !double;
1338    }
1339    false
1340}
1341
1342/// The line without its trailing `\` when the shell would join it with the next line. An even
1343/// number of trailing backslashes ends in a literal one (`C:\\`), not a continuation.
1344fn continued(line: &str) -> Option<&str> {
1345    let head = line.strip_suffix('\\')?;
1346    let escaped = (head.len() - head.trim_end_matches('\\').len()) % 2 == 1;
1347    (!escaped).then_some(head)
1348}
1349
1350fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1351    let text =
1352        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1353    let mut out = Vec::new();
1354    for (n, line) in text.lines().enumerate() {
1355        if line.trim().is_empty() {
1356            continue;
1357        }
1358        let input: Input = serde_json::from_str(line)
1359            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1360        let mut case = Case::new(input.args);
1361        case.stdin = input.stdin.map(String::into_bytes);
1362        case.env = input.env;
1363        for (file, content) in input.files {
1364            ensure!(
1365                safe_relative(&file),
1366                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1367                path.display(),
1368                n + 1
1369            );
1370            case.files.insert(PathBuf::from(file), content.into_bytes());
1371        }
1372        for file in input.remove {
1373            ensure!(
1374                safe_relative(&file),
1375                "{}:{}: removed `{file}` must be a relative path inside the sandbox",
1376                path.display(),
1377                n + 1
1378            );
1379            case.remove.push(PathBuf::from(file));
1380        }
1381        out.push((input.name, case));
1382    }
1383    Ok(out)
1384}
1385
1386pub(crate) fn is_word(arg: &str) -> bool {
1387    let mut chars = arg.chars();
1388    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1389        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1390}
1391
1392pub(crate) fn interleave<T>(groups: Vec<Vec<T>>) -> Vec<T> {
1393    let mut queues: Vec<std::collections::VecDeque<T>> =
1394        groups.into_iter().map(Into::into).collect();
1395    let mut out = Vec::new();
1396    loop {
1397        let mut progressed = false;
1398        for q in &mut queues {
1399            if let Some(item) = q.pop_front() {
1400                out.push(item);
1401                progressed = true;
1402            }
1403        }
1404        if !progressed {
1405            break;
1406        }
1407    }
1408    out
1409}
1410
1411/// Spreads traps round-robin across bases, deduplicating against `existing` and earlier traps
1412/// before capping at `limit`. `reserved` traps (such as the unknown-route probe) are always kept
1413/// first. Returns `(kept, dropped)` where `dropped` counts unique traps excluded by `limit`.
1414pub(crate) fn spread_traps<T, K, F>(
1415    per_base: Vec<Vec<T>>,
1416    reserved: Vec<T>,
1417    existing: &BTreeSet<K>,
1418    key: F,
1419    limit: usize,
1420) -> (Vec<T>, usize)
1421where
1422    K: Ord + Clone,
1423    F: Fn(&T) -> K,
1424{
1425    let mut seen = existing.clone();
1426    let mut out = Vec::new();
1427    let mut dropped = 0usize;
1428    for item in reserved {
1429        if seen.insert(key(&item)) {
1430            if out.len() < limit {
1431                out.push(item);
1432            } else {
1433                dropped += 1;
1434            }
1435        }
1436    }
1437    let mut queues: Vec<std::collections::VecDeque<T>> =
1438        per_base.into_iter().map(Into::into).collect();
1439    loop {
1440        let mut any = false;
1441        for q in &mut queues {
1442            while let Some(item) = q.pop_front() {
1443                if seen.insert(key(&item)) {
1444                    if out.len() < limit {
1445                        out.push(item);
1446                    } else {
1447                        dropped += 1;
1448                    }
1449                    any = true;
1450                    break;
1451                }
1452            }
1453        }
1454        if !any {
1455            break;
1456        }
1457    }
1458    (out, dropped)
1459}
1460
1461fn trap_cases(bases: &[Case]) -> (Vec<Case>, usize) {
1462    let mut per_base = Vec::with_capacity(bases.len());
1463    for base in bases {
1464        let mut slots: Vec<Vec<Case>> = Vec::new();
1465        for (i, arg) in base.args.iter().enumerate() {
1466            if i == 0 && is_word(arg) {
1467                continue;
1468            }
1469            let number = arg.parse::<f64>().is_ok();
1470            if arg.starts_with('-') && !number {
1471                continue;
1472            }
1473            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1474                INT_TRAPS.to_vec()
1475            } else if number && arg.contains(['.', 'e', 'E']) {
1476                FLOAT_TRAPS.to_vec()
1477            } else if base.files.contains_key(Path::new(arg)) {
1478                vec!["missing-input.txt"]
1479            } else {
1480                STRING_TRAPS.to_vec()
1481            };
1482            let slot: Vec<Case> = values
1483                .into_iter()
1484                .filter(|v| v != arg)
1485                .map(|v| {
1486                    let mut case = base.clone();
1487                    case.args[i] = v.to_string();
1488                    case
1489                })
1490                .collect();
1491            if !slot.is_empty() {
1492                slots.push(slot);
1493            }
1494        }
1495        if let Some(stdin) = &base.stdin {
1496            let json = std::str::from_utf8(stdin)
1497                .ok()
1498                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1499                .is_some_and(|v| v.is_object() || v.is_array());
1500            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1501            slots.push(
1502                values
1503                    .iter()
1504                    .map(|v| {
1505                        let mut case = base.clone();
1506                        case.stdin = Some(v.as_bytes().to_vec());
1507                        case
1508                    })
1509                    .collect(),
1510            );
1511        }
1512        per_base.push(interleave(slots));
1513    }
1514    let existing: BTreeSet<_> = bases.iter().map(Case::key).collect();
1515    spread_traps(per_base, Vec::new(), &existing, Case::key, MAX_TRAPS)
1516}
1517
1518pub(crate) fn slug(text: &str) -> String {
1519    slug_max(text, 24)
1520}
1521
1522/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
1523/// only past the 24th character stay apart.
1524pub(crate) fn given_slug(text: &str) -> String {
1525    slug_max(text, 96)
1526}
1527
1528fn slug_max(text: &str, max: usize) -> String {
1529    let mut out = String::new();
1530    for c in text.chars() {
1531        if c.is_ascii_alphanumeric() {
1532            out.push(c.to_ascii_lowercase());
1533        } else if !out.ends_with('-') && !out.is_empty() {
1534            out.push('-');
1535        }
1536    }
1537    out.truncate(max);
1538    out.trim_end_matches('-').to_string()
1539}
1540
1541pub struct RecordOptions<'a> {
1542    pub repo: &'a Path,
1543    /// The command that runs the original; taken from the saved config when empty.
1544    pub run: &'a [String],
1545    pub inputs: Option<&'a Path>,
1546    /// Built-in normalizer names, or `name=regex` for your own.
1547    pub normalize: &'a [String],
1548    pub name: Option<&'a str>,
1549    pub traps: bool,
1550    pub timeout_secs: Option<u64>,
1551    /// `Some(true)` records as a server, `Some(false)` drops any saved server setting and records
1552    /// as a CLI, and `None` keeps the saved mode (or enables server mode if server-only options
1553    /// such as `port`, non-empty `server_args`, or `pace_ms` are given).
1554    pub http: Option<bool>,
1555    /// The port a server always listens on (implies `http`); unset keeps the saved port, `Some(0)`
1556    /// removes it so the server gets a free port through `PORT` and `{port}`.
1557    pub port: Option<u16>,
1558    /// Servers: arguments every start gets after its command, the original's and every build's
1559    /// (non-empty implies `http`); `None` keeps the saved list, `Some(&[])` clears it.
1560    pub server_args: Option<&'a [String]>,
1561    /// Repository files or folders copied into a fresh working directory before every case (CLIs)
1562    /// or start (servers); `None` keeps the saved list, `Some(&[])` clears it.
1563    pub fresh: Option<&'a [String]>,
1564    /// Servers: milliseconds to wait after each response, for work the server does after
1565    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
1566    pub pace_ms: Option<u64>,
1567    /// Numbers in the output match within this tolerance; kept from the last recording when
1568    /// `None`, removed with 0.
1569    pub float_tolerance: Option<f64>,
1570    /// Written files of raw floats, `path=f32le` or `path=f64le`; kept from the last recording
1571    /// when empty.
1572    pub float_files: &'a [String],
1573    pub effects: Option<crate::effects::EffectsConfig>,
1574    /// Servers: seconds to wait for the port before giving up; kept from the last recording when
1575    /// `None`; 0 restores the default, a minute.
1576    pub ready_secs: Option<u64>,
1577}
1578
1579fn is_zero(n: &usize) -> bool {
1580    *n == 0
1581}
1582
1583#[derive(Debug, Serialize)]
1584pub struct RecordOutcome {
1585    pub dir: PathBuf,
1586    pub run: Vec<String>,
1587    pub cases: usize,
1588    pub examples: usize,
1589    pub inputs: usize,
1590    pub traps: usize,
1591    /// Unique traps dropped after hitting `MAX_TRAPS`.
1592    #[serde(default, skip_serializing_if = "is_zero")]
1593    pub traps_dropped: usize,
1594    /// Cases where the two runs of the original differed.
1595    pub noisy: Vec<String>,
1596    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1597    /// in any order, `lines` became a `...` that matches anything.
1598    pub noise: Vec<Noise>,
1599    /// Cases whose exit code or written files differed between the two runs.
1600    pub unstable: Vec<String>,
1601    /// Cases not written: the original timed out or did not answer.
1602    pub timed_out: Vec<String>,
1603    /// The cases this recording wrote.
1604    pub recorded: Vec<String>,
1605    /// Cases the last recording in this folder wrote and this one did not (a timeout included):
1606    /// removed, apart from files a case that stays reads (`fs.base`).
1607    pub stale: Vec<String>,
1608    /// Cases in the folder that no recording wrote (by hand, or before the list was kept):
1609    /// left in place.
1610    pub kept: Vec<String>,
1611}
1612
1613/// What each case's files are called after its name.
1614const CASE_FILES: [&str; 9] = [
1615    "toml",
1616    "stdin",
1617    "stdout",
1618    "stderr",
1619    REMOVED_EXT,
1620    crate::effects::EXT,
1621    "body",
1622    "in",
1623    "out",
1624];
1625
1626/// Removes the cases the last recording in this folder wrote (`previous`) that this one did not
1627/// write, and names the cases in the folder that did not come from a recording, which it keeps.
1628/// Only `previous` marks a case as a recording's: a case written by hand stays even when an input
1629/// of its name timed out now. Files a case that stays reads through `fs.base` (that folder, or one
1630/// inside it) stay too.
1631pub(crate) fn drop_stale(outcome: &mut RecordOutcome, previous: &[String]) -> Result<()> {
1632    let written: BTreeSet<&str> = outcome.recorded.iter().map(String::as_str).collect();
1633    let ours: BTreeSet<&str> = previous
1634        .iter()
1635        .map(String::as_str)
1636        .filter(|name| !written.contains(name))
1637        .collect();
1638    let read = bases_read(&outcome.dir, &ours);
1639    let mut stale = Vec::new();
1640    for name in &ours {
1641        if outcome.dir.join(format!("{name}.toml")).is_file() {
1642            stale.push((*name).to_string());
1643        }
1644        for ext in CASE_FILES {
1645            let path = outcome.dir.join(format!("{name}.{ext}"));
1646            // A folder a case that stays reads, holds one it reads, or is on the way to it as
1647            // written: `two.in/sub`, `../app-cases/two.in/sub` (resolved) and `two.in/../shared`
1648            // (on Unix only found while `two.in` exists) all keep `two.in`.
1649            let resolved = path.canonicalize().ok();
1650            if any_base_reads(&read, &path, resolved.as_deref()) {
1651                continue;
1652            }
1653            if path.is_dir() {
1654                std::fs::remove_dir_all(&path)
1655                    .with_context(|| format!("removing {}", path.display()))?;
1656            } else if path.is_file() {
1657                std::fs::remove_file(&path)
1658                    .with_context(|| format!("removing {}", path.display()))?;
1659            }
1660        }
1661    }
1662    let mut kept: Vec<String> = std::fs::read_dir(&outcome.dir)?
1663        .flatten()
1664        .filter_map(|entry| {
1665            let name = entry.file_name().to_string_lossy().into_owned();
1666            name.strip_suffix(".toml").map(str::to_string)
1667        })
1668        .filter(|name| !written.contains(name.as_str()))
1669        .collect();
1670    kept.sort();
1671    outcome.stale = stale;
1672    outcome.kept = kept;
1673    Ok(())
1674}
1675
1676fn any_base_reads(read: &BTreeSet<PathBuf>, path: &Path, resolved: Option<&Path>) -> bool {
1677    read.iter()
1678        .any(|base| base.starts_with(path) || resolved.is_some_and(|r| base.starts_with(r)))
1679}
1680
1681/// The `fs.base` folders that the cases in `dir` other than `going` read, each as written (joined
1682/// to `dir`) and, when it exists, resolved.
1683fn bases_read(dir: &Path, going: &BTreeSet<&str>) -> BTreeSet<PathBuf> {
1684    let Ok(entries) = std::fs::read_dir(dir) else {
1685        return BTreeSet::new();
1686    };
1687    entries
1688        .flatten()
1689        .map(|entry| entry.path())
1690        .filter(|path| {
1691            path.extension().is_some_and(|e| e == "toml")
1692                && path
1693                    .file_stem()
1694                    .and_then(|s| s.to_str())
1695                    .is_some_and(|stem| !going.contains(stem))
1696        })
1697        .filter_map(|path| std::fs::read_to_string(path).ok())
1698        .filter_map(|text| text.parse::<DocumentMut>().ok())
1699        .filter_map(|doc| {
1700            doc.get("fs")
1701                .and_then(|f| f.get("base"))
1702                .and_then(Item::as_str)
1703                .map(|base| dir.join(base))
1704        })
1705        .flat_map(|base| {
1706            let resolved = base.canonicalize().ok();
1707            std::iter::once(base).chain(resolved)
1708        })
1709        .collect()
1710}
1711
1712struct Recorded {
1713    stdout: Vec<u8>,
1714    stderr: Vec<u8>,
1715    effects: Option<Vec<u8>>,
1716    status: Status,
1717    written: BTreeMap<PathBuf, Vec<u8>>,
1718    removed: Vec<PathBuf>,
1719    binary: bool,
1720    noise: Vec<(String, NoiseKind)>,
1721    unstable: bool,
1722}
1723
1724/// How two runs of the original disagreed.
1725#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1726#[serde(rename_all = "lowercase")]
1727pub enum NoiseKind {
1728    /// Values within lines changed (times, ids): those parts are wildcards now.
1729    Values,
1730    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1731    /// in any order, and a port must produce exactly those lines.
1732    Order,
1733    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1734    /// anything. Look at these first.
1735    Lines,
1736}
1737
1738#[derive(Debug, Clone, Serialize)]
1739pub struct Noise {
1740    pub case: String,
1741    pub field: String,
1742    pub kind: NoiseKind,
1743}
1744
1745fn same_lines_any_order(a: &str, b: &str) -> bool {
1746    let (mut la, mut lb) = (lines(a), lines(b));
1747    la.sort_unstable();
1748    lb.sort_unstable();
1749    la == lb
1750}
1751
1752pub(crate) fn settle_text(
1753    norm: &Normalizers,
1754    a: &[u8],
1755    b: &[u8],
1756) -> (Vec<u8>, Option<NoiseKind>, bool) {
1757    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1758        (Ok(a), Ok(b)) => {
1759            let (a, b) = (norm.apply(a), norm.apply(b));
1760            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1761                (a.into_bytes(), None, false)
1762            } else if same_lines_any_order(&a, &b) {
1763                (a.into_bytes(), Some(NoiseKind::Order), false)
1764            } else {
1765                let merged = merge_noise(&a, &b);
1766                let kind = if merged.split('\n').any(|l| l == "...") {
1767                    NoiseKind::Lines
1768                } else {
1769                    NoiseKind::Values
1770                };
1771                (merged.into_bytes(), Some(kind), false)
1772            }
1773        }
1774        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1775    }
1776}
1777
1778fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1779    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1780        .iter()
1781        .any(|bytes| std::str::from_utf8(bytes).is_err());
1782    let settle_stream = |a: &[u8], b: &[u8]| {
1783        if binary {
1784            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1785        } else {
1786            let (bytes, noise, _) = settle_text(norm, a, b);
1787            (bytes, noise)
1788        }
1789    };
1790    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1791    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1792    let (effects, fx_noise) = match (&one.effects, &two.effects) {
1793        (Some(a), Some(b)) => {
1794            let (bytes, noise, _) = settle_text(norm, a, b);
1795            (Some(bytes), noise)
1796        }
1797        _ => (None, None),
1798    };
1799    let (w1, w2) = (one.written(case), two.written(case));
1800    let mut unstable = one.status != two.status
1801        || one.removed != two.removed
1802        || !w1.keys().eq(w2.keys())
1803        || (binary && (out_noise.is_some() || err_noise.is_some()));
1804    let mut noise: Vec<(String, NoiseKind)> = [
1805        ("stdout", out_noise),
1806        ("stderr", err_noise),
1807        (crate::effects::EXT, fx_noise),
1808    ]
1809    .into_iter()
1810    .filter_map(|(f, k)| Some((f.to_string(), k?)))
1811    .collect();
1812    let mut written = BTreeMap::new();
1813    for (path, a) in &w1 {
1814        let b = w2.get(path).unwrap_or(a);
1815        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1816        unstable |= file_bin && file_noise.is_some();
1817        if let Some(kind) = file_noise {
1818            noise.push((format!("file {}", path.display()), kind));
1819        }
1820        written.insert(path.clone(), bytes);
1821    }
1822    Recorded {
1823        stdout,
1824        stderr,
1825        effects,
1826        status: one.status.clone(),
1827        written,
1828        removed: one.removed.clone(),
1829        binary,
1830        noise,
1831        unstable,
1832    }
1833}
1834
1835fn dotted() -> Table {
1836    let mut t = Table::new();
1837    t.set_dotted(true);
1838    t
1839}
1840
1841fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1842    for ext in [
1843        "stdin",
1844        "stdout",
1845        "stderr",
1846        REMOVED_EXT,
1847        crate::effects::EXT,
1848    ] {
1849        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1850    }
1851    for ext in ["in", "out"] {
1852        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1853    }
1854    let mut doc = DocumentMut::new();
1855    let mut bin_t = dotted();
1856    bin_t["name"] = value(bin);
1857    doc["bin"] = Item::Table(bin_t);
1858    let mut args = toml_edit::Array::new();
1859    for a in &case.args {
1860        args.push(a.as_str());
1861    }
1862    doc["args"] = value(args);
1863    if !case.env.is_empty() {
1864        let mut add = dotted();
1865        for (k, v) in &case.env {
1866            add[k.as_str()] = value(v.as_str());
1867        }
1868        let mut env = dotted();
1869        env.insert("add", Item::Table(add));
1870        doc["env"] = Item::Table(env);
1871    }
1872    match rec.status {
1873        Status::Code(code) => {
1874            let mut status = dotted();
1875            status["code"] = value(i64::from(code));
1876            doc["status"] = Item::Table(status);
1877        }
1878        _ => doc["status"] = value("interrupted"),
1879    }
1880    let mut fs = dotted();
1881    fs["sandbox"] = value(true);
1882    if !case.files.is_empty() {
1883        fs["base"] = value(format!("{name}.in"));
1884    }
1885    if !case.remove.is_empty() {
1886        let mut remove = toml_edit::Array::new();
1887        for path in &case.remove {
1888            remove.push(path.to_string_lossy().as_ref());
1889        }
1890        fs["remove"] = value(remove);
1891    }
1892    doc["fs"] = Item::Table(fs);
1893    if rec.binary {
1894        doc["binary"] = value(true);
1895    }
1896    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1897    if let Some(stdin) = &case.stdin {
1898        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1899    }
1900    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1901    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1902    if !rec.removed.is_empty() {
1903        let list: String = rec
1904            .removed
1905            .iter()
1906            .map(|p| format!("{}\n", p.display()))
1907            .collect();
1908        std::fs::write(dir.join(format!("{name}.{REMOVED_EXT}")), list)?;
1909    }
1910    if let Some(effects) = &rec.effects {
1911        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
1912    }
1913    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1914        for (path, bytes) in files {
1915            let target = dir.join(format!("{name}.{sub}")).join(path);
1916            if let Some(parent) = target.parent() {
1917                std::fs::create_dir_all(parent)?;
1918            }
1919            std::fs::write(&target, bytes)?;
1920        }
1921    }
1922    Ok(())
1923}
1924
1925pub(crate) fn reserve_case_name(
1926    taken: &mut BTreeSet<String>,
1927    base: String,
1928    mut suffix: usize,
1929) -> String {
1930    let mut name = base.clone();
1931    while !taken.insert(name.clone()) {
1932        name = format!("{base}-{suffix}");
1933        suffix += 1;
1934    }
1935    name
1936}
1937
1938pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1939    check_timeout(opts.timeout_secs)?;
1940    let repo = opts
1941        .repo
1942        .canonical()
1943        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1944    let existing = Config::load(&repo)?;
1945    // The names the last recording wrote, and whether it wrote them to `http/` or to the CLI
1946    // folder: they are a recording's only in that folder.
1947    let (previous, previous_http) = existing
1948        .as_ref()
1949        .map(|c| (c.recorded.clone(), c.http.is_some()))
1950        .unwrap_or_default();
1951    let run = if !opts.run.is_empty() {
1952        opts.run.to_vec()
1953    } else if let Some(c) = &existing {
1954        c.run.clone()
1955    } else {
1956        bail!(
1957            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1958        );
1959    };
1960    let mut normalize = existing
1961        .as_ref()
1962        .map(|c| c.normalize.clone())
1963        .unwrap_or_default();
1964    let mut normalizers = existing
1965        .as_ref()
1966        .map(|c| c.normalizers.clone())
1967        .unwrap_or_default();
1968    for n in opts.normalize {
1969        if let Some((name, pattern)) = n.split_once('=') {
1970            normalizers.insert(name.to_string(), pattern.to_string());
1971        } else if !normalize.contains(n) {
1972            normalize.push(n.clone());
1973        }
1974    }
1975    let inferred = |run: &[String]| {
1976        app_names(&repo, run, None)
1977            .into_iter()
1978            .next()
1979            .unwrap_or_else(|| "app".to_string())
1980    };
1981    let explicit = opts.name.map(str::to_string).or_else(|| {
1982        existing
1983            .as_ref()
1984            .filter(|c| opts.run.is_empty() || c.run == opts.run || c.name != inferred(&c.run))
1985            .map(|c| c.name.clone())
1986    });
1987    let names = app_names(&repo, &run, explicit.as_deref());
1988    let timeout_secs = opts
1989        .timeout_secs
1990        .or(existing.as_ref().map(|c| c.timeout_secs))
1991        .unwrap_or_else(default_timeout);
1992    ensure!(
1993        timeout_secs >= 1,
1994        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
1995    );
1996    let mut config = Config {
1997        schema: SCHEMA.to_string(),
1998        name: explicit
1999            .or_else(|| names.first().cloned())
2000            .unwrap_or_else(|| "app".to_string()),
2001        run,
2002        normalize,
2003        normalizers,
2004        timeout_secs,
2005        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts)?,
2006        float_tolerance: match opts.float_tolerance {
2007            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
2008            None => existing.as_ref().and_then(|c| c.float_tolerance),
2009        },
2010        float_files: if opts.float_files.is_empty() {
2011            existing
2012                .as_ref()
2013                .map(|c| c.float_files.clone())
2014                .unwrap_or_default()
2015        } else {
2016            opts.float_files
2017                .iter()
2018                .map(|spec| {
2019                    let (path, format) = spec.rsplit_once('=').with_context(|| {
2020                        format!("--float-file `{spec}`: use PATH=f32le or PATH=f64le")
2021                    })?;
2022                    float_width(format)?;
2023                    Ok((path.to_string(), format.to_string()))
2024                })
2025                .collect::<Result<_>>()?
2026        },
2027        unordered: BTreeMap::new(),
2028        effects: crate::effects::EffectsConfig::merge(
2029            existing.as_ref().and_then(|c| c.effects.clone()),
2030            opts.effects.clone(),
2031        ),
2032        fresh: Vec::new(),
2033        recorded: Vec::new(),
2034    };
2035    if let Some(http) = config.http.as_mut() {
2036        if let Some(fresh) = opts.fresh {
2037            http.fresh = fresh.to_vec();
2038        }
2039    } else if let Some(fresh) = opts.fresh {
2040        config.fresh = fresh.to_vec();
2041    } else if let Some(c) = &existing {
2042        config.fresh = c.fresh.clone();
2043    }
2044    let norm = Normalizers::new(&config)?;
2045    if config.http.is_some() {
2046        let mut outcome = crate::http::record(&repo, &config, &norm, opts)?;
2047        config.unordered = unordered_of(&outcome.noise);
2048        drop_stale(&mut outcome, if previous_http { &previous } else { &[] })?;
2049        config.recorded = outcome.recorded.clone();
2050        std::fs::write(
2051            cases_dir(&repo).join(CONFIG_FILE),
2052            serde_json::to_string_pretty(&config)? + "\n",
2053        )?;
2054        if config.http.as_ref().is_some_and(|h| h.fresh.is_empty()) {
2055            let _ = std::fs::remove_dir_all(
2056                cases_dir(&repo)
2057                    .join(crate::http::HTTP_DIR)
2058                    .join(crate::http::FILES_DIR),
2059            );
2060        }
2061        return Ok(outcome);
2062    }
2063
2064    let examples = find_examples(&repo, &names);
2065    let inputs = match opts.inputs {
2066        Some(path) => read_inputs(path)?,
2067        None => Vec::new(),
2068    };
2069    let mut planned: Vec<(String, Case)> = Vec::new();
2070    let mut seen = BTreeSet::new();
2071    let mut taken = BTreeSet::new();
2072    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
2073        if !seen.insert(case.key()) {
2074            return false;
2075        }
2076        let base_name = match given {
2077            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
2078            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
2079                Some(s) => format!("{prefix}-{n:03}-{s}"),
2080                None => format!("{prefix}-{n:03}"),
2081            },
2082        };
2083        let name = reserve_case_name(&mut taken, base_name, n);
2084        planned.push((name, case));
2085        true
2086    };
2087    let mut bases = Vec::new();
2088    let mut counts = [0usize; 3];
2089    for case in examples {
2090        if push("example", counts[0] + 1, None, case.clone()) {
2091            counts[0] += 1;
2092            bases.push(case);
2093        }
2094    }
2095    for (given, case) in inputs {
2096        if push("input", counts[1] + 1, given, case.clone()) {
2097            counts[1] += 1;
2098            bases.push(case);
2099        }
2100    }
2101    if bases.is_empty() {
2102        let case = Case::new(Vec::new());
2103        push("example", 1, Some("no-args".to_string()), case.clone());
2104        bases.push(case);
2105    }
2106    let mut traps_dropped = 0usize;
2107    if opts.traps {
2108        let (traps, dropped) = trap_cases(&bases);
2109        traps_dropped = dropped;
2110        for case in traps {
2111            if push("trap", counts[2] + 1, None, case) {
2112                counts[2] += 1;
2113            }
2114        }
2115    }
2116
2117    let timeout = Duration::from_secs(config.timeout_secs);
2118    let effects = config.effects.as_ref();
2119    let base = crate::http::snapshot_to(&repo, &config.fresh, &cases_dir(&repo).join(FRESH_DIR))?;
2120    let base = base.as_deref();
2121    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
2122        let one = run_case(&config.run, &repo, case, timeout, effects, base)?;
2123        let two = run_case(&config.run, &repo, case, timeout, effects, base)?;
2124        Ok((one, two))
2125    };
2126    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2127        planned.iter().map(run_twice).collect()
2128    } else {
2129        par_map(&planned, run_twice)
2130    };
2131    let dir = cases_dir(&repo);
2132    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
2133    let mut outcome = RecordOutcome {
2134        dir: dir.clone(),
2135        run: config.run.clone(),
2136        cases: 0,
2137        examples: counts[0],
2138        inputs: counts[1],
2139        traps: counts[2],
2140        traps_dropped,
2141        noisy: Vec::new(),
2142        noise: Vec::new(),
2143        unstable: Vec::new(),
2144        timed_out: Vec::new(),
2145        recorded: Vec::new(),
2146        stale: Vec::new(),
2147        kept: Vec::new(),
2148    };
2149    for ((name, case), runs) in planned.iter().zip(runs) {
2150        let (one, two) = runs?;
2151        if one.status == Status::Timeout || two.status == Status::Timeout {
2152            outcome.timed_out.push(name.clone());
2153            continue;
2154        }
2155        let rec = settle(&norm, case, &one, &two);
2156        write_case(&dir, &config.name, name, case, &rec)?;
2157        outcome.cases += 1;
2158        outcome.recorded.push(name.clone());
2159        if !rec.noise.is_empty() {
2160            outcome.noisy.push(name.clone());
2161        }
2162        outcome
2163            .noise
2164            .extend(rec.noise.iter().map(|(field, kind)| Noise {
2165                case: name.clone(),
2166                field: field.clone(),
2167                kind: *kind,
2168            }));
2169        if rec.unstable {
2170            outcome.unstable.push(name.clone());
2171        }
2172    }
2173    config.unordered = unordered_of(&outcome.noise);
2174    drop_stale(&mut outcome, if previous_http { &[] } else { &previous })?;
2175    config.recorded = outcome.recorded.clone();
2176    std::fs::write(
2177        dir.join(CONFIG_FILE),
2178        serde_json::to_string_pretty(&config)? + "\n",
2179    )?;
2180    if config.fresh.is_empty() {
2181        let fresh_dir = dir.join(FRESH_DIR);
2182        let retained_reads = bases_read(&dir, &BTreeSet::new());
2183        let resolved = fresh_dir.canonicalize().ok();
2184        if !any_base_reads(&retained_reads, &fresh_dir, resolved.as_deref()) {
2185            let _ = std::fs::remove_dir_all(&fresh_dir);
2186        }
2187    }
2188    Ok(outcome)
2189}
2190
2191fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
2192    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
2193    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
2194        out.entry(n.case.clone()).or_default().push(n.field.clone());
2195    }
2196    out
2197}
2198
2199enum Expect {
2200    Code(i32),
2201    Failed,
2202    Killed,
2203    Skip,
2204}
2205
2206struct Spec {
2207    name: String,
2208    case: Case,
2209    stdout: Option<Vec<u8>>,
2210    stderr: Option<Vec<u8>>,
2211    effects: Option<Vec<u8>>,
2212    status: Expect,
2213    out_dir: Option<PathBuf>,
2214    removed: Option<Vec<PathBuf>>,
2215    binary: bool,
2216}
2217
2218fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
2219    walk_files(base)
2220        .into_iter()
2221        .map(|p| {
2222            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
2223            let bytes = std::fs::read(&p).unwrap_or_default();
2224            (rel, bytes)
2225        })
2226        .collect()
2227}
2228
2229fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
2230    let name = path
2231        .file_stem()
2232        .map(|s| s.to_string_lossy().into_owned())
2233        .unwrap_or_default();
2234    let text =
2235        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
2236    let doc: DocumentMut = text
2237        .parse()
2238        .with_context(|| format!("parsing {}", path.display()))?;
2239    let args = match doc.get("args") {
2240        Some(item) if item.as_array().is_some() => item
2241            .as_array()
2242            .into_iter()
2243            .flatten()
2244            .map(|v| {
2245                v.as_str()
2246                    .map(str::to_string)
2247                    .unwrap_or_else(|| v.to_string())
2248            })
2249            .collect(),
2250        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
2251        None => Vec::new(),
2252    };
2253    let mut case = Case::new(args);
2254    let side = |key: &str| -> Result<Option<Vec<u8>>> {
2255        if let Some(s) = doc.get(key).and_then(Item::as_str) {
2256            return Ok(Some(s.as_bytes().to_vec()));
2257        }
2258        let file = dir.join(format!("{name}.{key}"));
2259        Ok(if file.exists() {
2260            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
2261        } else {
2262            None
2263        })
2264    };
2265    case.stdin = side("stdin")?;
2266    if let Some(env) = doc.get("env") {
2267        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
2268        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
2269            for (k, v) in add.iter() {
2270                case.env
2271                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
2272            }
2273        }
2274        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
2275            case.env_remove = remove
2276                .iter()
2277                .filter_map(|v| v.as_str().map(str::to_string))
2278                .collect();
2279        }
2280    }
2281    let base = doc
2282        .get("fs")
2283        .and_then(|f| f.get("base"))
2284        .and_then(Item::as_str)
2285        .map(|b| dir.join(b))
2286        .unwrap_or_else(|| dir.join(format!("{name}.in")));
2287    if base.is_dir() {
2288        case.files = read_files(&base);
2289    }
2290    if let Some(remove) = doc
2291        .get("fs")
2292        .and_then(|f| f.get("remove"))
2293        .and_then(Item::as_array)
2294    {
2295        case.remove = remove
2296            .iter()
2297            .filter_map(|v| v.as_str().map(PathBuf::from))
2298            .collect();
2299    }
2300    let status = match doc.get("status") {
2301        None => Expect::Code(0),
2302        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
2303            (Some("success"), _) => Expect::Code(0),
2304            (Some("failed"), _) => Expect::Failed,
2305            (Some("interrupted"), _) => Expect::Killed,
2306            (Some("skipped"), _) => Expect::Skip,
2307            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
2308            _ => bail!("{}: unknown `status`", path.display()),
2309        },
2310    };
2311    let out_dir = dir.join(format!("{name}.out"));
2312    Ok(Spec {
2313        stdout: side("stdout")?,
2314        stderr: side("stderr")?,
2315        effects: side(crate::effects::EXT)?,
2316        status,
2317        out_dir: out_dir.is_dir().then_some(out_dir),
2318        removed: side(REMOVED_EXT)?.map(|bytes| {
2319            String::from_utf8_lossy(&bytes)
2320                .lines()
2321                .filter(|l| !l.is_empty())
2322                .map(PathBuf::from)
2323                .collect()
2324        }),
2325        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
2326        name,
2327        case,
2328    })
2329}
2330
2331fn float_width(format: &str) -> Result<usize> {
2332    match format {
2333        "f32le" => Ok(4),
2334        "f64le" => Ok(8),
2335        other => bail!("float file format `{other}`: use f32le or f64le"),
2336    }
2337}
2338
2339fn floats(bytes: &[u8], width: usize) -> Vec<f64> {
2340    bytes
2341        .chunks_exact(width)
2342        .map(|c| match c.try_into() {
2343            Ok(b) if width == 4 => f64::from(f32::from_le_bytes(b)),
2344            _ => c.try_into().map_or(f64::NAN, f64::from_le_bytes),
2345        })
2346        .collect()
2347}
2348
2349fn compare_floats(
2350    expected: &[u8],
2351    actual: &[u8],
2352    width: usize,
2353    tol: Option<f64>,
2354) -> Option<String> {
2355    if !expected.len().is_multiple_of(width) || expected.len() != actual.len() {
2356        return Some(format!(
2357            "{} values expected, {} bytes got ({} bytes per value)\n",
2358            expected.len() / width,
2359            actual.len(),
2360            width
2361        ));
2362    }
2363    let (e, a) = (floats(expected, width), floats(actual, width));
2364    let tol = tol.unwrap_or(0.0);
2365    let same =
2366        |x: f64, y: f64| x == y || (x.is_nan() && y.is_nan()) || crate::tolerance::near(x, y, tol);
2367    let off: Vec<usize> = (0..e.len()).filter(|&i| !same(e[i], a[i])).collect();
2368    let first = *off.first()?;
2369    let (mut abs, mut rel) = (0.0f64, 0.0f64);
2370    for &i in &off {
2371        let d = (e[i] - a[i]).abs();
2372        abs = abs.max(d);
2373        rel = rel.max(d / e[i].abs().max(a[i].abs()).max(f64::MIN_POSITIVE));
2374    }
2375    Some(format!(
2376        "{} of {} values differ beyond the tolerance ({tol}); first at index {first}: {} expected, {} got; max abs diff {abs:e}, max rel diff {rel:e}\n",
2377        off.len(),
2378        e.len(),
2379        e[first],
2380        a[first]
2381    ))
2382}
2383
2384pub(crate) fn compare(
2385    norm: &Normalizers,
2386    expected: &[u8],
2387    actual: &[u8],
2388    binary: bool,
2389    unordered: bool,
2390) -> Option<String> {
2391    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
2392    {
2393        let e = norm.canonical(&norm.apply(e));
2394        let a = norm.canonical(&norm.apply(a));
2395        let tol = norm.float_tolerance;
2396        if unordered {
2397            let (mut el, mut al) = (lines(&e), lines(&a));
2398            let same = lines_match_in_any_order(&el, &al, tol);
2399            el.sort_unstable();
2400            al.sort_unstable();
2401            return (!same).then(|| {
2402                format!(
2403                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
2404                    render_diff(&el.join("\n"), &al.join("\n"), tol)
2405                )
2406            });
2407        }
2408        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
2409    }
2410    (expected != actual).then(|| {
2411        format!(
2412            "binary content differs ({} bytes expected, {} bytes got)\n",
2413            expected.len(),
2414            actual.len()
2415        )
2416    })
2417}
2418
2419pub struct ReplayOptions<'a> {
2420    pub repo: &'a Path,
2421    /// Command line of the build to test; the original's command when `None`.
2422    pub build: Option<&'a str>,
2423    pub timeout_secs: Option<u64>,
2424    /// Servers: the port the build listens on, when it is fixed.
2425    pub port: Option<u16>,
2426    /// Replay only this case (a library: only this unit).
2427    pub case: Option<&'a str>,
2428}
2429
2430pub(crate) fn only_case<T>(
2431    items: Vec<T>,
2432    case: Option<&str>,
2433    name: impl Fn(&T) -> &str,
2434) -> Result<Vec<T>> {
2435    let Some(case) = case else {
2436        return Ok(items);
2437    };
2438    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
2439    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
2440    ensure!(
2441        !kept.is_empty(),
2442        "no case named {case}; the cases are: {}",
2443        names.join(", ")
2444    );
2445    Ok(kept)
2446}
2447
2448#[derive(Debug, Serialize)]
2449pub struct Problem {
2450    pub field: String,
2451    pub detail: String,
2452}
2453
2454#[derive(Debug, Serialize)]
2455pub struct Failure {
2456    pub case: String,
2457    pub args: Vec<String>,
2458    pub problems: Vec<Problem>,
2459}
2460
2461/// Cases the build handed to the original: the front door appends a line to the file named by
2462/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
2463#[derive(Debug, Serialize)]
2464pub struct Fallback {
2465    pub cases: usize,
2466    pub total: usize,
2467    pub rate: f64,
2468    /// The cases that fell back.
2469    pub names: Vec<String>,
2470}
2471
2472#[derive(Debug, Serialize)]
2473pub struct ReplayOutcome {
2474    pub build: Vec<String>,
2475    pub passed: usize,
2476    pub total: usize,
2477    pub skipped: usize,
2478    pub failures: Vec<Failure>,
2479    pub fallback: Option<Fallback>,
2480    pub report: PathBuf,
2481}
2482
2483fn check(
2484    norm: &Normalizers,
2485    command: &[String],
2486    repo: &Path,
2487    spec: &Spec,
2488    timeout: Duration,
2489    effects: Option<&crate::effects::EffectsConfig>,
2490    base: Option<&Path>,
2491) -> Result<(Vec<Problem>, Option<bool>)> {
2492    let run = run_case(command, repo, &spec.case, timeout, effects, base)?;
2493    let mut problems = Vec::new();
2494    let status_ok = match (&spec.status, &run.status) {
2495        (Expect::Code(e), Status::Code(a)) => e == a,
2496        (Expect::Failed, Status::Code(a)) => *a != 0,
2497        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
2498        _ => false,
2499    };
2500    if !status_ok {
2501        let expected = match &spec.status {
2502            Expect::Code(c) => format!("exit code {c}"),
2503            Expect::Failed => "a non-zero exit code".to_string(),
2504            Expect::Killed => "killed by a signal".to_string(),
2505            Expect::Skip => String::new(),
2506        };
2507        problems.push(Problem {
2508            field: "status".to_string(),
2509            detail: format!("expected {expected}, got {}\n", run.status),
2510        });
2511    }
2512    let no_effects = Vec::new();
2513    for (field, expected, actual) in [
2514        ("stdout", &spec.stdout, &run.stdout),
2515        ("stderr", &spec.stderr, &run.stderr),
2516        (
2517            crate::effects::EXT,
2518            &spec.effects,
2519            run.effects.as_ref().unwrap_or(&no_effects),
2520        ),
2521    ] {
2522        if let Some(expected) = expected
2523            && let Some(detail) = compare(
2524                norm,
2525                expected,
2526                actual,
2527                spec.binary,
2528                norm.unordered(&spec.name, field),
2529            )
2530        {
2531            problems.push(Problem {
2532                field: field.to_string(),
2533                detail,
2534            });
2535        }
2536    }
2537    if let Some(expected) = &spec.removed
2538        && *expected != run.removed
2539    {
2540        let list = |paths: &[PathBuf]| -> String {
2541            paths
2542                .iter()
2543                .map(|p| format!("  {}\n", p.display()))
2544                .collect()
2545        };
2546        problems.push(Problem {
2547            field: "removed files".to_string(),
2548            detail: format!(
2549                "expected removed:\n{}got removed:\n{}",
2550                list(expected),
2551                list(&run.removed)
2552            ),
2553        });
2554    }
2555    if let Some(out_dir) = &spec.out_dir {
2556        for (path, expected) in read_files(out_dir) {
2557            let field = format!("file {}", path.display());
2558            match run.files.get(&path) {
2559                None => problems.push(Problem {
2560                    field,
2561                    detail: "not written\n".to_string(),
2562                }),
2563                Some(actual) => {
2564                    let unordered = norm.unordered(&spec.name, &field);
2565                    let detail = match norm.float_files.get(&path) {
2566                        Some(&width) => {
2567                            compare_floats(&expected, actual, width, norm.float_tolerance)
2568                        }
2569                        None => compare(norm, &expected, actual, false, unordered),
2570                    };
2571                    if let Some(detail) = detail {
2572                        problems.push(Problem { field, detail });
2573                    }
2574                }
2575            }
2576        }
2577    }
2578    Ok((problems, run.fallback))
2579}
2580
2581pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
2582    stable_paths(&report_body(outcome))
2583}
2584
2585/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
2586/// same file and CI can commit it and fail on `git diff --exit-code`.
2587fn stable_paths(text: &str) -> String {
2588    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
2589    let tmp = std::env::temp_dir();
2590    let tmp = tmp.to_string_lossy();
2591    let tmp = tmp.trim_end_matches(['/', '\\']);
2592    let text = if tmp.len() > 1 {
2593        text.replace(tmp, "$TMPDIR")
2594    } else {
2595        text.to_string()
2596    };
2597    SANDBOX
2598        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
2599        .replace_all(&text, "rust-anything-app-$1")
2600        .into_owned()
2601}
2602
2603fn report_body(outcome: &ReplayOutcome) -> String {
2604    let mut out = String::from("# App replay\n\n");
2605    out += &format!(
2606        "Build: `{}`\n\n",
2607        outcome
2608            .build
2609            .iter()
2610            .map(|w| shell_quote(w))
2611            .collect::<Vec<_>>()
2612            .join(" ")
2613    );
2614    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
2615    if outcome.skipped > 0 {
2616        out += &format!("Skipped: {}\n\n", outcome.skipped);
2617    }
2618    out += &match &outcome.fallback {
2619        Some(f) => format!(
2620            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
2621            f.rate * 100.0,
2622            f.cases,
2623            f.total
2624        ),
2625        None => "Fallback rate: not reported by this build\n\n".to_string(),
2626    };
2627    if outcome.failures.is_empty() {
2628        out += "Every case matches.\n";
2629        return out;
2630    }
2631    out += "## Failing cases\n";
2632    for f in &outcome.failures {
2633        out += &format!(
2634            "\n### {}\n\nArguments: `{}`\n",
2635            f.case,
2636            f.args
2637                .iter()
2638                .map(|w| shell_quote(w))
2639                .collect::<Vec<_>>()
2640                .join(" ")
2641        );
2642        for p in &f.problems {
2643            out += &format!(
2644                "\n{}:\n\n```diff\n{}```\n",
2645                p.field,
2646                p.detail.replace("```", "`\u{200b}``")
2647            );
2648        }
2649    }
2650    out
2651}
2652
2653fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2654    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2655        .with_context(|| {
2656            format!(
2657                "no cases in {}: run `rust-anything app record` first",
2658                dir.display()
2659            )
2660        })?
2661        .flatten()
2662        .map(|e| e.path())
2663        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2664        .collect();
2665    paths.sort();
2666    let specs = paths
2667        .iter()
2668        .map(|p| load_spec(dir, p))
2669        .collect::<Result<Vec<_>>>()?;
2670    ensure!(
2671        !specs.is_empty(),
2672        "no cases in {}: run `rust-anything app record` first",
2673        dir.display()
2674    );
2675    Ok(specs)
2676}
2677
2678/// The recorded cases' arguments, each with whether the original exited 0.
2679pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
2680    Ok(load_specs(&cases_dir(repo))?
2681        .into_iter()
2682        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
2683        .collect())
2684}
2685
2686pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2687    check_timeout(opts.timeout_secs)?;
2688    let repo = opts
2689        .repo
2690        .canonical()
2691        .with_context(|| format!("no folder {}", opts.repo.display()))?;
2692    let dir = cases_dir(&repo);
2693    let config = Config::load(&repo)?;
2694    if config.is_none()
2695        && let Ok(state) = crate::front_door::State::load(&repo)
2696        && state.kind == crate::front_door::AppKind::Library
2697    {
2698        ensure!(
2699            opts.build.is_none(),
2700            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
2701            state.name
2702        );
2703        return crate::library::replay(&repo, &state, opts.case);
2704    }
2705    let command = match (opts.build, &config) {
2706        (Some(build), _) => shell_split(build)?,
2707        (None, Some(c)) => c.run.clone(),
2708        (None, None) => bail!(
2709            "no {} in {}: run `rust-anything app record` first, or pass --build",
2710            CONFIG_FILE,
2711            dir.display()
2712        ),
2713    };
2714    ensure!(!command.is_empty(), "the build command is empty");
2715    let config = config.unwrap_or_else(|| Config {
2716        schema: SCHEMA.to_string(),
2717        name: "app".to_string(),
2718        run: Vec::new(),
2719        normalize: Vec::new(),
2720        normalizers: BTreeMap::new(),
2721        timeout_secs: default_timeout(),
2722        http: None,
2723        float_tolerance: None,
2724        float_files: BTreeMap::new(),
2725        unordered: BTreeMap::new(),
2726        effects: None,
2727        fresh: Vec::new(),
2728        recorded: Vec::new(),
2729    });
2730    let norm = Normalizers::new(&config)?;
2731    let timeout_secs = opts.timeout_secs.unwrap_or(config.timeout_secs);
2732    ensure!(
2733        timeout_secs >= 1,
2734        "--timeout must be at least 1 second (saved timeout_secs in {CONFIG_FILE} is 0; pass --timeout 1 or higher)"
2735    );
2736    let timeout = Duration::from_secs(timeout_secs);
2737    if config.http.is_some() {
2738        return crate::http::replay(
2739            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2740        );
2741    }
2742    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2743    let effects = config.effects.as_ref();
2744    let base = if config.fresh.is_empty() {
2745        None
2746    } else {
2747        let base = dir.join(FRESH_DIR);
2748        ensure!(
2749            base.is_dir(),
2750            "no {}: record again to snapshot the fresh files",
2751            base.display()
2752        );
2753        Some(base)
2754    };
2755    let check_one = |spec: &Spec| {
2756        if matches!(spec.status, Expect::Skip) {
2757            return Ok((Vec::new(), None));
2758        }
2759        check(
2760            &norm,
2761            &command,
2762            &repo,
2763            spec,
2764            timeout,
2765            effects,
2766            base.as_deref(),
2767        )
2768    };
2769    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2770        specs.iter().map(check_one).collect()
2771    } else {
2772        par_map(&specs, check_one)
2773    };
2774    let mut outcome = ReplayOutcome {
2775        build: command.clone(),
2776        passed: 0,
2777        total: 0,
2778        skipped: 0,
2779        failures: Vec::new(),
2780        fallback: None,
2781        report: dir.join(REPORT_FILE),
2782    };
2783    let (mut reported, mut fell_back) = (false, Vec::new());
2784    for (spec, result) in specs.iter().zip(results) {
2785        if matches!(spec.status, Expect::Skip) {
2786            outcome.skipped += 1;
2787            continue;
2788        }
2789        let (problems, fallback) = result?;
2790        outcome.total += 1;
2791        reported |= fallback.is_some();
2792        if fallback == Some(true) {
2793            fell_back.push(spec.name.clone());
2794        }
2795        if problems.is_empty() {
2796            outcome.passed += 1;
2797        } else {
2798            outcome.failures.push(Failure {
2799                case: spec.name.clone(),
2800                args: spec.case.args.clone(),
2801                problems,
2802            });
2803        }
2804    }
2805    if reported {
2806        outcome.fallback = Some(Fallback {
2807            cases: fell_back.len(),
2808            total: outcome.total,
2809            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2810            names: fell_back,
2811        });
2812    }
2813    std::fs::write(&outcome.report, report_markdown(&outcome))
2814        .with_context(|| format!("writing {}", outcome.report.display()))?;
2815    Ok(outcome)
2816}
2817
2818#[cfg(test)]
2819mod tests {
2820    use super::*;
2821
2822    #[test]
2823    fn given_names_keep_their_tail() {
2824        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
2825        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
2826        assert_ne!(a, b);
2827        assert_eq!(
2828            a,
2829            "tests-format-typescript-conformance-types-never-never-ts"
2830        );
2831        assert_eq!(slug(&a).len(), 23);
2832    }
2833
2834    #[test]
2835    fn reports_do_not_carry_sandbox_paths() {
2836        let tmp = std::env::temp_dir();
2837        let line = format!(
2838            "-cwd {}\n",
2839            tmp.join("rust-anything-app-run-4242-7")
2840                .join("cwd")
2841                .display()
2842        );
2843        let stable = stable_paths(&line);
2844        assert!(!stable.contains("4242"), "{stable}");
2845        assert!(stable.contains("$TMPDIR"), "{stable}");
2846        assert_eq!(
2847            stable,
2848            stable_paths(&line.replace("4242-7", "99-0")),
2849            "{stable}"
2850        );
2851    }
2852
2853    fn text_matches_exact(e: &str, a: &str) -> bool {
2854        text_matches(e, a, None)
2855    }
2856
2857    fn norm_with_tolerance(tol: Option<f64>) -> Normalizers {
2858        Normalizers::new(&Config {
2859            schema: SCHEMA.to_string(),
2860            name: "app".to_string(),
2861            run: Vec::new(),
2862            normalize: Vec::new(),
2863            normalizers: BTreeMap::new(),
2864            timeout_secs: default_timeout(),
2865            http: None,
2866            float_tolerance: tol,
2867            float_files: BTreeMap::new(),
2868            unordered: BTreeMap::new(),
2869            effects: None,
2870            fresh: Vec::new(),
2871            recorded: Vec::new(),
2872        })
2873        .unwrap()
2874    }
2875
2876    #[test]
2877    fn unordered_lines_pair_up_by_value_within_the_tolerance() {
2878        let norm = norm_with_tolerance(Some(1e-9));
2879        // `2.0` meets `2.0` and `10.0` meets `9.999999999999999`, but `10.0` sorts before `2.0`
2880        // as text, so pairing the sorted lines by position compared `10.0` against `2.0`.
2881        let expected = b"n 2.0\nn 10.0\n";
2882        let actual = b"n 2.0\nn 9.999999999999999\n";
2883        assert!(compare(&norm, expected, actual, false, false).is_none());
2884        assert!(compare(&norm, expected, actual, false, true).is_none());
2885        // A line that is genuinely different is still reported.
2886        let changed = b"n 2.0\nn 11.0\n";
2887        assert!(compare(&norm, expected, changed, false, true).is_some());
2888        // The order the lines arrive in does not matter.
2889        let swapped = b"n 9.999999999999999\nn 2.0\n";
2890        assert!(compare(&norm, expected, swapped, false, true).is_none());
2891    }
2892
2893    #[test]
2894    fn unordered_lines_pair_up_around_a_wildcard() {
2895        let norm = norm_with_tolerance(Some(1e-9));
2896        // `[..]` takes the line the numeric pairing does not want, so a tolerance and a wildcard
2897        // in the same output do not fight over the ordering.
2898        let expected = b"n 10.0\nn [..]\n";
2899        assert!(compare(&norm, expected, b"n 10.0\nn 2.0\n", false, true).is_none());
2900        assert!(compare(&norm, expected, b"n 2.0\nn 10.0\n", false, true).is_none());
2901        assert!(
2902            compare(
2903                &norm,
2904                expected,
2905                b"n 2.0\nn 9.999999999999999\n",
2906                false,
2907                true
2908            )
2909            .is_none()
2910        );
2911        // Nothing to take the 10.0: both actual lines are far from it.
2912        assert!(compare(&norm, expected, b"n 2.0\nn 3.0\n", false, true).is_some());
2913    }
2914
2915    #[test]
2916    fn unordered_lines_keep_a_plain_permutation_matching() {
2917        let norm = norm_with_tolerance(Some(1e-9));
2918        // The same lines in another order match whatever the numbers look like, and a value
2919        // written two ways stays a difference rather than becoming one by being re-sorted.
2920        assert!(compare(&norm, b"n 2\nn 2.0\n", b"n 2.0\nn 2\n", false, true).is_none());
2921        assert!(compare(&norm, b"n 2\nn 2\n", b"n 2.0\nn 2.0\n", false, true).is_some());
2922    }
2923
2924    #[test]
2925    fn unordered_lines_without_a_tolerance_still_compare_as_text() {
2926        let norm = norm_with_tolerance(None);
2927        let expected = b"b\na\n";
2928        assert!(compare(&norm, expected, b"a\nb\n", false, true).is_none());
2929        assert!(compare(&norm, expected, b"a\nc\n", false, true).is_some());
2930        assert!(compare(&norm, expected, b"a\n", false, true).is_some());
2931        // Without a tolerance a number is text like any other, so this stays a mismatch.
2932        let numeric = b"n 10.0\nn 2.0\n";
2933        assert!(compare(&norm, numeric, b"n 2.0\nn 9.999999999999999\n", false, true).is_some());
2934    }
2935
2936    #[cfg(unix)]
2937    #[test]
2938    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
2939        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
2940            let command = ["/bin/sh".into(), "-c".into(), script.into()];
2941            let start = Instant::now();
2942            let run = run_case(
2943                &command,
2944                Path::new("."),
2945                &Case::new(Vec::new()),
2946                Duration::from_millis(200),
2947                None,
2948                None,
2949            )
2950            .unwrap();
2951            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
2952            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
2953        }
2954    }
2955
2956    #[test]
2957    fn matching_follows_trycmd() {
2958        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
2959        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
2960        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
2961        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
2962        assert!(text_matches_exact(
2963            "head\n...\ntail\n",
2964            "head\n1\n2\ntail\n"
2965        ));
2966        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
2967        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
2968        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
2969    }
2970
2971    #[test]
2972    fn numbers_match_within_the_tolerance() {
2973        let e = "step 1\nenergy 0.3\nat [..]\n";
2974        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
2975        assert!(!text_matches(e, a, None));
2976        assert!(text_matches(e, a, Some(1e-9)));
2977        assert!(!text_matches(
2978            e,
2979            "step 2\nenergy 0.3\nat 12:00\n",
2980            Some(1e-9)
2981        ));
2982        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
2983    }
2984
2985    #[cfg(unix)]
2986    #[test]
2987    fn binary_capture_replays_its_text_companion_byte_for_byte() {
2988        let repo = temp_dir("binary-stream-pair").unwrap();
2989        let run = [
2990            "/bin/sh".to_string(),
2991            "-c".to_string(),
2992            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
2993        ];
2994        let recorded = record(&RecordOptions {
2995            repo: &repo,
2996            run: &run,
2997            inputs: None,
2998            normalize: &["timestamps".into()],
2999            name: None,
3000            traps: false,
3001            timeout_secs: None,
3002            http: None,
3003            server_args: None,
3004            fresh: None,
3005            pace_ms: None,
3006            port: None,
3007            float_tolerance: None,
3008            float_files: &[],
3009            effects: None,
3010            ready_secs: None,
3011        })
3012        .unwrap();
3013        assert_eq!(recorded.cases, 1);
3014        let replayed = replay(&ReplayOptions {
3015            repo: &repo,
3016            build: None,
3017            timeout_secs: None,
3018            port: None,
3019            case: None,
3020        })
3021        .unwrap();
3022        assert_eq!(
3023            (replayed.passed, replayed.total),
3024            (1, 1),
3025            "{:?}",
3026            replayed.failures
3027        );
3028        std::fs::remove_dir_all(repo).unwrap();
3029    }
3030
3031    #[test]
3032    fn noise_is_classified() {
3033        let norm = Normalizers::new(&Config {
3034            schema: SCHEMA.to_string(),
3035            name: "app".to_string(),
3036            run: Vec::new(),
3037            normalize: Vec::new(),
3038            normalizers: BTreeMap::new(),
3039            timeout_secs: 30,
3040            http: None,
3041            float_tolerance: None,
3042            float_files: BTreeMap::new(),
3043            unordered: BTreeMap::new(),
3044            effects: None,
3045            fresh: Vec::new(),
3046            recorded: Vec::new(),
3047        })
3048        .unwrap();
3049        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
3050        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
3051        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
3052        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
3053        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
3054        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
3055        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
3056    }
3057
3058    #[test]
3059    fn unordered_output_matches_in_any_order_but_not_other_lines() {
3060        let norm = Normalizers::new(&Config {
3061            schema: SCHEMA.to_string(),
3062            name: "app".to_string(),
3063            run: Vec::new(),
3064            normalize: Vec::new(),
3065            normalizers: BTreeMap::new(),
3066            timeout_secs: 30,
3067            http: None,
3068            float_tolerance: None,
3069            float_files: BTreeMap::new(),
3070            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
3071            effects: None,
3072            fresh: Vec::new(),
3073            recorded: Vec::new(),
3074        })
3075        .unwrap();
3076        assert!(norm.unordered("c", "stdout"));
3077        assert!(!norm.unordered("c", "stderr"));
3078        let e = b"x=1\ny=2\n";
3079        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
3080        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
3081        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
3082        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
3083    }
3084
3085    #[test]
3086    fn timestamps_cover_javascript_date_strings() {
3087        let re = Regex::new(TIMESTAMP).unwrap();
3088        let line = "Generated on Sat Nov 21 2026 01:30:12 GMT+0300 (Türkiye Standard Time) - ok";
3089        assert_eq!(re.replace_all(line, "[..]"), "Generated on [..] - ok");
3090        assert_eq!(
3091            re.replace_all("Mon Jan 05 2026 09:00:00 GMT-0800", "[..]"),
3092            "[..]"
3093        );
3094        assert_eq!(re.replace_all("at 2026-11-16T10:00:00Z", "[..]"), "at [..]");
3095        assert_eq!(re.replace_all("Saturday 12", "[..]"), "Saturday 12");
3096    }
3097
3098    #[test]
3099    fn noise_becomes_wildcards() {
3100        assert_eq!(
3101            merge_noise(
3102                "start\nnow: 2026-11-16 10:00:01\nend\n",
3103                "start\nnow: 2026-11-16 10:00:02\nend\n"
3104            ),
3105            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
3106        );
3107        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
3108        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
3109        let merged = merge_noise("x 1\n", "x 2\n");
3110        assert!(text_matches_exact(&merged, "x 3\n"));
3111    }
3112
3113    #[test]
3114    fn normalizers_by_name() {
3115        let mut config = Config {
3116            schema: SCHEMA.to_string(),
3117            name: "app".to_string(),
3118            run: Vec::new(),
3119            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
3120            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
3121            timeout_secs: 30,
3122            http: None,
3123            float_tolerance: None,
3124            float_files: BTreeMap::new(),
3125            unordered: BTreeMap::new(),
3126            effects: None,
3127            fresh: Vec::new(),
3128            recorded: Vec::new(),
3129        };
3130        let norm = Normalizers::new(&config).unwrap();
3131        assert_eq!(
3132            norm.apply(
3133                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
3134            ),
3135            "at [..] id [..] [..]"
3136        );
3137        assert_eq!(
3138            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
3139            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
3140        );
3141        config.normalize.push("nope".into());
3142        assert!(Normalizers::new(&config).is_err());
3143    }
3144
3145    #[test]
3146    fn examples_become_cases() {
3147        let repo = temp_dir("examples").unwrap();
3148        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
3149        std::fs::write(
3150            repo.join("README.md"),
3151            "# 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",
3152        )
3153        .unwrap();
3154        let names = vec!["tool".to_string()];
3155        let cases = find_examples(&repo, &names);
3156        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
3157        assert_eq!(
3158            args,
3159            [
3160                vec!["count", "in.txt"],
3161                vec!["words"],
3162                vec!["upper", "x y"],
3163                vec!["sort"],
3164            ]
3165        );
3166        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
3167        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
3168        assert_eq!(cases[2].env["LANG"], "C");
3169        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
3170        std::fs::remove_dir_all(&repo).unwrap();
3171    }
3172
3173    #[test]
3174    fn examples_continued_with_a_backslash_are_joined() {
3175        let repo = temp_dir("continued-examples").unwrap();
3176        std::fs::write(
3177            repo.join("README.md"),
3178            "```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",
3179        )
3180        .unwrap();
3181        std::fs::write(
3182            repo.join("demo.sh"),
3183            "tool sort \\\n  --reverse\n# tool hidden \\\ntool count c.txt\n",
3184        )
3185        .unwrap();
3186        let names = vec!["tool".to_string()];
3187        let args: Vec<Vec<String>> = find_examples(&repo, &names)
3188            .iter()
3189            .map(|c| c.args.clone())
3190            .collect();
3191        std::fs::remove_dir_all(&repo).unwrap();
3192        // Not continuations: a doubled backslash (a literal one), a backslash followed by a space,
3193        // and a backslash at the end of a comment. Joining adds no space of its own (`--mode=loud`).
3194        assert_eq!(
3195            args,
3196            [
3197                vec!["upper", "--loud", "x y"],
3198                vec!["path", "C:\\"],
3199                vec!["count", "in.txt"],
3200                vec!["upper", "--mode=loud"],
3201                vec!["echo", "a "],
3202                vec!["count", "b.txt"],
3203                vec!["sort", "--reverse"],
3204                vec!["count", "c.txt"],
3205            ]
3206        );
3207    }
3208
3209    #[test]
3210    fn traps_keep_the_shape_of_the_case() {
3211        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
3212        base.stdin = Some(b"{\"a\":1}".to_vec());
3213        let (traps, dropped) = trap_cases(&[base]);
3214        assert_eq!(dropped, 0);
3215        assert!(traps.iter().all(|c| c.args[0] == "div"));
3216        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
3217        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
3218        assert!(
3219            traps
3220                .iter()
3221                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
3222        );
3223        let (text, dropped_text) = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
3224        assert_eq!(dropped_text, 0);
3225        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
3226    }
3227
3228    #[test]
3229    fn traps_spread_round_robin_deduplicate_before_truncating_and_count_dropped() {
3230        // 40 distinct commands, each with an int and a string arg -> > 300 unique traps.
3231        let mut bases: Vec<Case> = (0..40)
3232            .map(|i| Case::new(vec![format!("cmd{i:02}"), "7".into(), "hi".into()]))
3233            .collect();
3234        let (unique_traps, unique_dropped) = trap_cases(&bases);
3235        // Adding a duplicate base whose traps all collide must not change the kept traps or
3236        // inflate `dropped`.
3237        bases.push(bases[0].clone());
3238        let (traps, dropped) = trap_cases(&bases);
3239
3240        assert_eq!(unique_traps.len(), MAX_TRAPS);
3241        assert!(unique_dropped > 0);
3242        assert_eq!(traps.len(), MAX_TRAPS);
3243        assert_eq!(dropped, unique_dropped);
3244
3245        // Every single one of the 40 commands gets traps (not just the first few).
3246        for i in 0..40 {
3247            let cmd = format!("cmd{i:02}");
3248            let count = unique_traps.iter().filter(|c| c.args[0] == cmd).count();
3249            assert!(
3250                count >= 7,
3251                "{cmd} only got {count} traps out of {MAX_TRAPS}"
3252            );
3253        }
3254
3255        // Many bases with colliding traps (> 300 raw traps, < 300 unique) must deduplicate
3256        // before truncating so nothing is dropped and unique traps from later bases survive.
3257        let mut dup_bases: Vec<Case> = (1..=40)
3258            .map(|i| Case::new(vec!["dup".into(), i.to_string()]))
3259            .collect();
3260        dup_bases.push(Case::new(vec!["tail".into(), "hello".into()]));
3261        let (dup_traps, dup_dropped) = trap_cases(&dup_bases);
3262        assert_eq!(dup_dropped, 0);
3263        assert!(dup_traps.iter().any(|c| c.args[0] == "tail"));
3264        let keys: BTreeSet<_> = dup_traps.iter().map(Case::key).collect();
3265        assert_eq!(keys.len(), dup_traps.len());
3266    }
3267
3268    #[cfg(unix)]
3269    #[test]
3270    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
3271        let repo = temp_dir("case-name-collisions").unwrap();
3272        let inputs = repo.join("cases.jsonl");
3273        std::fs::write(
3274            &inputs,
3275            concat!(
3276                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
3277                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
3278                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
3279            ),
3280        )
3281        .unwrap();
3282        let recorded = record(&RecordOptions {
3283            repo: &repo,
3284            run: &["/bin/echo".into()],
3285            inputs: Some(&inputs),
3286            normalize: &[],
3287            name: None,
3288            traps: false,
3289            timeout_secs: None,
3290            http: None,
3291            server_args: None,
3292            fresh: None,
3293            pace_ms: None,
3294            port: None,
3295            float_tolerance: None,
3296            float_files: &[],
3297            effects: None,
3298            ready_secs: None,
3299        })
3300        .unwrap();
3301        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
3302        assert_eq!(recorded.cases, 3);
3303        assert_eq!(read("x.stdout"), "one\n");
3304        assert_eq!(read("x-3.stdout"), "two\n");
3305        assert_eq!(read("x-4.stdout"), "three\n");
3306        std::fs::remove_dir_all(repo).unwrap();
3307    }
3308
3309    #[cfg(unix)]
3310    #[test]
3311    fn a_new_run_command_renames_an_inferred_name_but_keeps_a_given_one() {
3312        let repo = temp_dir("rename-on-new-run").unwrap();
3313        std::fs::write(repo.join("one.sh"), "echo one\n").unwrap();
3314        std::fs::write(repo.join("two.sh"), "echo two\n").unwrap();
3315        let rec = |script: &str, name: Option<&str>| {
3316            let run = ["/bin/sh".to_string(), script.to_string()];
3317            record(&RecordOptions {
3318                repo: &repo,
3319                run: &run,
3320                inputs: None,
3321                normalize: &[],
3322                name,
3323                traps: false,
3324                timeout_secs: None,
3325                http: None,
3326                server_args: None,
3327                fresh: None,
3328                pace_ms: None,
3329                port: None,
3330                float_tolerance: None,
3331                float_files: &[],
3332                effects: None,
3333                ready_secs: None,
3334            })
3335            .unwrap();
3336            Config::load(&repo).unwrap().unwrap().name
3337        };
3338        assert_eq!(rec("one.sh", None), "one");
3339        assert_eq!(rec("two.sh", None), "two");
3340        assert_eq!(rec("two.sh", Some("mytool")), "mytool");
3341        assert_eq!(rec("one.sh", None), "mytool");
3342        std::fs::remove_dir_all(&repo).unwrap();
3343    }
3344
3345    #[test]
3346    fn names_come_from_the_run_command_and_manifests() {
3347        let repo = temp_dir("names").unwrap();
3348        std::fs::create_dir_all(repo.join("out")).unwrap();
3349        std::fs::write(
3350            repo.join("package.json"),
3351            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
3352        )
3353        .unwrap();
3354        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
3355        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
3356        std::fs::remove_dir_all(&repo).unwrap();
3357    }
3358
3359    #[test]
3360    fn python_program_names_are_case_insensitive() {
3361        assert!(is_python_program("PYTHON"));
3362        assert!(is_python_program("/tools/Python3.exe"));
3363        assert!(is_python_program("Py.cmd"));
3364        assert!(!is_python_program("pythonw.exe"));
3365    }
3366
3367    #[test]
3368    fn shell_words() {
3369        assert_eq!(
3370            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
3371            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
3372        );
3373        assert!(shell_split("a | b").is_err());
3374        assert!(shell_tokens("echo $(date)").is_none());
3375        assert!(shell_tokens("echo `date`").is_none());
3376        assert_eq!(
3377            shell_split(r"echo \$(date) \`date\`").unwrap(),
3378            ["echo", "$(date)", "`date`"]
3379        );
3380        #[cfg(windows)]
3381        assert_eq!(
3382            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
3383            [r"C:\tools\rust-anything\app.exe", "--flag"]
3384        );
3385        #[cfg(windows)]
3386        assert_eq!(
3387            shell_split(r"run C:\$cache\tool.exe").unwrap(),
3388            ["run", r"C:\$cache\tool.exe"]
3389        );
3390        #[cfg(windows)]
3391        assert_eq!(
3392            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
3393            [r"\\server\share\tool.exe", "--flag"]
3394        );
3395        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
3396    }
3397
3398    #[test]
3399    fn record_and_replay_reject_zero_timeout_and_leave_cases_untouched() {
3400        let repo = temp_dir("zero-timeout").unwrap();
3401        let dir = cases_dir(&repo);
3402        std::fs::create_dir_all(&dir).unwrap();
3403        let sentinel_cfg = format!(
3404            r#"{{"schema":"{SCHEMA}","name":"app","run":["echo","ok"],"timeout_secs":30,"recorded":["no-args"]}}"#
3405        );
3406        let cfg_path = dir.join(CONFIG_FILE);
3407        let case_path = dir.join("no-args.toml");
3408        std::fs::write(&cfg_path, &sentinel_cfg).unwrap();
3409        std::fs::write(&case_path, "stdout = \"ok\\n\"\n").unwrap();
3410
3411        let rec_err = record(&RecordOptions {
3412            repo: &repo,
3413            run: &["definitely-not-run".to_string()],
3414            inputs: None,
3415            normalize: &[],
3416            name: None,
3417            traps: false,
3418            timeout_secs: Some(0),
3419            http: None,
3420            server_args: None,
3421            fresh: None,
3422            pace_ms: None,
3423            port: None,
3424            float_tolerance: None,
3425            float_files: &[],
3426            effects: None,
3427            ready_secs: None,
3428        })
3429        .unwrap_err();
3430        let rec_msg = format!("{rec_err:#}");
3431        assert!(
3432            rec_msg.contains("--timeout") && rec_msg.contains("1 second"),
3433            "{rec_msg}"
3434        );
3435
3436        let rep_err = replay(&ReplayOptions {
3437            repo: &repo,
3438            build: None,
3439            timeout_secs: Some(0),
3440            port: None,
3441            case: None,
3442        })
3443        .unwrap_err();
3444        let rep_msg = format!("{rep_err:#}");
3445        assert!(
3446            rep_msg.contains("--timeout") && rep_msg.contains("1 second"),
3447            "{rep_msg}"
3448        );
3449
3450        assert_eq!(std::fs::read_to_string(&cfg_path).unwrap(), sentinel_cfg);
3451        assert_eq!(
3452            std::fs::read_to_string(&case_path).unwrap(),
3453            "stdout = \"ok\\n\"\n"
3454        );
3455
3456        let zero_cfg = sentinel_cfg.replace(r#""timeout_secs":30"#, r#""timeout_secs":0"#);
3457        std::fs::write(&cfg_path, &zero_cfg).unwrap();
3458        let saved_zero_err = replay(&ReplayOptions {
3459            repo: &repo,
3460            build: None,
3461            timeout_secs: None,
3462            port: None,
3463            case: None,
3464        })
3465        .unwrap_err();
3466        let saved_msg = format!("{saved_zero_err:#}");
3467        assert!(
3468            saved_msg.contains("--timeout") && saved_msg.contains("1 second"),
3469            "{saved_msg}"
3470        );
3471
3472        std::fs::remove_dir_all(repo).unwrap();
3473    }
3474}