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};
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;
29const MAX_INPUT_FILE: u64 = 1 << 20;
30const TIMESTAMP: &str = r"\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";
31const UUID: &str =
32    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";
33
34pub(crate) const INT_TRAPS: [&str; 8] = [
35    "-7",
36    "0",
37    "-1",
38    "2147483648",
39    "9007199254740993",
40    "9223372036854775807",
41    "-9223372036854775808",
42    "18446744073709551616",
43];
44pub(crate) const FLOAT_TRAPS: [&str; 7] = [
45    "-0.0",
46    "0.1",
47    "0.30000000000000004",
48    "1e21",
49    "1e-7",
50    "5e-324",
51    "1.7976931348623157e308",
52];
53pub(crate) const STRING_TRAPS: [&str; 10] = [
54    "héllo wörld",
55    "👍🏽 thumbs",
56    "日本語",
57    "",
58    "e\u{301}",
59    "İstanbul",
60    "straße",
61    "ılık ırmak",
62    "👨\u{200D}👩\u{200D}👧 family",
63    "a\u{00A0}b",
64];
65pub(crate) const STDIN_TRAPS: [&str; 4] = [
66    "naïve café 👍🏽\nsecond line\n",
67    "",
68    "日本語 テキスト\r\nline two\r\n",
69    "  spaced   out  \n\n",
70];
71pub(crate) const JSON_TRAPS: [&str; 2] = [
72    r#"{"zebra":1,"apple":2,"10":3,"2":4,"é":5,"Apple":6}"#,
73    r#"{"n":9007199254740993,"f":1e21,"t":0.1,"neg":-7}"#,
74];
75const NOT_APP_NAMES: [&str; 29] = [
76    "node", "nodejs", "python", "python3", "py", "ruby", "java", "go", "deno", "bun", "tsx",
77    "ts-node", "sh", "bash", "zsh", "cargo", "npx", "npm", "pnpm", "yarn", "uv", "poetry",
78    "bundle", "run", "exec", "env", "sudo", "php", "dotnet",
79];
80
81/// `rust/app-cases/rust-anything.json`: how to run the original, and the normalizers.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Config {
84    pub schema: String,
85    pub name: String,
86    pub run: Vec<String>,
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub normalize: Vec<String>,
89    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
90    pub normalizers: BTreeMap<String, String>,
91    #[serde(default = "default_timeout")]
92    pub timeout_secs: u64,
93    /// Set when the app is a server: cases are requests, in `http/`.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub http: Option<crate::http::HttpConfig>,
96    /// Numbers in the output match within this relative tolerance.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub float_tolerance: Option<f64>,
99    /// Outputs whose line order the original's own runs disagreed on, by case: their lines must
100    /// match in any order.
101    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
102    pub unordered: BTreeMap<String, Vec<String>>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub effects: Option<crate::effects::EffectsConfig>,
105}
106
107pub(crate) fn default_timeout() -> u64 {
108    30
109}
110
111impl Config {
112    pub fn load(repo: &Path) -> Result<Option<Config>> {
113        let path = cases_dir(repo).join(CONFIG_FILE);
114        if !path.exists() {
115            return Ok(None);
116        }
117        let text = std::fs::read_to_string(&path)
118            .with_context(|| format!("reading {}", path.display()))?;
119        Ok(Some(
120            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
121        ))
122    }
123}
124
125pub fn cases_dir(repo: &Path) -> PathBuf {
126    repo.join(CASES_DIR)
127}
128
129/// One line of an `--inputs` file.
130#[derive(Debug, Clone, Default, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct Input {
133    #[serde(default)]
134    pub name: Option<String>,
135    #[serde(default)]
136    pub args: Vec<String>,
137    #[serde(default)]
138    pub stdin: Option<String>,
139    #[serde(default)]
140    pub env: BTreeMap<String, String>,
141    #[serde(default)]
142    pub files: BTreeMap<String, String>,
143}
144
145#[derive(Debug, Clone)]
146struct Case {
147    args: Vec<String>,
148    stdin: Option<Vec<u8>>,
149    env: BTreeMap<String, String>,
150    env_remove: Vec<String>,
151    inherit_env: bool,
152    files: BTreeMap<PathBuf, Vec<u8>>,
153}
154
155impl Case {
156    fn new(args: Vec<String>) -> Self {
157        Case {
158            args,
159            stdin: None,
160            env: BTreeMap::new(),
161            env_remove: Vec::new(),
162            inherit_env: true,
163            files: BTreeMap::new(),
164        }
165    }
166
167    fn key(&self) -> String {
168        serde_json::json!([self.args, self.stdin, self.env, self.files]).to_string()
169    }
170}
171
172#[derive(Debug, Clone, PartialEq, Eq)]
173enum Status {
174    Code(i32),
175    Killed,
176    Timeout,
177}
178
179impl std::fmt::Display for Status {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        match self {
182            Status::Code(c) => write!(f, "exit code {c}"),
183            Status::Killed => write!(f, "killed by a signal"),
184            Status::Timeout => write!(f, "timed out"),
185        }
186    }
187}
188
189struct Run {
190    stdout: Vec<u8>,
191    stderr: Vec<u8>,
192    status: Status,
193    files: BTreeMap<PathBuf, Vec<u8>>,
194    fallback: Option<bool>,
195    effects: Option<Vec<u8>>,
196}
197
198impl Run {
199    fn written(&self, case: &Case) -> BTreeMap<PathBuf, Vec<u8>> {
200        self.files
201            .iter()
202            .filter(|(path, bytes)| case.files.get(*path) != Some(*bytes))
203            .map(|(p, b)| (p.clone(), b.clone()))
204            .collect()
205    }
206}
207
208pub(crate) struct Normalizers {
209    patterns: Vec<Regex>,
210    key_order: bool,
211    float_tolerance: Option<f64>,
212    unordered: BTreeMap<String, Vec<String>>,
213}
214
215impl Normalizers {
216    fn new(config: &Config) -> Result<Self> {
217        let mut sources: Vec<(&str, &str)> = Vec::new();
218        let mut key_order = false;
219        for name in &config.normalize {
220            match name.as_str() {
221                "timestamps" => sources.push((name, TIMESTAMP)),
222                "uuids" => sources.push((name, UUID)),
223                "key-order" => key_order = true,
224                other => bail!(
225                    "unknown normalizer `{other}`: use {} or define it as `name=regex`",
226                    BUILTIN_NORMALIZERS.join(", ")
227                ),
228            }
229        }
230        sources.extend(
231            config
232                .normalizers
233                .iter()
234                .map(|(n, p)| (n.as_str(), p.as_str())),
235        );
236        let patterns = sources
237            .iter()
238            .map(|(name, pattern)| {
239                Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))
240            })
241            .collect::<Result<Vec<_>>>()?;
242        let float_tolerance = config
243            .float_tolerance
244            .map(crate::tolerance::check)
245            .transpose()?;
246        Ok(Normalizers {
247            patterns,
248            key_order,
249            float_tolerance,
250            unordered: config.unordered.clone(),
251        })
252    }
253
254    /// Whether the original's runs disagreed on the line order of this case's `field`.
255    pub(crate) fn unordered(&self, case: &str, field: &str) -> bool {
256        self.unordered
257            .get(case)
258            .is_some_and(|fields| fields.iter().any(|f| f == field))
259    }
260
261    pub(crate) fn apply(&self, text: &str) -> String {
262        let mut out = text.to_string();
263        for p in &self.patterns {
264            out = p.replace_all(&out, "[..]").into_owned();
265        }
266        out
267    }
268
269    fn canonical(&self, text: &str) -> String {
270        if self.key_order {
271            sort_json_text(text)
272        } else {
273            text.to_string()
274        }
275    }
276}
277
278fn sort_value(v: Value) -> Value {
279    match v {
280        Value::Object(map) => {
281            let sorted: BTreeMap<String, Value> =
282                map.into_iter().map(|(k, v)| (k, sort_value(v))).collect();
283            Value::Object(sorted.into_iter().collect())
284        }
285        Value::Array(items) => Value::Array(items.into_iter().map(sort_value).collect()),
286        other => other,
287    }
288}
289
290fn sort_json_text(text: &str) -> String {
291    let trimmed = text.trim();
292    if trimmed.starts_with(['{', '['])
293        && let Ok(v) = serde_json::from_str::<Value>(trimmed)
294    {
295        return serde_json::to_string_pretty(&sort_value(v)).unwrap_or_default() + "\n";
296    }
297    text.split('\n')
298        .map(|line| {
299            let t = line.trim();
300            if t.starts_with(['{', '['])
301                && let Ok(v) = serde_json::from_str::<Value>(t)
302            {
303                return sort_value(v).to_string();
304            }
305            line.to_string()
306        })
307        .collect::<Vec<_>>()
308        .join("\n")
309}
310
311pub(crate) fn temp_dir(tag: &str) -> Result<PathBuf> {
312    static NEXT: AtomicUsize = AtomicUsize::new(0);
313    let dir = std::env::temp_dir().join(format!(
314        "rust-anything-app-{tag}-{}-{}",
315        std::process::id(),
316        NEXT.fetch_add(1, Ordering::SeqCst)
317    ));
318    let _ = std::fs::remove_dir_all(&dir);
319    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
320    Ok(dir)
321}
322
323pub(crate) fn resolve_word(repo: &Path, word: &str) -> String {
324    if word.starts_with('-') {
325        return word.to_string();
326    }
327    let path = repo.join(word);
328    let looks_like_path = word.contains('/') || word.contains('\\') || path.is_file();
329    if looks_like_path && path.exists() {
330        return path
331            .canonical()
332            .unwrap_or(path)
333            .to_string_lossy()
334            .into_owned();
335    }
336    word.to_string()
337}
338
339#[cfg(any(windows, test))]
340fn is_python_program(program: &str) -> bool {
341    Path::new(program)
342        .file_stem()
343        .and_then(|name| name.to_str())
344        .is_some_and(|name| {
345            ["python", "python3", "py"]
346                .iter()
347                .any(|candidate| name.eq_ignore_ascii_case(candidate))
348        })
349}
350
351fn run_case(
352    command: &[String],
353    repo: &Path,
354    case: &Case,
355    timeout: Duration,
356    effects: Option<&crate::effects::EffectsConfig>,
357) -> Result<Run> {
358    let sandbox = temp_dir("run")?;
359    let result = run_in(command, repo, case, timeout, &sandbox, effects);
360    let _ = std::fs::remove_dir_all(&sandbox);
361    result
362}
363
364fn run_in(
365    command: &[String],
366    repo: &Path,
367    case: &Case,
368    timeout: Duration,
369    sandbox: &Path,
370    effects: Option<&crate::effects::EffectsConfig>,
371) -> Result<Run> {
372    let work = sandbox.join("cwd");
373    std::fs::create_dir_all(&work)?;
374    for (path, bytes) in &case.files {
375        let target = work.join(path);
376        if let Some(parent) = target.parent() {
377            std::fs::create_dir_all(parent)?;
378        }
379        std::fs::write(&target, bytes)?;
380    }
381    let log = sandbox.join("fallback.log");
382    let (program, rest) = command.split_first().context("empty command")?;
383    let mut cmd = Command::new(resolve_word(repo, program));
384    cmd.args(rest.iter().map(|w| resolve_word(repo, w)))
385        .args(&case.args)
386        .current_dir(&work)
387        .stdin(Stdio::piped())
388        .stdout(Stdio::piped())
389        .stderr(Stdio::piped());
390    if !case.inherit_env {
391        cmd.env_clear();
392    }
393    #[cfg(windows)]
394    if is_python_program(program)
395        && (!case.inherit_env || std::env::var_os("PYTHONIOENCODING").is_none())
396    {
397        // Python otherwise inherits the legacy Windows console code page even though its stdio
398        // is piped. UTF-8 keeps generated Unicode traps recordable; a case can still override it.
399        cmd.env("PYTHONIOENCODING", "utf-8");
400    }
401    for key in &case.env_remove {
402        cmd.env_remove(key);
403    }
404    let sinks = effects
405        .map(|config| -> Result<_> {
406            let sinks = crate::effects::Sinks::start(config)?;
407            sinks.reset(repo)?;
408            Ok(sinks)
409        })
410        .transpose()?;
411    if let Some(sinks) = &sinks {
412        cmd.envs(sinks.env());
413    }
414    cmd.envs(&case.env).env(FALLBACK_ENV, &log);
415    #[cfg(unix)]
416    {
417        use std::os::unix::process::CommandExt as _;
418        cmd.process_group(0);
419    }
420    let mut child = cmd
421        .spawn()
422        .with_context(|| format!("running `{}`", command.join(" ")))?;
423    let stdin = child.stdin.take();
424    let input = case.stdin.clone().unwrap_or_default();
425    let writer = std::thread::spawn(move || {
426        if let Some(mut pipe) = stdin {
427            let _ = pipe.write_all(&input);
428        }
429    });
430    let mut out_pipe = child.stdout.take().context("no stdout pipe")?;
431    let mut err_pipe = child.stderr.take().context("no stderr pipe")?;
432    let out_reader = std::thread::spawn(move || {
433        let mut buf = Vec::new();
434        let _ = out_pipe.read_to_end(&mut buf);
435        buf
436    });
437    let err_reader = std::thread::spawn(move || {
438        let mut buf = Vec::new();
439        let _ = err_pipe.read_to_end(&mut buf);
440        buf
441    });
442    let start = Instant::now();
443    let status = loop {
444        if let Some(s) = child.try_wait()? {
445            #[cfg(unix)]
446            let pipes_done =
447                writer.is_finished() && out_reader.is_finished() && err_reader.is_finished();
448            #[cfg(not(unix))]
449            let pipes_done = true;
450            if pipes_done {
451                break s.code().map_or(Status::Killed, Status::Code);
452            }
453        }
454        if start.elapsed() > timeout {
455            #[cfg(unix)]
456            {
457                let _ = Command::new("/bin/kill")
458                    .args(["-KILL", "--", &format!("-{}", child.id())])
459                    .stderr(Stdio::null())
460                    .status();
461            }
462            let _ = child.kill();
463            let _ = child.wait();
464            break Status::Timeout;
465        }
466        std::thread::sleep(Duration::from_millis(2));
467    };
468    let _ = writer.join();
469    let stdout = out_reader.join().unwrap_or_default();
470    let stderr = err_reader.join().unwrap_or_default();
471
472    let mut cwd_forms = vec![work.to_string_lossy().into_owned()];
473    if let Ok(real) = work.canonical() {
474        cwd_forms.insert(0, real.to_string_lossy().into_owned());
475    }
476    let redact = |bytes: Vec<u8>| -> Vec<u8> {
477        match String::from_utf8(bytes) {
478            Ok(mut text) => {
479                for form in &cwd_forms {
480                    text = text.replace(form.as_str(), "[CWD]");
481                }
482                text.into_bytes()
483            }
484            Err(e) => e.into_bytes(),
485        }
486    };
487    let mut files = BTreeMap::new();
488    for path in walk_files(&work) {
489        let rel = path.strip_prefix(&work).unwrap_or(&path).to_path_buf();
490        files.insert(rel, redact(std::fs::read(&path).unwrap_or_default()));
491    }
492    let fallback = std::fs::metadata(&log).ok().map(|m| m.len() > 0);
493    let effects = sinks.map(|s| redact(s.take(repo)));
494    Ok(Run {
495        stdout: redact(stdout),
496        stderr: redact(stderr),
497        status,
498        files,
499        fallback,
500        effects,
501    })
502}
503
504fn walk_files(root: &Path) -> Vec<PathBuf> {
505    let mut out = Vec::new();
506    let mut stack = vec![root.to_path_buf()];
507    while let Some(dir) = stack.pop() {
508        let Ok(entries) = std::fs::read_dir(&dir) else {
509            continue;
510        };
511        for entry in entries.flatten() {
512            let Ok(kind) = entry.file_type() else {
513                continue;
514            };
515            if kind.is_dir() {
516                stack.push(entry.path());
517            } else if kind.is_file() {
518                out.push(entry.path());
519            }
520        }
521    }
522    out.sort();
523    out
524}
525
526fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
527    let threads = std::thread::available_parallelism()
528        .map_or(4, |n| n.get())
529        .clamp(1, 8);
530    let next = AtomicUsize::new(0);
531    let results: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
532    std::thread::scope(|s| {
533        for _ in 0..threads {
534            s.spawn(|| {
535                loop {
536                    let i = next.fetch_add(1, Ordering::SeqCst);
537                    let Some(item) = items.get(i) else { break };
538                    let r = f(item);
539                    if let Ok(mut slot) = results[i].lock() {
540                        *slot = Some(r);
541                    }
542                }
543            });
544        }
545    });
546    results
547        .into_iter()
548        .filter_map(|m| m.into_inner().ok().flatten())
549        .collect()
550}
551
552#[derive(Debug, Clone, PartialEq, Eq)]
553pub(crate) struct Tok {
554    pub(crate) text: String,
555    pub(crate) op: bool,
556}
557
558pub(crate) fn shell_tokens(line: &str) -> Option<Vec<Tok>> {
559    let mut toks = Vec::new();
560    let mut cur = String::new();
561    let mut in_tok = false;
562    let mut chars = line.chars().peekable();
563    let flush = |toks: &mut Vec<Tok>, cur: &mut String, in_tok: &mut bool| {
564        if *in_tok {
565            toks.push(Tok {
566                text: std::mem::take(cur),
567                op: false,
568            });
569            *in_tok = false;
570        }
571    };
572    while let Some(c) = chars.next() {
573        match c {
574            ' ' | '\t' => flush(&mut toks, &mut cur, &mut in_tok),
575            '\'' => {
576                in_tok = true;
577                loop {
578                    match chars.next()? {
579                        '\'' => break,
580                        x => cur.push(x),
581                    }
582                }
583            }
584            '"' => {
585                in_tok = true;
586                loop {
587                    match chars.next()? {
588                        '"' => break,
589                        '\\' => match chars.next()? {
590                            x @ ('"' | '\\' | '$' | '`') => cur.push(x),
591                            x => {
592                                cur.push('\\');
593                                cur.push(x);
594                            }
595                        },
596                        '`' => return None,
597                        '$' if chars.peek() == Some(&'(') => return None,
598                        x => cur.push(x),
599                    }
600                }
601            }
602            '\\' => {
603                in_tok = true;
604                let mut following = chars.clone();
605                let next = following.next();
606                let after_next = following.next();
607                let escaped_substitution = next == Some('$') && after_next == Some('(');
608                let unc_prefix = cur.is_empty()
609                    && next == Some('\\')
610                    && after_next
611                        .is_some_and(|c| !c.is_whitespace() && !"'\"\\|<>&;$`".contains(c));
612                if cfg!(windows)
613                    && (unc_prefix
614                        || (!escaped_substitution
615                            && !chars
616                                .peek()
617                                .is_some_and(|c| c.is_whitespace() || "'\"\\|<>&;`".contains(*c))))
618                {
619                    cur.push('\\');
620                } else if let Some(x) = chars.next() {
621                    cur.push(x);
622                }
623            }
624            '|' | '<' | '>' | ';' | '&' => {
625                flush(&mut toks, &mut cur, &mut in_tok);
626                let mut op = c.to_string();
627                while let Some(&n) = chars.peek() {
628                    if !"|<>&".contains(n) {
629                        break;
630                    }
631                    op.push(n);
632                    chars.next();
633                }
634                toks.push(Tok { text: op, op: true });
635            }
636            '#' if !in_tok => break,
637            '`' => return None,
638            '$' if chars.peek() == Some(&'(') => return None,
639            _ => {
640                in_tok = true;
641                cur.push(c);
642            }
643        }
644    }
645    flush(&mut toks, &mut cur, &mut in_tok);
646    Some(toks)
647}
648
649/// Splits a command line into words, shell-style quoting, no shell operators.
650pub fn shell_split(line: &str) -> Result<Vec<String>> {
651    let toks = shell_tokens(line).with_context(|| format!("cannot split `{line}`"))?;
652    if let Some(op) = toks.iter().find(|t| t.op) {
653        bail!(
654            "`{line}` uses the shell operator `{}`: put the pipeline in a script and give its path",
655            op.text
656        );
657    }
658    Ok(toks.into_iter().map(|t| t.text).collect())
659}
660
661pub(crate) fn shell_quote(word: &str) -> String {
662    let plain = !word.is_empty()
663        && word
664            .chars()
665            .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
666    if plain {
667        word.to_string()
668    } else {
669        format!("'{}'", word.replace('\'', r"'\''"))
670    }
671}
672
673fn lines(text: &str) -> Vec<&str> {
674    let text = text.strip_suffix('\n').unwrap_or(text);
675    if text.is_empty() {
676        return Vec::new();
677    }
678    text.split('\n')
679        .map(|l| l.strip_suffix('\r').unwrap_or(l))
680        .collect()
681}
682
683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
684enum Op {
685    Equal(usize, usize),
686    Delete(usize),
687    Insert(usize),
688}
689
690fn diff_ops<A, B>(a: &[A], b: &[B], eq: impl Fn(&A, &B) -> bool) -> Vec<Op> {
691    let mut head = 0;
692    while head < a.len() && head < b.len() && eq(&a[head], &b[head]) {
693        head += 1;
694    }
695    let mut tail = 0;
696    while tail < a.len() - head
697        && tail < b.len() - head
698        && eq(&a[a.len() - 1 - tail], &b[b.len() - 1 - tail])
699    {
700        tail += 1;
701    }
702    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);
703    let mut ops: Vec<Op> = (0..head).map(|i| Op::Equal(i, i)).collect();
704    let (n, m) = (am.len(), bm.len());
705    if n * m <= 4_000_000 {
706        let mut lcs = vec![vec![0u32; m + 1]; n + 1];
707        for i in (0..n).rev() {
708            for j in (0..m).rev() {
709                lcs[i][j] = if eq(&am[i], &bm[j]) {
710                    lcs[i + 1][j + 1] + 1
711                } else {
712                    lcs[i + 1][j].max(lcs[i][j + 1])
713                };
714            }
715        }
716        let (mut i, mut j) = (0, 0);
717        while i < n || j < m {
718            if i < n && j < m && eq(&am[i], &bm[j]) {
719                ops.push(Op::Equal(head + i, head + j));
720                i += 1;
721                j += 1;
722            } else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
723                ops.push(Op::Delete(head + i));
724                i += 1;
725            } else {
726                ops.push(Op::Insert(head + j));
727                j += 1;
728            }
729        }
730    } else {
731        ops.extend((0..n).map(|i| Op::Delete(head + i)));
732        ops.extend((0..m).map(|j| Op::Insert(head + j)));
733    }
734    ops.extend((0..tail).map(|k| Op::Equal(a.len() - tail + k, b.len() - tail + k)));
735    ops
736}
737
738pub(crate) fn line_matches(expected: &str, actual: &str) -> bool {
739    if !expected.contains("[..]") {
740        return expected == actual;
741    }
742    let parts: Vec<&str> = expected.split("[..]").collect();
743    let (first, last) = (parts[0], parts[parts.len() - 1]);
744    let Some(rest) = actual.strip_prefix(first) else {
745        return false;
746    };
747    let Some(mut rest) = rest.strip_suffix(last) else {
748        return false;
749    };
750    for mid in &parts[1..parts.len() - 1] {
751        match rest.find(mid) {
752            Some(i) => rest = &rest[i + mid.len()..],
753            None => return false,
754        }
755    }
756    true
757}
758
759/// A line within the float tolerance, for lines without wildcards.
760fn line_matches_within(expected: &str, actual: &str, tol: Option<f64>) -> bool {
761    line_matches(expected, actual)
762        || tol.is_some_and(|t| {
763            !expected.contains("[..]") && crate::tolerance::line_close(expected, actual, t)
764        })
765}
766
767/// trycmd's matching: `[..]` is any text within a line, a `...` line is any number of lines.
768fn text_matches(expected: &str, actual: &str, tol: Option<f64>) -> bool {
769    let (e, a) = (lines(expected), lines(actual));
770    let m = a.len();
771    let mut next = vec![false; m + 1];
772    next[m] = true;
773    for line in e.iter().rev() {
774        let mut cur = vec![false; m + 1];
775        for j in (0..=m).rev() {
776            cur[j] = if *line == "..." {
777                next[j] || (j < m && cur[j + 1])
778            } else {
779                j < m && line_matches_within(line, a[j], tol) && next[j + 1]
780            };
781        }
782        next = cur;
783    }
784    next[0]
785}
786
787fn render_diff(expected: &str, actual: &str, tol: Option<f64>) -> String {
788    let (e, a) = (lines(expected), lines(actual));
789    let ops = diff_ops(&e, &a, |x, y| line_matches_within(x, y, tol));
790    let changed: Vec<bool> = ops.iter().map(|op| !matches!(op, Op::Equal(..))).collect();
791    let near = |k: usize| {
792        let lo = k.saturating_sub(3);
793        let hi = (k + 4).min(ops.len());
794        changed[lo..hi].iter().any(|c| *c)
795    };
796    let mut out = String::new();
797    let mut skipped = false;
798    for (k, op) in ops.iter().enumerate() {
799        match op {
800            Op::Equal(_, j) if near(k) => {
801                skipped = false;
802                out += &format!("  {}\n", a[*j]);
803            }
804            Op::Equal(..) => {
805                if !skipped {
806                    out += "  ⋮\n";
807                    skipped = true;
808                }
809            }
810            Op::Delete(i) => {
811                skipped = false;
812                out += &format!("- {}\n", e[*i]);
813            }
814            Op::Insert(j) => {
815                skipped = false;
816                out += &format!("+ {}\n", a[*j]);
817            }
818        }
819    }
820    let trail = |s: &str| s.ends_with('\n') || s.is_empty();
821    if out.is_empty() || trail(expected) != trail(actual) {
822        out += &format!(
823            "(trailing newline: expected {}, got {})\n",
824            trail(expected),
825            trail(actual)
826        );
827    }
828    out
829}
830
831fn tokens(line: &str) -> Vec<&str> {
832    let mut out = Vec::new();
833    let mut start = None;
834    for (i, c) in line.char_indices() {
835        if c.is_alphanumeric() {
836            start.get_or_insert(i);
837        } else {
838            if let Some(s) = start.take() {
839                out.push(&line[s..i]);
840            }
841            out.push(&line[i..i + c.len_utf8()]);
842        }
843    }
844    if let Some(s) = start {
845        out.push(&line[s..]);
846    }
847    out
848}
849
850pub(crate) fn merge_line(a: &str, b: &str) -> String {
851    let (ta, tb) = (tokens(a), tokens(b));
852    if ta.len() != tb.len() {
853        return "[..]".to_string();
854    }
855    let mut out = String::new();
856    for (x, y) in ta.iter().zip(&tb) {
857        if x == y {
858            out += x;
859        } else if !out.ends_with("[..]") {
860            out += "[..]";
861        }
862    }
863    out
864}
865
866/// Two runs of the original: what they agree on stays, what differs becomes a wildcard.
867fn merge_noise(a: &str, b: &str) -> String {
868    if a == b {
869        return a.to_string();
870    }
871    let (la, lb): (Vec<&str>, Vec<&str>) = (a.split('\n').collect(), b.split('\n').collect());
872    let ops = diff_ops(&la, &lb, |x, y| x == y);
873    let mut out: Vec<String> = Vec::new();
874    let (mut dels, mut ins): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
875    let flush = |out: &mut Vec<String>, dels: &mut Vec<&str>, ins: &mut Vec<&str>| {
876        if dels.is_empty() && ins.is_empty() {
877            return;
878        }
879        if dels.len() == ins.len() {
880            for (x, y) in dels.iter().zip(ins.iter()) {
881                out.push(merge_line(x, y));
882            }
883        } else if out.last().map(String::as_str) != Some("...") {
884            out.push("...".to_string());
885        }
886        dels.clear();
887        ins.clear();
888    };
889    for op in ops {
890        match op {
891            Op::Equal(i, _) => {
892                flush(&mut out, &mut dels, &mut ins);
893                out.push(la[i].to_string());
894            }
895            Op::Delete(i) => dels.push(la[i]),
896            Op::Insert(j) => ins.push(lb[j]),
897        }
898    }
899    flush(&mut out, &mut dels, &mut ins);
900    out.join("\n")
901}
902
903fn stem(word: &str) -> String {
904    Path::new(word)
905        .file_stem()
906        .map(|s| s.to_string_lossy().to_lowercase())
907        .unwrap_or_default()
908}
909
910/// Names the app is invoked by, most specific first.
911fn app_names(repo: &Path, run: &[String], explicit: Option<&str>) -> Vec<String> {
912    let mut names: Vec<String> = Vec::new();
913    let mut add = |name: &str| {
914        let name = name.rsplit('/').next().unwrap_or(name).to_lowercase();
915        if !name.is_empty() && !NOT_APP_NAMES.contains(&name.as_str()) && !names.contains(&name) {
916            names.push(name);
917        }
918    };
919    if let Some(name) = explicit {
920        add(name);
921    }
922    for word in run {
923        let path = repo.join(word);
924        if word.starts_with('-') || path.is_dir() || Path::new(word).is_dir() {
925            continue;
926        }
927        add(&stem(word));
928    }
929    if let Ok(text) = std::fs::read_to_string(repo.join("package.json"))
930        && let Ok(pkg) = serde_json::from_str::<Value>(&text)
931    {
932        match &pkg["bin"] {
933            Value::String(_) => add(pkg["name"].as_str().unwrap_or_default()),
934            Value::Object(map) => map.keys().for_each(|k| add(k)),
935            _ => {}
936        }
937    }
938    if let Ok(text) = std::fs::read_to_string(repo.join("pyproject.toml"))
939        && let Ok(doc) = text.parse::<DocumentMut>()
940    {
941        for table in [
942            doc.get("project").and_then(|p| p.get("scripts")),
943            doc.get("tool")
944                .and_then(|t| t.get("poetry"))
945                .and_then(|p| p.get("scripts")),
946        ]
947        .into_iter()
948        .flatten()
949        {
950            if let Some(t) = table.as_table_like() {
951                t.iter().for_each(|(k, _)| add(k));
952            }
953        }
954    }
955    for (dir, dirs_only) in [("cmd", true), ("bin", false), ("exe", false)] {
956        let Ok(entries) = std::fs::read_dir(repo.join(dir)) else {
957            continue;
958        };
959        let mut found: Vec<String> = entries
960            .flatten()
961            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir() == dirs_only))
962            .map(|e| stem(&e.file_name().to_string_lossy()))
963            .collect();
964        found.sort();
965        found.iter().for_each(|n| add(n));
966    }
967    names
968}
969
970fn safe_relative(arg: &str) -> bool {
971    let p = Path::new(arg);
972    !arg.is_empty()
973        && !arg.starts_with('-')
974        && p.components().all(|c| matches!(c, Component::Normal(_)))
975}
976
977fn read_input_file(candidates: &[PathBuf]) -> Option<Vec<u8>> {
978    candidates
979        .iter()
980        .find(|p| p.is_file() && std::fs::metadata(p).is_ok_and(|m| m.len() <= MAX_INPUT_FILE))
981        .and_then(|p| std::fs::read(p).ok())
982}
983
984fn parse_example(line: &str, names: &[String], repo: &Path, doc_dir: &Path) -> Option<Case> {
985    let toks = shell_tokens(line)?;
986    let ops: Vec<usize> = (0..toks.len()).filter(|&i| toks[i].op).collect();
987    let words = |range: &[Tok]| -> Vec<String> { range.iter().map(|t| t.text.clone()).collect() };
988    let lookup = |arg: &str| -> Option<Vec<u8>> {
989        if !safe_relative(arg) {
990            return None;
991        }
992        read_input_file(&[repo.join(arg), doc_dir.join(arg)])
993    };
994    let (main, stdin): (Vec<String>, Option<Vec<u8>>) = match ops.as_slice() {
995        [] => (words(&toks), None),
996        [i] if toks[*i].text == "|" => {
997            let feed = words(&toks[..*i]);
998            let stdin = match feed.first().map(String::as_str) {
999                Some("echo") => {
1000                    let newline = feed.get(1).map(String::as_str) != Some("-n");
1001                    let text: Vec<&str> = feed[1..]
1002                        .iter()
1003                        .map(String::as_str)
1004                        .filter(|w| !matches!(*w, "-n" | "-e"))
1005                        .collect();
1006                    let mut text = text.join(" ");
1007                    if newline {
1008                        text.push('\n');
1009                    }
1010                    text.into_bytes()
1011                }
1012                Some("printf") if feed.len() == 2 => feed[1]
1013                    .replace("\\n", "\n")
1014                    .replace("\\t", "\t")
1015                    .into_bytes(),
1016                Some("cat") if feed.len() == 2 => lookup(&feed[1])?,
1017                _ => return None,
1018            };
1019            (words(&toks[*i + 1..]), Some(stdin))
1020        }
1021        [i] if toks[*i].text == "<" && *i + 2 == toks.len() => {
1022            (words(&toks[..*i]), Some(lookup(&toks[*i + 1].text)?))
1023        }
1024        _ => return None,
1025    };
1026    let mut env = BTreeMap::new();
1027    let mut rest = main.as_slice();
1028    while let Some((first, tail)) = rest.split_first() {
1029        let Some((k, v)) = first.split_once('=') else {
1030            break;
1031        };
1032        if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1033            break;
1034        }
1035        env.insert(k.to_string(), v.to_string());
1036        rest = tail;
1037    }
1038    let (prog, args) = rest.split_first()?;
1039    if !names.contains(&stem(prog)) {
1040        return None;
1041    }
1042    let mut case = Case::new(args.to_vec());
1043    case.env = env;
1044    case.stdin = stdin;
1045    for arg in args {
1046        if let Some(bytes) = lookup(arg) {
1047            case.files.insert(PathBuf::from(arg), bytes);
1048        }
1049    }
1050    Some(case)
1051}
1052
1053fn find_examples(repo: &Path, names: &[String]) -> Vec<Case> {
1054    if names.is_empty() {
1055        return Vec::new();
1056    }
1057    scan_examples(repo, |line, doc_dir| {
1058        parse_example(line, names, repo, doc_dir)
1059    })
1060}
1061
1062/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
1063/// with the folder of the file it came from.
1064pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
1065    let skip = ["node_modules", "target", "vendor", ".git"];
1066    let walker = crate::walk::filtered(repo, move |e| {
1067        let name = e.file_name().to_string_lossy();
1068        !skip.contains(&name.as_ref())
1069    })
1070    .max_depth(Some(4))
1071    .sort_by_file_name(|a, b| a.cmp(b))
1072    .build();
1073    let rust_dir = repo.join("rust");
1074    let mut out = Vec::new();
1075    for entry in walker.flatten() {
1076        let path = entry.path();
1077        if path.starts_with(&rust_dir) || !path.is_file() {
1078            continue;
1079        }
1080        let ext = path
1081            .extension()
1082            .map(|e| e.to_string_lossy().to_lowercase())
1083            .unwrap_or_default();
1084        let markdown = matches!(ext.as_str(), "md" | "markdown");
1085        if !markdown && ext != "sh" {
1086            continue;
1087        }
1088        let Ok(text) = std::fs::read_to_string(path) else {
1089            continue;
1090        };
1091        let doc_dir = path.parent().unwrap_or(repo);
1092        let mut fence: Option<String> = None;
1093        for raw in text.lines() {
1094            let line = raw.trim();
1095            if markdown {
1096                if line.starts_with("```") || line.starts_with("~~~") {
1097                    fence = match fence {
1098                        Some(_) => None,
1099                        None => Some(
1100                            line.trim_start_matches(['`', '~'])
1101                                .split_whitespace()
1102                                .next()
1103                                .unwrap_or_default()
1104                                .to_lowercase(),
1105                        ),
1106                    };
1107                    continue;
1108                }
1109                let Some(lang) = &fence else { continue };
1110                let candidate = match line.strip_prefix("$ ") {
1111                    Some(rest) => rest,
1112                    None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => line,
1113                    None => continue,
1114                };
1115                if let Some(case) = parse(candidate, doc_dir) {
1116                    out.push(case);
1117                }
1118            } else {
1119                let candidate = line.strip_prefix("$ ").unwrap_or(line);
1120                if let Some(case) = parse(candidate, doc_dir) {
1121                    out.push(case);
1122                }
1123            }
1124        }
1125    }
1126    out
1127}
1128
1129fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1130    let text =
1131        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1132    let mut out = Vec::new();
1133    for (n, line) in text.lines().enumerate() {
1134        if line.trim().is_empty() {
1135            continue;
1136        }
1137        let input: Input = serde_json::from_str(line)
1138            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1139        let mut case = Case::new(input.args);
1140        case.stdin = input.stdin.map(String::into_bytes);
1141        case.env = input.env;
1142        for (file, content) in input.files {
1143            ensure!(
1144                safe_relative(&file),
1145                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1146                path.display(),
1147                n + 1
1148            );
1149            case.files.insert(PathBuf::from(file), content.into_bytes());
1150        }
1151        out.push((input.name, case));
1152    }
1153    Ok(out)
1154}
1155
1156pub(crate) fn is_word(arg: &str) -> bool {
1157    let mut chars = arg.chars();
1158    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1159        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1160}
1161
1162fn trap_cases(bases: &[Case]) -> Vec<Case> {
1163    let mut out = Vec::new();
1164    for base in bases {
1165        for (i, arg) in base.args.iter().enumerate() {
1166            if i == 0 && is_word(arg) {
1167                continue;
1168            }
1169            let number = arg.parse::<f64>().is_ok();
1170            if arg.starts_with('-') && !number {
1171                continue;
1172            }
1173            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1174                INT_TRAPS.to_vec()
1175            } else if number && arg.contains(['.', 'e', 'E']) {
1176                FLOAT_TRAPS.to_vec()
1177            } else if base.files.contains_key(Path::new(arg)) {
1178                vec!["missing-input.txt"]
1179            } else {
1180                STRING_TRAPS.to_vec()
1181            };
1182            for v in values.into_iter().filter(|v| v != arg) {
1183                let mut case = base.clone();
1184                case.args[i] = v.to_string();
1185                out.push(case);
1186            }
1187        }
1188        if let Some(stdin) = &base.stdin {
1189            let json = std::str::from_utf8(stdin)
1190                .ok()
1191                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1192                .is_some_and(|v| v.is_object() || v.is_array());
1193            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1194            for v in values {
1195                let mut case = base.clone();
1196                case.stdin = Some(v.as_bytes().to_vec());
1197                out.push(case);
1198            }
1199        }
1200    }
1201    out.truncate(MAX_TRAPS);
1202    out
1203}
1204
1205pub(crate) fn slug(text: &str) -> String {
1206    slug_max(text, 24)
1207}
1208
1209/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
1210/// only past the 24th character stay apart.
1211pub(crate) fn given_slug(text: &str) -> String {
1212    slug_max(text, 96)
1213}
1214
1215fn slug_max(text: &str, max: usize) -> String {
1216    let mut out = String::new();
1217    for c in text.chars() {
1218        if c.is_ascii_alphanumeric() {
1219            out.push(c.to_ascii_lowercase());
1220        } else if !out.ends_with('-') && !out.is_empty() {
1221            out.push('-');
1222        }
1223    }
1224    out.truncate(max);
1225    out.trim_end_matches('-').to_string()
1226}
1227
1228pub struct RecordOptions<'a> {
1229    pub repo: &'a Path,
1230    /// The command that runs the original; taken from the saved config when empty.
1231    pub run: &'a [String],
1232    pub inputs: Option<&'a Path>,
1233    /// Built-in normalizer names, or `name=regex` for your own.
1234    pub normalize: &'a [String],
1235    pub name: Option<&'a str>,
1236    pub traps: bool,
1237    pub timeout_secs: Option<u64>,
1238    /// The app is a server: record requests instead of command lines.
1239    pub http: bool,
1240    /// The port a server always listens on (implies `http`); unset, it gets a free one through
1241    /// `PORT` and `{port}`.
1242    pub port: Option<u16>,
1243    /// Servers: arguments every start gets after its command, the original's and every build's
1244    /// (implies `http`); kept from the last recording when empty.
1245    pub server_args: &'a [String],
1246    /// Servers: repository files or folders copied into a fresh working directory before every
1247    /// start (implies `http`); kept from the last recording when empty.
1248    pub fresh: &'a [String],
1249    /// Servers: milliseconds to wait after each response, for work the server does after
1250    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
1251    pub pace_ms: Option<u64>,
1252    /// Numbers in the output match within this tolerance; kept from the last recording when
1253    /// `None`, removed with 0.
1254    pub float_tolerance: Option<f64>,
1255    pub effects: Option<crate::effects::EffectsConfig>,
1256}
1257
1258#[derive(Debug, Serialize)]
1259pub struct RecordOutcome {
1260    pub dir: PathBuf,
1261    pub run: Vec<String>,
1262    pub cases: usize,
1263    pub examples: usize,
1264    pub inputs: usize,
1265    pub traps: usize,
1266    /// Cases where the two runs of the original differed.
1267    pub noisy: Vec<String>,
1268    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1269    /// in any order, `lines` became a `...` that matches anything.
1270    pub noise: Vec<Noise>,
1271    /// Cases whose exit code or written files differed between the two runs.
1272    pub unstable: Vec<String>,
1273    /// Cases not written: the original timed out or did not answer.
1274    pub timed_out: Vec<String>,
1275}
1276
1277struct Recorded {
1278    stdout: Vec<u8>,
1279    stderr: Vec<u8>,
1280    effects: Option<Vec<u8>>,
1281    status: Status,
1282    written: BTreeMap<PathBuf, Vec<u8>>,
1283    binary: bool,
1284    noise: Vec<(String, NoiseKind)>,
1285    unstable: bool,
1286}
1287
1288/// How two runs of the original disagreed.
1289#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1290#[serde(rename_all = "lowercase")]
1291pub enum NoiseKind {
1292    /// Values within lines changed (times, ids): those parts are wildcards now.
1293    Values,
1294    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1295    /// in any order, and a port must produce exactly those lines.
1296    Order,
1297    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1298    /// anything. Look at these first.
1299    Lines,
1300}
1301
1302#[derive(Debug, Clone, Serialize)]
1303pub struct Noise {
1304    pub case: String,
1305    pub field: String,
1306    pub kind: NoiseKind,
1307}
1308
1309fn same_lines_any_order(a: &str, b: &str) -> bool {
1310    let (mut la, mut lb) = (lines(a), lines(b));
1311    la.sort_unstable();
1312    lb.sort_unstable();
1313    la == lb
1314}
1315
1316pub(crate) fn settle_text(
1317    norm: &Normalizers,
1318    a: &[u8],
1319    b: &[u8],
1320) -> (Vec<u8>, Option<NoiseKind>, bool) {
1321    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1322        (Ok(a), Ok(b)) => {
1323            let (a, b) = (norm.apply(a), norm.apply(b));
1324            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1325                (a.into_bytes(), None, false)
1326            } else if same_lines_any_order(&a, &b) {
1327                (a.into_bytes(), Some(NoiseKind::Order), false)
1328            } else {
1329                let merged = merge_noise(&a, &b);
1330                let kind = if merged.split('\n').any(|l| l == "...") {
1331                    NoiseKind::Lines
1332                } else {
1333                    NoiseKind::Values
1334                };
1335                (merged.into_bytes(), Some(kind), false)
1336            }
1337        }
1338        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1339    }
1340}
1341
1342fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1343    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1344        .iter()
1345        .any(|bytes| std::str::from_utf8(bytes).is_err());
1346    let settle_stream = |a: &[u8], b: &[u8]| {
1347        if binary {
1348            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1349        } else {
1350            let (bytes, noise, _) = settle_text(norm, a, b);
1351            (bytes, noise)
1352        }
1353    };
1354    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1355    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1356    let (effects, fx_noise) = match (&one.effects, &two.effects) {
1357        (Some(a), Some(b)) => {
1358            let (bytes, noise, _) = settle_text(norm, a, b);
1359            (Some(bytes), noise)
1360        }
1361        _ => (None, None),
1362    };
1363    let (w1, w2) = (one.written(case), two.written(case));
1364    let mut unstable = one.status != two.status
1365        || !w1.keys().eq(w2.keys())
1366        || (binary && (out_noise.is_some() || err_noise.is_some()));
1367    let mut noise: Vec<(String, NoiseKind)> = [
1368        ("stdout", out_noise),
1369        ("stderr", err_noise),
1370        (crate::effects::EXT, fx_noise),
1371    ]
1372    .into_iter()
1373    .filter_map(|(f, k)| Some((f.to_string(), k?)))
1374    .collect();
1375    let mut written = BTreeMap::new();
1376    for (path, a) in &w1 {
1377        let b = w2.get(path).unwrap_or(a);
1378        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1379        unstable |= file_bin && file_noise.is_some();
1380        if let Some(kind) = file_noise {
1381            noise.push((format!("file {}", path.display()), kind));
1382        }
1383        written.insert(path.clone(), bytes);
1384    }
1385    Recorded {
1386        stdout,
1387        stderr,
1388        effects,
1389        status: one.status.clone(),
1390        written,
1391        binary,
1392        noise,
1393        unstable,
1394    }
1395}
1396
1397fn dotted() -> Table {
1398    let mut t = Table::new();
1399    t.set_dotted(true);
1400    t
1401}
1402
1403fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1404    for ext in ["stdin", "stdout", "stderr", crate::effects::EXT] {
1405        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1406    }
1407    for ext in ["in", "out"] {
1408        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1409    }
1410    let mut doc = DocumentMut::new();
1411    let mut bin_t = dotted();
1412    bin_t["name"] = value(bin);
1413    doc["bin"] = Item::Table(bin_t);
1414    let mut args = toml_edit::Array::new();
1415    for a in &case.args {
1416        args.push(a.as_str());
1417    }
1418    doc["args"] = value(args);
1419    if !case.env.is_empty() {
1420        let mut add = dotted();
1421        for (k, v) in &case.env {
1422            add[k.as_str()] = value(v.as_str());
1423        }
1424        let mut env = dotted();
1425        env.insert("add", Item::Table(add));
1426        doc["env"] = Item::Table(env);
1427    }
1428    match rec.status {
1429        Status::Code(code) => {
1430            let mut status = dotted();
1431            status["code"] = value(i64::from(code));
1432            doc["status"] = Item::Table(status);
1433        }
1434        _ => doc["status"] = value("interrupted"),
1435    }
1436    let mut fs = dotted();
1437    fs["sandbox"] = value(true);
1438    if !case.files.is_empty() {
1439        fs["base"] = value(format!("{name}.in"));
1440    }
1441    doc["fs"] = Item::Table(fs);
1442    if rec.binary {
1443        doc["binary"] = value(true);
1444    }
1445    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1446    if let Some(stdin) = &case.stdin {
1447        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1448    }
1449    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1450    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1451    if let Some(effects) = &rec.effects {
1452        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
1453    }
1454    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1455        for (path, bytes) in files {
1456            let target = dir.join(format!("{name}.{sub}")).join(path);
1457            if let Some(parent) = target.parent() {
1458                std::fs::create_dir_all(parent)?;
1459            }
1460            std::fs::write(&target, bytes)?;
1461        }
1462    }
1463    Ok(())
1464}
1465
1466pub(crate) fn reserve_case_name(
1467    taken: &mut BTreeSet<String>,
1468    base: String,
1469    mut suffix: usize,
1470) -> String {
1471    let mut name = base.clone();
1472    while !taken.insert(name.clone()) {
1473        name = format!("{base}-{suffix}");
1474        suffix += 1;
1475    }
1476    name
1477}
1478
1479pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1480    let repo = opts
1481        .repo
1482        .canonical()
1483        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1484    let existing = Config::load(&repo)?;
1485    let run = if !opts.run.is_empty() {
1486        opts.run.to_vec()
1487    } else if let Some(c) = &existing {
1488        c.run.clone()
1489    } else {
1490        bail!(
1491            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1492        );
1493    };
1494    let mut normalize = existing
1495        .as_ref()
1496        .map(|c| c.normalize.clone())
1497        .unwrap_or_default();
1498    let mut normalizers = existing
1499        .as_ref()
1500        .map(|c| c.normalizers.clone())
1501        .unwrap_or_default();
1502    for n in opts.normalize {
1503        if let Some((name, pattern)) = n.split_once('=') {
1504            normalizers.insert(name.to_string(), pattern.to_string());
1505        } else if !normalize.contains(n) {
1506            normalize.push(n.clone());
1507        }
1508    }
1509    let explicit = opts
1510        .name
1511        .map(str::to_string)
1512        .or_else(|| existing.as_ref().map(|c| c.name.clone()));
1513    let names = app_names(&repo, &run, explicit.as_deref());
1514    let mut config = Config {
1515        schema: SCHEMA.to_string(),
1516        name: explicit
1517            .or_else(|| names.first().cloned())
1518            .unwrap_or_else(|| "app".to_string()),
1519        run,
1520        normalize,
1521        normalizers,
1522        timeout_secs: opts
1523            .timeout_secs
1524            .or(existing.as_ref().map(|c| c.timeout_secs))
1525            .unwrap_or_else(default_timeout),
1526        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts),
1527        float_tolerance: match opts.float_tolerance {
1528            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
1529            None => existing.as_ref().and_then(|c| c.float_tolerance),
1530        },
1531        unordered: BTreeMap::new(),
1532        effects: crate::effects::EffectsConfig::merge(
1533            existing.as_ref().and_then(|c| c.effects.clone()),
1534            opts.effects.clone(),
1535        ),
1536    };
1537    let norm = Normalizers::new(&config)?;
1538    if config.http.is_some() {
1539        let outcome = crate::http::record(&repo, &config, &norm, opts)?;
1540        config.unordered = unordered_of(&outcome.noise);
1541        std::fs::write(
1542            cases_dir(&repo).join(CONFIG_FILE),
1543            serde_json::to_string_pretty(&config)? + "\n",
1544        )?;
1545        return Ok(outcome);
1546    }
1547
1548    let examples = find_examples(&repo, &names);
1549    let inputs = match opts.inputs {
1550        Some(path) => read_inputs(path)?,
1551        None => Vec::new(),
1552    };
1553    let mut planned: Vec<(String, Case)> = Vec::new();
1554    let mut seen = BTreeSet::new();
1555    let mut taken = BTreeSet::new();
1556    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
1557        if !seen.insert(case.key()) {
1558            return false;
1559        }
1560        let base_name = match given {
1561            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
1562            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
1563                Some(s) => format!("{prefix}-{n:03}-{s}"),
1564                None => format!("{prefix}-{n:03}"),
1565            },
1566        };
1567        let name = reserve_case_name(&mut taken, base_name, n);
1568        planned.push((name, case));
1569        true
1570    };
1571    let mut bases = Vec::new();
1572    let mut counts = [0usize; 3];
1573    for case in examples {
1574        if push("example", counts[0] + 1, None, case.clone()) {
1575            counts[0] += 1;
1576            bases.push(case);
1577        }
1578    }
1579    for (given, case) in inputs {
1580        if push("input", counts[1] + 1, given, case.clone()) {
1581            counts[1] += 1;
1582            bases.push(case);
1583        }
1584    }
1585    if bases.is_empty() {
1586        let case = Case::new(Vec::new());
1587        push("example", 1, Some("no-args".to_string()), case.clone());
1588        bases.push(case);
1589    }
1590    if opts.traps {
1591        for case in trap_cases(&bases) {
1592            if push("trap", counts[2] + 1, None, case) {
1593                counts[2] += 1;
1594            }
1595        }
1596    }
1597
1598    let timeout = Duration::from_secs(config.timeout_secs);
1599    let effects = config.effects.as_ref();
1600    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
1601        let one = run_case(&config.run, &repo, case, timeout, effects)?;
1602        let two = run_case(&config.run, &repo, case, timeout, effects)?;
1603        Ok((one, two))
1604    };
1605    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
1606        planned.iter().map(run_twice).collect()
1607    } else {
1608        par_map(&planned, run_twice)
1609    };
1610    let dir = cases_dir(&repo);
1611    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1612    let mut outcome = RecordOutcome {
1613        dir: dir.clone(),
1614        run: config.run.clone(),
1615        cases: 0,
1616        examples: counts[0],
1617        inputs: counts[1],
1618        traps: counts[2],
1619        noisy: Vec::new(),
1620        noise: Vec::new(),
1621        unstable: Vec::new(),
1622        timed_out: Vec::new(),
1623    };
1624    for ((name, case), runs) in planned.iter().zip(runs) {
1625        let (one, two) = runs?;
1626        if one.status == Status::Timeout || two.status == Status::Timeout {
1627            outcome.timed_out.push(name.clone());
1628            continue;
1629        }
1630        let rec = settle(&norm, case, &one, &two);
1631        write_case(&dir, &config.name, name, case, &rec)?;
1632        outcome.cases += 1;
1633        if !rec.noise.is_empty() {
1634            outcome.noisy.push(name.clone());
1635        }
1636        outcome
1637            .noise
1638            .extend(rec.noise.iter().map(|(field, kind)| Noise {
1639                case: name.clone(),
1640                field: field.clone(),
1641                kind: *kind,
1642            }));
1643        if rec.unstable {
1644            outcome.unstable.push(name.clone());
1645        }
1646    }
1647    config.unordered = unordered_of(&outcome.noise);
1648    std::fs::write(
1649        dir.join(CONFIG_FILE),
1650        serde_json::to_string_pretty(&config)? + "\n",
1651    )?;
1652    Ok(outcome)
1653}
1654
1655fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
1656    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
1657    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
1658        out.entry(n.case.clone()).or_default().push(n.field.clone());
1659    }
1660    out
1661}
1662
1663enum Expect {
1664    Code(i32),
1665    Failed,
1666    Killed,
1667    Skip,
1668}
1669
1670struct Spec {
1671    name: String,
1672    case: Case,
1673    stdout: Option<Vec<u8>>,
1674    stderr: Option<Vec<u8>>,
1675    effects: Option<Vec<u8>>,
1676    status: Expect,
1677    out_dir: Option<PathBuf>,
1678    binary: bool,
1679}
1680
1681fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1682    walk_files(base)
1683        .into_iter()
1684        .map(|p| {
1685            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
1686            let bytes = std::fs::read(&p).unwrap_or_default();
1687            (rel, bytes)
1688        })
1689        .collect()
1690}
1691
1692fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1693    let name = path
1694        .file_stem()
1695        .map(|s| s.to_string_lossy().into_owned())
1696        .unwrap_or_default();
1697    let text =
1698        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1699    let doc: DocumentMut = text
1700        .parse()
1701        .with_context(|| format!("parsing {}", path.display()))?;
1702    let args = match doc.get("args") {
1703        Some(item) if item.as_array().is_some() => item
1704            .as_array()
1705            .into_iter()
1706            .flatten()
1707            .map(|v| {
1708                v.as_str()
1709                    .map(str::to_string)
1710                    .unwrap_or_else(|| v.to_string())
1711            })
1712            .collect(),
1713        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
1714        None => Vec::new(),
1715    };
1716    let mut case = Case::new(args);
1717    let side = |key: &str| -> Result<Option<Vec<u8>>> {
1718        if let Some(s) = doc.get(key).and_then(Item::as_str) {
1719            return Ok(Some(s.as_bytes().to_vec()));
1720        }
1721        let file = dir.join(format!("{name}.{key}"));
1722        Ok(if file.exists() {
1723            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
1724        } else {
1725            None
1726        })
1727    };
1728    case.stdin = side("stdin")?;
1729    if let Some(env) = doc.get("env") {
1730        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
1731        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
1732            for (k, v) in add.iter() {
1733                case.env
1734                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
1735            }
1736        }
1737        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
1738            case.env_remove = remove
1739                .iter()
1740                .filter_map(|v| v.as_str().map(str::to_string))
1741                .collect();
1742        }
1743    }
1744    let base = doc
1745        .get("fs")
1746        .and_then(|f| f.get("base"))
1747        .and_then(Item::as_str)
1748        .map(|b| dir.join(b))
1749        .unwrap_or_else(|| dir.join(format!("{name}.in")));
1750    if base.is_dir() {
1751        case.files = read_files(&base);
1752    }
1753    let status = match doc.get("status") {
1754        None => Expect::Code(0),
1755        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
1756            (Some("success"), _) => Expect::Code(0),
1757            (Some("failed"), _) => Expect::Failed,
1758            (Some("interrupted"), _) => Expect::Killed,
1759            (Some("skipped"), _) => Expect::Skip,
1760            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
1761            _ => bail!("{}: unknown `status`", path.display()),
1762        },
1763    };
1764    let out_dir = dir.join(format!("{name}.out"));
1765    Ok(Spec {
1766        stdout: side("stdout")?,
1767        stderr: side("stderr")?,
1768        effects: side(crate::effects::EXT)?,
1769        status,
1770        out_dir: out_dir.is_dir().then_some(out_dir),
1771        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
1772        name,
1773        case,
1774    })
1775}
1776
1777pub(crate) fn compare(
1778    norm: &Normalizers,
1779    expected: &[u8],
1780    actual: &[u8],
1781    binary: bool,
1782    unordered: bool,
1783) -> Option<String> {
1784    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
1785    {
1786        let e = norm.canonical(&norm.apply(e));
1787        let a = norm.canonical(&norm.apply(a));
1788        let tol = norm.float_tolerance;
1789        if unordered {
1790            let (mut el, mut al) = (lines(&e), lines(&a));
1791            el.sort_unstable();
1792            al.sort_unstable();
1793            let same = el.len() == al.len()
1794                && el
1795                    .iter()
1796                    .zip(&al)
1797                    .all(|(x, y)| line_matches_within(x, y, tol));
1798            return (!same).then(|| {
1799                format!(
1800                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
1801                    render_diff(&el.join("\n"), &al.join("\n"), tol)
1802                )
1803            });
1804        }
1805        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
1806    }
1807    (expected != actual).then(|| {
1808        format!(
1809            "binary content differs ({} bytes expected, {} bytes got)\n",
1810            expected.len(),
1811            actual.len()
1812        )
1813    })
1814}
1815
1816pub struct ReplayOptions<'a> {
1817    pub repo: &'a Path,
1818    /// Command line of the build to test; the original's command when `None`.
1819    pub build: Option<&'a str>,
1820    pub timeout_secs: Option<u64>,
1821    /// Servers: the port the build listens on, when it is fixed.
1822    pub port: Option<u16>,
1823    /// Replay only this case (a library: only this unit).
1824    pub case: Option<&'a str>,
1825}
1826
1827pub(crate) fn only_case<T>(
1828    items: Vec<T>,
1829    case: Option<&str>,
1830    name: impl Fn(&T) -> &str,
1831) -> Result<Vec<T>> {
1832    let Some(case) = case else {
1833        return Ok(items);
1834    };
1835    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
1836    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
1837    ensure!(
1838        !kept.is_empty(),
1839        "no case named {case}; the cases are: {}",
1840        names.join(", ")
1841    );
1842    Ok(kept)
1843}
1844
1845#[derive(Debug, Serialize)]
1846pub struct Problem {
1847    pub field: String,
1848    pub detail: String,
1849}
1850
1851#[derive(Debug, Serialize)]
1852pub struct Failure {
1853    pub case: String,
1854    pub args: Vec<String>,
1855    pub problems: Vec<Problem>,
1856}
1857
1858/// Cases the build handed to the original: the front door appends a line to the file named by
1859/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
1860#[derive(Debug, Serialize)]
1861pub struct Fallback {
1862    pub cases: usize,
1863    pub total: usize,
1864    pub rate: f64,
1865    /// The cases that fell back.
1866    pub names: Vec<String>,
1867}
1868
1869#[derive(Debug, Serialize)]
1870pub struct ReplayOutcome {
1871    pub build: Vec<String>,
1872    pub passed: usize,
1873    pub total: usize,
1874    pub skipped: usize,
1875    pub failures: Vec<Failure>,
1876    pub fallback: Option<Fallback>,
1877    pub report: PathBuf,
1878}
1879
1880fn check(
1881    norm: &Normalizers,
1882    command: &[String],
1883    repo: &Path,
1884    spec: &Spec,
1885    timeout: Duration,
1886    effects: Option<&crate::effects::EffectsConfig>,
1887) -> Result<(Vec<Problem>, Option<bool>)> {
1888    let run = run_case(command, repo, &spec.case, timeout, effects)?;
1889    let mut problems = Vec::new();
1890    let status_ok = match (&spec.status, &run.status) {
1891        (Expect::Code(e), Status::Code(a)) => e == a,
1892        (Expect::Failed, Status::Code(a)) => *a != 0,
1893        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
1894        _ => false,
1895    };
1896    if !status_ok {
1897        let expected = match &spec.status {
1898            Expect::Code(c) => format!("exit code {c}"),
1899            Expect::Failed => "a non-zero exit code".to_string(),
1900            Expect::Killed => "killed by a signal".to_string(),
1901            Expect::Skip => String::new(),
1902        };
1903        problems.push(Problem {
1904            field: "status".to_string(),
1905            detail: format!("expected {expected}, got {}\n", run.status),
1906        });
1907    }
1908    let no_effects = Vec::new();
1909    for (field, expected, actual) in [
1910        ("stdout", &spec.stdout, &run.stdout),
1911        ("stderr", &spec.stderr, &run.stderr),
1912        (
1913            crate::effects::EXT,
1914            &spec.effects,
1915            run.effects.as_ref().unwrap_or(&no_effects),
1916        ),
1917    ] {
1918        if let Some(expected) = expected
1919            && let Some(detail) = compare(
1920                norm,
1921                expected,
1922                actual,
1923                spec.binary,
1924                norm.unordered(&spec.name, field),
1925            )
1926        {
1927            problems.push(Problem {
1928                field: field.to_string(),
1929                detail,
1930            });
1931        }
1932    }
1933    if let Some(out_dir) = &spec.out_dir {
1934        for (path, expected) in read_files(out_dir) {
1935            let field = format!("file {}", path.display());
1936            match run.files.get(&path) {
1937                None => problems.push(Problem {
1938                    field,
1939                    detail: "not written\n".to_string(),
1940                }),
1941                Some(actual) => {
1942                    let unordered = norm.unordered(&spec.name, &field);
1943                    if let Some(detail) = compare(norm, &expected, actual, false, unordered) {
1944                        problems.push(Problem { field, detail });
1945                    }
1946                }
1947            }
1948        }
1949    }
1950    Ok((problems, run.fallback))
1951}
1952
1953pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
1954    stable_paths(&report_body(outcome))
1955}
1956
1957/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
1958/// same file and CI can commit it and fail on `git diff --exit-code`.
1959fn stable_paths(text: &str) -> String {
1960    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1961    let tmp = std::env::temp_dir();
1962    let tmp = tmp.to_string_lossy();
1963    let tmp = tmp.trim_end_matches(['/', '\\']);
1964    let text = if tmp.len() > 1 {
1965        text.replace(tmp, "$TMPDIR")
1966    } else {
1967        text.to_string()
1968    };
1969    SANDBOX
1970        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
1971        .replace_all(&text, "rust-anything-app-$1")
1972        .into_owned()
1973}
1974
1975fn report_body(outcome: &ReplayOutcome) -> String {
1976    let mut out = String::from("# App replay\n\n");
1977    out += &format!(
1978        "Build: `{}`\n\n",
1979        outcome
1980            .build
1981            .iter()
1982            .map(|w| shell_quote(w))
1983            .collect::<Vec<_>>()
1984            .join(" ")
1985    );
1986    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
1987    if outcome.skipped > 0 {
1988        out += &format!("Skipped: {}\n\n", outcome.skipped);
1989    }
1990    out += &match &outcome.fallback {
1991        Some(f) => format!(
1992            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
1993            f.rate * 100.0,
1994            f.cases,
1995            f.total
1996        ),
1997        None => "Fallback rate: not reported by this build\n\n".to_string(),
1998    };
1999    if outcome.failures.is_empty() {
2000        out += "Every case matches.\n";
2001        return out;
2002    }
2003    out += "## Failing cases\n";
2004    for f in &outcome.failures {
2005        out += &format!(
2006            "\n### {}\n\nArguments: `{}`\n",
2007            f.case,
2008            f.args
2009                .iter()
2010                .map(|w| shell_quote(w))
2011                .collect::<Vec<_>>()
2012                .join(" ")
2013        );
2014        for p in &f.problems {
2015            out += &format!(
2016                "\n{}:\n\n```diff\n{}```\n",
2017                p.field,
2018                p.detail.replace("```", "`\u{200b}``")
2019            );
2020        }
2021    }
2022    out
2023}
2024
2025fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2026    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2027        .with_context(|| {
2028            format!(
2029                "no cases in {}: run `rust-anything app record` first",
2030                dir.display()
2031            )
2032        })?
2033        .flatten()
2034        .map(|e| e.path())
2035        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2036        .collect();
2037    paths.sort();
2038    let specs = paths
2039        .iter()
2040        .map(|p| load_spec(dir, p))
2041        .collect::<Result<Vec<_>>>()?;
2042    ensure!(
2043        !specs.is_empty(),
2044        "no cases in {}: run `rust-anything app record` first",
2045        dir.display()
2046    );
2047    Ok(specs)
2048}
2049
2050/// The recorded cases' arguments, each with whether the original exited 0.
2051pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
2052    Ok(load_specs(&cases_dir(repo))?
2053        .into_iter()
2054        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
2055        .collect())
2056}
2057
2058pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2059    let repo = opts
2060        .repo
2061        .canonical()
2062        .with_context(|| format!("no folder {}", opts.repo.display()))?;
2063    let dir = cases_dir(&repo);
2064    let config = Config::load(&repo)?;
2065    if config.is_none()
2066        && let Ok(state) = crate::front_door::State::load(&repo)
2067        && state.kind == crate::front_door::AppKind::Library
2068    {
2069        ensure!(
2070            opts.build.is_none(),
2071            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
2072            state.name
2073        );
2074        return crate::library::replay(&repo, &state, opts.case);
2075    }
2076    let command = match (opts.build, &config) {
2077        (Some(build), _) => shell_split(build)?,
2078        (None, Some(c)) => c.run.clone(),
2079        (None, None) => bail!(
2080            "no {} in {}: run `rust-anything app record` first, or pass --build",
2081            CONFIG_FILE,
2082            dir.display()
2083        ),
2084    };
2085    ensure!(!command.is_empty(), "the build command is empty");
2086    let config = config.unwrap_or_else(|| Config {
2087        schema: SCHEMA.to_string(),
2088        name: "app".to_string(),
2089        run: Vec::new(),
2090        normalize: Vec::new(),
2091        normalizers: BTreeMap::new(),
2092        timeout_secs: default_timeout(),
2093        http: None,
2094        float_tolerance: None,
2095        unordered: BTreeMap::new(),
2096        effects: None,
2097    });
2098    let norm = Normalizers::new(&config)?;
2099    let timeout = Duration::from_secs(opts.timeout_secs.unwrap_or(config.timeout_secs));
2100    if config.http.is_some() {
2101        return crate::http::replay(
2102            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2103        );
2104    }
2105    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2106    let effects = config.effects.as_ref();
2107    let check_one = |spec: &Spec| {
2108        if matches!(spec.status, Expect::Skip) {
2109            return Ok((Vec::new(), None));
2110        }
2111        check(&norm, &command, &repo, spec, timeout, effects)
2112    };
2113    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2114        specs.iter().map(check_one).collect()
2115    } else {
2116        par_map(&specs, check_one)
2117    };
2118    let mut outcome = ReplayOutcome {
2119        build: command.clone(),
2120        passed: 0,
2121        total: 0,
2122        skipped: 0,
2123        failures: Vec::new(),
2124        fallback: None,
2125        report: dir.join(REPORT_FILE),
2126    };
2127    let (mut reported, mut fell_back) = (false, Vec::new());
2128    for (spec, result) in specs.iter().zip(results) {
2129        if matches!(spec.status, Expect::Skip) {
2130            outcome.skipped += 1;
2131            continue;
2132        }
2133        let (problems, fallback) = result?;
2134        outcome.total += 1;
2135        reported |= fallback.is_some();
2136        if fallback == Some(true) {
2137            fell_back.push(spec.name.clone());
2138        }
2139        if problems.is_empty() {
2140            outcome.passed += 1;
2141        } else {
2142            outcome.failures.push(Failure {
2143                case: spec.name.clone(),
2144                args: spec.case.args.clone(),
2145                problems,
2146            });
2147        }
2148    }
2149    if reported {
2150        outcome.fallback = Some(Fallback {
2151            cases: fell_back.len(),
2152            total: outcome.total,
2153            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2154            names: fell_back,
2155        });
2156    }
2157    std::fs::write(&outcome.report, report_markdown(&outcome))
2158        .with_context(|| format!("writing {}", outcome.report.display()))?;
2159    Ok(outcome)
2160}
2161
2162#[cfg(test)]
2163mod tests {
2164    use super::*;
2165
2166    #[test]
2167    fn given_names_keep_their_tail() {
2168        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
2169        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
2170        assert_ne!(a, b);
2171        assert_eq!(
2172            a,
2173            "tests-format-typescript-conformance-types-never-never-ts"
2174        );
2175        assert_eq!(slug(&a).len(), 23);
2176    }
2177
2178    #[test]
2179    fn reports_do_not_carry_sandbox_paths() {
2180        let tmp = std::env::temp_dir();
2181        let line = format!(
2182            "-cwd {}\n",
2183            tmp.join("rust-anything-app-run-4242-7")
2184                .join("cwd")
2185                .display()
2186        );
2187        let stable = stable_paths(&line);
2188        assert!(!stable.contains("4242"), "{stable}");
2189        assert!(stable.contains("$TMPDIR"), "{stable}");
2190        assert_eq!(
2191            stable,
2192            stable_paths(&line.replace("4242-7", "99-0")),
2193            "{stable}"
2194        );
2195    }
2196
2197    fn text_matches_exact(e: &str, a: &str) -> bool {
2198        text_matches(e, a, None)
2199    }
2200
2201    #[cfg(unix)]
2202    #[test]
2203    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
2204        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
2205            let command = ["/bin/sh".into(), "-c".into(), script.into()];
2206            let start = Instant::now();
2207            let run = run_case(
2208                &command,
2209                Path::new("."),
2210                &Case::new(Vec::new()),
2211                Duration::from_millis(200),
2212                None,
2213            )
2214            .unwrap();
2215            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
2216            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
2217        }
2218    }
2219
2220    #[test]
2221    fn matching_follows_trycmd() {
2222        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
2223        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
2224        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
2225        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
2226        assert!(text_matches_exact(
2227            "head\n...\ntail\n",
2228            "head\n1\n2\ntail\n"
2229        ));
2230        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
2231        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
2232        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
2233    }
2234
2235    #[test]
2236    fn numbers_match_within_the_tolerance() {
2237        let e = "step 1\nenergy 0.3\nat [..]\n";
2238        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
2239        assert!(!text_matches(e, a, None));
2240        assert!(text_matches(e, a, Some(1e-9)));
2241        assert!(!text_matches(
2242            e,
2243            "step 2\nenergy 0.3\nat 12:00\n",
2244            Some(1e-9)
2245        ));
2246        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
2247    }
2248
2249    #[cfg(unix)]
2250    #[test]
2251    fn binary_capture_replays_its_text_companion_byte_for_byte() {
2252        let repo = temp_dir("binary-stream-pair").unwrap();
2253        let run = [
2254            "/bin/sh".to_string(),
2255            "-c".to_string(),
2256            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
2257        ];
2258        let recorded = record(&RecordOptions {
2259            repo: &repo,
2260            run: &run,
2261            inputs: None,
2262            normalize: &["timestamps".into()],
2263            name: None,
2264            traps: false,
2265            timeout_secs: None,
2266            http: false,
2267            server_args: &[],
2268            fresh: &[],
2269            pace_ms: None,
2270            port: None,
2271            float_tolerance: None,
2272            effects: None,
2273        })
2274        .unwrap();
2275        assert_eq!(recorded.cases, 1);
2276        let replayed = replay(&ReplayOptions {
2277            repo: &repo,
2278            build: None,
2279            timeout_secs: None,
2280            port: None,
2281            case: None,
2282        })
2283        .unwrap();
2284        assert_eq!(
2285            (replayed.passed, replayed.total),
2286            (1, 1),
2287            "{:?}",
2288            replayed.failures
2289        );
2290        std::fs::remove_dir_all(repo).unwrap();
2291    }
2292
2293    #[test]
2294    fn noise_is_classified() {
2295        let norm = Normalizers::new(&Config {
2296            schema: SCHEMA.to_string(),
2297            name: "app".to_string(),
2298            run: Vec::new(),
2299            normalize: Vec::new(),
2300            normalizers: BTreeMap::new(),
2301            timeout_secs: 30,
2302            http: None,
2303            float_tolerance: None,
2304            unordered: BTreeMap::new(),
2305            effects: None,
2306        })
2307        .unwrap();
2308        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
2309        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
2310        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
2311        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
2312        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
2313        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
2314        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
2315    }
2316
2317    #[test]
2318    fn unordered_output_matches_in_any_order_but_not_other_lines() {
2319        let norm = Normalizers::new(&Config {
2320            schema: SCHEMA.to_string(),
2321            name: "app".to_string(),
2322            run: Vec::new(),
2323            normalize: Vec::new(),
2324            normalizers: BTreeMap::new(),
2325            timeout_secs: 30,
2326            http: None,
2327            float_tolerance: None,
2328            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
2329            effects: None,
2330        })
2331        .unwrap();
2332        assert!(norm.unordered("c", "stdout"));
2333        assert!(!norm.unordered("c", "stderr"));
2334        let e = b"x=1\ny=2\n";
2335        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
2336        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
2337        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
2338        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
2339    }
2340
2341    #[test]
2342    fn noise_becomes_wildcards() {
2343        assert_eq!(
2344            merge_noise(
2345                "start\nnow: 2026-11-16 10:00:01\nend\n",
2346                "start\nnow: 2026-11-16 10:00:02\nend\n"
2347            ),
2348            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
2349        );
2350        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
2351        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
2352        let merged = merge_noise("x 1\n", "x 2\n");
2353        assert!(text_matches_exact(&merged, "x 3\n"));
2354    }
2355
2356    #[test]
2357    fn normalizers_by_name() {
2358        let mut config = Config {
2359            schema: SCHEMA.to_string(),
2360            name: "app".to_string(),
2361            run: Vec::new(),
2362            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
2363            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
2364            timeout_secs: 30,
2365            http: None,
2366            float_tolerance: None,
2367            unordered: BTreeMap::new(),
2368            effects: None,
2369        };
2370        let norm = Normalizers::new(&config).unwrap();
2371        assert_eq!(
2372            norm.apply(
2373                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
2374            ),
2375            "at [..] id [..] [..]"
2376        );
2377        assert_eq!(
2378            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
2379            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
2380        );
2381        config.normalize.push("nope".into());
2382        assert!(Normalizers::new(&config).is_err());
2383    }
2384
2385    #[test]
2386    fn examples_become_cases() {
2387        let repo = temp_dir("examples").unwrap();
2388        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
2389        std::fs::write(
2390            repo.join("README.md"),
2391            "# 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",
2392        )
2393        .unwrap();
2394        let names = vec!["tool".to_string()];
2395        let cases = find_examples(&repo, &names);
2396        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
2397        assert_eq!(
2398            args,
2399            [
2400                vec!["count", "in.txt"],
2401                vec!["words"],
2402                vec!["upper", "x y"],
2403                vec!["sort"],
2404            ]
2405        );
2406        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
2407        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
2408        assert_eq!(cases[2].env["LANG"], "C");
2409        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
2410        std::fs::remove_dir_all(&repo).unwrap();
2411    }
2412
2413    #[test]
2414    fn traps_keep_the_shape_of_the_case() {
2415        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
2416        base.stdin = Some(b"{\"a\":1}".to_vec());
2417        let traps = trap_cases(&[base]);
2418        assert!(traps.iter().all(|c| c.args[0] == "div"));
2419        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
2420        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
2421        assert!(
2422            traps
2423                .iter()
2424                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
2425        );
2426        let text = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
2427        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
2428    }
2429
2430    #[cfg(unix)]
2431    #[test]
2432    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
2433        let repo = temp_dir("case-name-collisions").unwrap();
2434        let inputs = repo.join("cases.jsonl");
2435        std::fs::write(
2436            &inputs,
2437            concat!(
2438                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
2439                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
2440                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
2441            ),
2442        )
2443        .unwrap();
2444        let recorded = record(&RecordOptions {
2445            repo: &repo,
2446            run: &["/bin/echo".into()],
2447            inputs: Some(&inputs),
2448            normalize: &[],
2449            name: None,
2450            traps: false,
2451            timeout_secs: None,
2452            http: false,
2453            server_args: &[],
2454            fresh: &[],
2455            pace_ms: None,
2456            port: None,
2457            float_tolerance: None,
2458            effects: None,
2459        })
2460        .unwrap();
2461        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
2462        assert_eq!(recorded.cases, 3);
2463        assert_eq!(read("x.stdout"), "one\n");
2464        assert_eq!(read("x-3.stdout"), "two\n");
2465        assert_eq!(read("x-4.stdout"), "three\n");
2466        std::fs::remove_dir_all(repo).unwrap();
2467    }
2468
2469    #[test]
2470    fn names_come_from_the_run_command_and_manifests() {
2471        let repo = temp_dir("names").unwrap();
2472        std::fs::create_dir_all(repo.join("out")).unwrap();
2473        std::fs::write(
2474            repo.join("package.json"),
2475            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
2476        )
2477        .unwrap();
2478        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
2479        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
2480        std::fs::remove_dir_all(&repo).unwrap();
2481    }
2482
2483    #[test]
2484    fn python_program_names_are_case_insensitive() {
2485        assert!(is_python_program("PYTHON"));
2486        assert!(is_python_program("/tools/Python3.exe"));
2487        assert!(is_python_program("Py.cmd"));
2488        assert!(!is_python_program("pythonw.exe"));
2489    }
2490
2491    #[test]
2492    fn shell_words() {
2493        assert_eq!(
2494            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
2495            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
2496        );
2497        assert!(shell_split("a | b").is_err());
2498        assert!(shell_tokens("echo $(date)").is_none());
2499        assert!(shell_tokens("echo `date`").is_none());
2500        assert_eq!(
2501            shell_split(r"echo \$(date) \`date\`").unwrap(),
2502            ["echo", "$(date)", "`date`"]
2503        );
2504        #[cfg(windows)]
2505        assert_eq!(
2506            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
2507            [r"C:\tools\rust-anything\app.exe", "--flag"]
2508        );
2509        #[cfg(windows)]
2510        assert_eq!(
2511            shell_split(r"run C:\$cache\tool.exe").unwrap(),
2512            ["run", r"C:\$cache\tool.exe"]
2513        );
2514        #[cfg(windows)]
2515        assert_eq!(
2516            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
2517            [r"\\server\share\tool.exe", "--flag"]
2518        );
2519        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
2520    }
2521}