Skip to main content

fallow_api/runtime/
mutation.rs

1//! Orchestration entry points of mutation testing for CLI, MCP and NAPI.
2//!
3//! [`plan_mutation`] runs only the static half and never executes user code.
4//! [`run_mutation`] plans through the engine, then runs the tests of the
5//! project against each planned mutant through the embedded companion.
6
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11use fallow_engine::mutation::{
12    DiffIndex, MutantDisposition, MutationPlan, MutationPlanRequest, MutationScope,
13    plan_mutations_for_session_with,
14};
15use fallow_engine::session::AnalysisSession;
16use fallow_output::{
17    MutationCacheOutput, MutationPlanOutput, MutationPlanSchemaVersion, MutationReport,
18    MutationResumeOutput, MutationRunnerOutput, MutationRuntimeOutput, MutationSchemaVersion,
19    MutationScopeKind, MutationScopeOutput, MutationTimings, MutationWorktreeCheck,
20};
21use fallow_types::envelope::ElapsedMs;
22use rustc_hash::FxHashSet;
23
24use crate::ProgrammaticError;
25use crate::analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
26use crate::mutation::companion::{COMPANION_FILES, install};
27use crate::mutation::discovery::{JsRuntime, discover_runtime};
28use crate::mutation::journal::{JOURNAL_FORMAT, Journal, JournalHeader, JournalMismatch};
29use crate::mutation::last_report::ignore_cache_dir;
30use crate::mutation::manifest::{Manifest, RunnerRange, manifest};
31use crate::mutation::node_args::node_test_args;
32use crate::mutation::protocol::{InitOptions, InitRequest};
33use crate::mutation::report::{
34    CompletionFacts, baseline_failures, completion, function_results, issues, mutant_results,
35    plan_counts, plan_files, plan_mutants, skipped_files, summary, tool_version,
36};
37use crate::mutation::result_cache::{KeyFiles, NOT_KEYED, ResultCache};
38use crate::mutation::run_dir::{RunFile, write_run_dir};
39use crate::mutation::runner_select::{Runner, select_runner};
40use crate::mutation::scheduler::{
41    OutcomeJournal, ResultLookup, ScheduleConfig, ScheduleError, ScheduleIssue, ScheduleOutcome,
42    SchedulePlan, ScheduledMutant, run_schedule_with_progress,
43};
44use crate::mutation::transport::ProcessSpawner;
45use crate::mutation::typecheck::typecheck_survivors;
46use crate::mutation::worktree::{Exclusions, WorktreeSnapshot, canonical_path, snapshot};
47use crate::mutation::{
48    MutationProgress, MutationProgressSink, MutationRunOptions, MutationRunScope,
49};
50
51type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
52
53/// The default timeout of `init` and the dry run (`protocol.md` section 8).
54const DEFAULT_RUNNER_TIMEOUT: Duration = Duration::from_secs(120);
55
56fn mutation_error(code: &str, message: impl Into<String>) -> ProgrammaticError {
57    ProgrammaticError::new(message, 2).with_code(code)
58}
59
60#[expect(
61    clippy::cast_possible_truncation,
62    reason = "a run lasts far less than 2^64 milliseconds"
63)]
64const fn millis(duration: Duration) -> u64 {
65    duration.as_millis() as u64
66}
67
68fn validate(options: &MutationRunOptions) -> ProgrammaticResult<()> {
69    if options.concurrency == Some(0) {
70        return Err(mutation_error(
71            "FALLOW_INVALID_MUTATION_OPTIONS",
72            "the mutation concurrency must be at least 1",
73        )
74        .with_context("mutation.concurrency"));
75    }
76    if options.max_mutants == Some(0) {
77        return Err(mutation_error(
78            "FALLOW_INVALID_MUTATION_OPTIONS",
79            "the mutant limit must be at least 1",
80        )
81        .with_context("mutation.maxMutants"));
82    }
83    if options.kill_matrix && !options.kill_matrix_targets.is_empty() {
84        return Err(mutation_error(
85            "FALLOW_INVALID_MUTATION_OPTIONS",
86            "the full kill matrix and the kill matrix for targets are exclusive; pass only one of them",
87        ));
88    }
89    if options
90        .kill_matrix_targets
91        .iter()
92        .any(|target| target.trim().is_empty())
93    {
94        return Err(mutation_error(
95            "FALLOW_INVALID_MUTATION_OPTIONS",
96            "a kill matrix target must name a test file or a test id",
97        ));
98    }
99    if options.time_budget.is_some_and(|budget| budget.is_zero())
100        || options
101            .runner_timeout
102            .is_some_and(|timeout| timeout.is_zero())
103    {
104        return Err(mutation_error(
105            "FALLOW_INVALID_MUTATION_OPTIONS",
106            "a mutation time limit must be more than zero",
107        ));
108    }
109    Ok(())
110}
111
112/// The separator between the file and the name in a runner test id.
113const TEST_ID_SEPARATOR: &str = "::";
114
115/// A `--kill-matrix-for` target in the form of the runner test ids: the file
116/// part is root-relative, with forward slashes and no leading `./`. The name
117/// after the first `::` stays as given.
118fn normalize_target(root: &Path, target: &str) -> String {
119    let (file, name) = target
120        .split_once(TEST_ID_SEPARATOR)
121        .map_or((target, None), |(file, name)| (file, Some(name)));
122    let file = file.trim();
123    let path = Path::new(file);
124    let relative = if path.is_absolute() {
125        let canonical_root = root.canonicalize().ok();
126        path.strip_prefix(root)
127            .ok()
128            .or_else(|| {
129                canonical_root
130                    .as_deref()
131                    .and_then(|root| path.strip_prefix(root).ok())
132            })
133            .map_or_else(|| file.to_owned(), |rel| rel.to_string_lossy().into_owned())
134    } else {
135        file.to_owned()
136    };
137    let relative = relative.replace('\\', "/");
138    let mut trimmed = relative.as_str();
139    while let Some(rest) = trimmed.strip_prefix("./") {
140        trimmed = rest;
141    }
142    let relative = trimmed.to_owned();
143    match name {
144        Some(name) => format!("{relative}{TEST_ID_SEPARATOR}{name}"),
145        None => relative,
146    }
147}
148
149/// `options` with each `--kill-matrix-for` target normalized and without
150/// duplicates. `None` outside target mode. A target whose file part is empty
151/// after normalization, for example `./`, is an error.
152fn with_normalized_targets(
153    options: &MutationRunOptions,
154    root: &Path,
155) -> ProgrammaticResult<Option<MutationRunOptions>> {
156    if options.kill_matrix_targets.is_empty() {
157        return Ok(None);
158    }
159    let mut targets: Vec<String> = Vec::new();
160    for raw in &options.kill_matrix_targets {
161        let target = normalize_target(root, raw);
162        if target.is_empty() || target.starts_with(TEST_ID_SEPARATOR) {
163            return Err(mutation_error(
164                "FALLOW_INVALID_MUTATION_OPTIONS",
165                format!("the kill matrix target `{raw}` names no test file"),
166            ));
167        }
168        if !targets.contains(&target) {
169            targets.push(target);
170        }
171    }
172    Ok(Some(MutationRunOptions {
173        kill_matrix_targets: targets,
174        ..options.clone()
175    }))
176}
177
178/// The targets in sorted order, so that the order of the flags does not make
179/// a resume mismatch.
180fn sorted_targets(targets: &[String]) -> Vec<String> {
181    let mut sorted = targets.to_vec();
182    sorted.sort();
183    sorted
184}
185
186/// The kill matrix mode of the report.
187fn kill_matrix_mode<'a>(
188    options: &'a MutationRunOptions,
189    outcome: Option<&'a ScheduleOutcome>,
190) -> crate::mutation::kill_matrix::Mode<'a> {
191    use crate::mutation::kill_matrix::Mode;
192    if !options.kill_matrix_targets.is_empty() {
193        return Mode::Targets {
194            requested: &options.kill_matrix_targets,
195            resolved: outcome.map_or(&[], |outcome| outcome.targets.as_slice()),
196        };
197    }
198    if options.kill_matrix {
199        Mode::Full
200    } else {
201        Mode::Disabled
202    }
203}
204
205fn load_session(resolved: &ProgrammaticAnalysisContext) -> ProgrammaticResult<AnalysisSession> {
206    let mut project = fallow_engine::project_config::config_for_project_with_load_options(
207        resolved.root(),
208        resolved.config_path().as_deref(),
209        fallow_config::ConfigLoadOptions {
210            allow_remote_extends: resolved.allow_remote_extends,
211        },
212    )
213    .map_err(|error| {
214        ProgrammaticError::new(format!("failed to load config: {error}"), 2)
215            .with_code("FALLOW_CONFIG_LOAD_FAILED")
216            .with_context("analysis.configPath")
217    })?;
218    project.config.no_cache = resolved.no_cache;
219    project.config.threads = resolved.threads;
220    Ok(AnalysisSession::from_config(project))
221}
222
223fn scope_output(options: &MutationRunOptions, base_ref: Option<String>) -> MutationScopeOutput {
224    MutationScopeOutput {
225        kind: match options.scope {
226            MutationRunScope::Changed { .. } => MutationScopeKind::Changed,
227            MutationRunScope::All => MutationScopeKind::All,
228            MutationRunScope::Paths(_) => MutationScopeKind::Paths,
229        },
230        base_ref,
231    }
232}
233
234/// The engine scope, and the base ref of a changed scope.
235fn engine_scope(
236    options: &MutationRunOptions,
237    resolved: &ProgrammaticAnalysisContext,
238) -> ProgrammaticResult<(MutationScope, Option<String>)> {
239    let root = resolved.root();
240    match &options.scope {
241        MutationRunScope::All => Ok((MutationScope::All, None)),
242        MutationRunScope::Paths(paths) => Ok((MutationScope::Paths(paths.clone()), None)),
243        MutationRunScope::Changed { base } => {
244            if let Some(diff) = &resolved.diff {
245                return Ok((MutationScope::ChangedSinceBase(diff.clone()), None));
246            }
247            let resolved_base = crate::audit_run::resolve_audit_base(root, base.as_deref())
248                .map_err(|error| {
249                    let message = match error {
250                        crate::audit_run::AuditBaseError::InvalidRef { value, reason, .. } => {
251                            format!("invalid base ref `{value}`: {reason}")
252                        }
253                        crate::audit_run::AuditBaseError::NotDetected => {
254                            "no base branch to compare against; pass a base ref or mutate all files"
255                                .to_owned()
256                        }
257                    };
258                    mutation_error("FALLOW_MUTATION_BASE_NOT_FOUND", message)
259                        .with_context("mutation.base")
260                })?;
261            let text =
262                fallow_engine::changed_files::try_get_changed_diff(root, &resolved_base.git_ref)
263                    .map_err(|error| {
264                        mutation_error(
265                            "FALLOW_CHANGED_FILES_FAILED",
266                            format!(
267                                "cannot diff against `{}`: {}",
268                                resolved_base.git_ref,
269                                error.describe()
270                            ),
271                        )
272                    })?;
273            let label = format!("git diff {}", resolved_base.git_ref);
274            let index = fallow_engine::diff_source::place_diff(
275                DiffIndex::from_unified_diff(&text),
276                root,
277                &fallow_engine::diff_source::diff_base_candidates(root),
278                &label,
279            )
280            .map_err(|stand_down| {
281                let (_, message) = stand_down.into_parts();
282                mutation_error("FALLOW_CHANGED_FILES_FAILED", message)
283            })?;
284            Ok((
285                MutationScope::ChangedSinceBase(index),
286                Some(resolved_base.git_ref),
287            ))
288        }
289    }
290}
291
292/// The operators of the `mutation.operators` config key. The CLI and MCP
293/// callers pass `None` when the user names no operator, so both apply this
294/// one rule.
295fn config_operators(
296    session: &AnalysisSession,
297) -> ProgrammaticResult<Option<Vec<fallow_engine::mutation::Operator>>> {
298    let Some(names) = &session.config().mutation.operators else {
299        return Ok(None);
300    };
301    names
302        .iter()
303        .map(|name| {
304            fallow_engine::mutation::Operator::from_name(name.as_str()).ok_or_else(|| {
305                mutation_error(
306                    "FALLOW_INVALID_MUTATION_OPTIONS",
307                    format!("unknown mutation operator `{}`", name.as_str()),
308                )
309                .with_context("mutation.operators")
310            })
311        })
312        .collect::<ProgrammaticResult<Vec<_>>>()
313        .map(Some)
314}
315
316struct Planned {
317    resolved: ProgrammaticAnalysisContext,
318    cache_dir: PathBuf,
319    /// The test runner, selected from the config value and the first plan.
320    runner: Runner,
321    plan: MutationPlan,
322    base_ref: Option<String>,
323    /// The selected runner config file, relative to the project root.
324    runner_config: Option<String>,
325    /// The names of the selected operators. `None` uses each operator.
326    operators: Option<Vec<String>>,
327}
328
329/// The selected runner config: the caller option, else the
330/// `mutation.runnerConfig` config key. The result is relative to the project
331/// root, with `/` separators, as the companion resolves it against the root.
332///
333/// # Errors
334///
335/// Returns an exit-2 error when the file does not exist, is not a file, is
336/// outside the project root, or when the runner reads no config file.
337fn runner_config(
338    options: &MutationRunOptions,
339    session: &AnalysisSession,
340    root: &Path,
341    runner: Runner,
342) -> ProgrammaticResult<Option<String>> {
343    let Some(raw) = options.runner_config.clone().or_else(|| {
344        session
345            .config()
346            .mutation
347            .runner_config
348            .as_ref()
349            .map(PathBuf::from)
350    }) else {
351        return Ok(None);
352    };
353    let invalid = |message: String| {
354        mutation_error("FALLOW_INVALID_MUTATION_OPTIONS", message)
355            .with_context("mutation.runnerConfig")
356    };
357    let shown = raw.display();
358    if runner != Runner::Vitest {
359        return Err(invalid(format!(
360            "the runner config `{shown}` needs the Vitest runner, but the run uses `{}`; only Vitest reads a config file",
361            runner.name()
362        )));
363    }
364    let candidate = if raw.is_absolute() {
365        raw.clone()
366    } else {
367        root.join(&raw)
368    };
369    if !candidate.is_file() {
370        return Err(invalid(format!(
371            "the runner config `{shown}` is not a file; a relative path is relative to the project root"
372        )));
373    }
374    let root = canonical_path(root);
375    let file = canonical_path(&candidate);
376    let Ok(relative) = file.strip_prefix(&root) else {
377        return Err(invalid(format!(
378            "the runner config `{shown}` is outside the project root `{}`",
379            root.display()
380        )));
381    };
382    Ok(Some(
383        relative
384            .components()
385            .map(|part| part.as_os_str().to_string_lossy())
386            .collect::<Vec<_>>()
387            .join("/"),
388    ))
389}
390
391fn plan_for(
392    options: &MutationRunOptions,
393    before_plan: impl FnOnce(&Path, &Path) -> ProgrammaticResult<()>,
394) -> ProgrammaticResult<Planned> {
395    validate(options)?;
396    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
397    let session = load_session(&resolved)?;
398    let cache_dir = session.config().cache_dir.clone();
399    let configured = session.config().mutation.runner;
400    before_plan(resolved.root(), &cache_dir)?;
401    let (scope, base_ref) = engine_scope(options, &resolved)?;
402    let operators = match &options.operators {
403        Some(operators) => Some(operators.clone()),
404        None => config_operators(&session)?,
405    };
406    let operator_names = operators.as_deref().map(operator_names);
407    let request = MutationPlanRequest {
408        scope,
409        operators,
410        allow_side_effects: options.allow_side_effects,
411        max_mutants: options.max_mutants,
412        skip_component_files: false,
413    };
414    // The runner decision reads the test files of the first plan. A second
415    // plan without the component files keeps that decision.
416    let mut selected = None;
417    let plan = resolved
418        .install(|| {
419            plan_mutations_for_session_with(&session, &request, |plan| {
420                let runner = select_runner(configured, resolved.root(), &plan.test_files);
421                selected = Some(runner);
422                !runner.loads_component_files()
423            })
424        })
425        .map_err(|error| mutation_error("FALLOW_MUTATION_PLAN_FAILED", error.to_string()))?;
426    let runner =
427        selected.unwrap_or_else(|| select_runner(configured, resolved.root(), &plan.test_files));
428    let runner_config = runner_config(options, &session, resolved.root(), runner)?;
429    Ok(Planned {
430        resolved,
431        cache_dir,
432        runner,
433        plan,
434        base_ref,
435        runner_config,
436        operators: operator_names,
437    })
438}
439
440/// Builds the static mutation plan. It runs no user code.
441///
442/// # Errors
443///
444/// Returns an error for invalid options, a base ref that does not resolve,
445/// or a failed analysis.
446pub fn plan_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationPlanOutput> {
447    let started = Instant::now();
448    let planned = plan_for(options, |_, _| Ok(()))?;
449    let plan = &planned.plan;
450    Ok(MutationPlanOutput {
451        schema_version: MutationPlanSchemaVersion::V1,
452        version: tool_version(),
453        elapsed_ms: ElapsedMs(millis(started.elapsed())),
454        scope: scope_output(options, planned.base_ref.clone()),
455        counts: plan_counts(plan),
456        mutants: plan_mutants(plan),
457        files: plan_files(plan),
458        test_files: plan.test_files.clone(),
459        no_test_files: plan.no_test_files,
460        framework_config_checked: plan.framework_config_checked,
461        skipped_files: skipped_files(plan),
462        unmatched_paths: plan.unmatched_paths.clone(),
463    })
464}
465
466fn unsafe_cache_dir(message: String) -> ProgrammaticError {
467    mutation_error("FALLOW_MUTATION_UNSAFE_CACHE_DIR", message)
468        .with_help(
469            "set cache.dir or FALLOW_CACHE_DIR to a directory that holds no project file, such as .fallow",
470        )
471        .with_context("cache.dir")
472}
473
474/// Refuses a cache directory that is the root or a directory above it. The
475/// worktree check leaves the mutation cache out, and the analysis writes a
476/// `.gitignore` that ignores the whole cache directory, so such a cache
477/// directory hides each stray write from the check.
478fn guard_cache_dir(root: &Path, cache_dir: &Path) -> ProgrammaticResult<()> {
479    if !canonical_path(root).starts_with(canonical_path(cache_dir)) {
480        return Ok(());
481    }
482    Err(unsafe_cache_dir(format!(
483        "the cache directory `{}` is the project root or a directory above it, so the worktree check cannot see stray writes",
484        cache_dir.display()
485    )))
486}
487
488/// Refuses a cache directory that holds a planned source or test file.
489fn guard_cache_holds_no_planned_file(
490    root: &Path,
491    cache_dir: &Path,
492    plan: &MutationPlan,
493) -> ProgrammaticResult<()> {
494    let root = canonical_path(root);
495    let cache = canonical_path(cache_dir);
496    let inside = plan
497        .files
498        .iter()
499        .map(|file| file.path.as_str())
500        .chain(plan.test_files.iter().map(String::as_str))
501        .find(|path| root.join(path).starts_with(&cache));
502    let Some(path) = inside else {
503        return Ok(());
504    };
505    Err(unsafe_cache_dir(format!(
506        "the cache directory `{}` holds the project file `{path}`, so the worktree check cannot see stray writes",
507        cache_dir.display()
508    )))
509}
510
511fn take_worktree_snapshot(
512    root: &Path,
513    cache_dir: &Path,
514    output_paths: &[PathBuf],
515    start: Option<&WorktreeSnapshot>,
516) -> ProgrammaticResult<Option<WorktreeSnapshot>> {
517    // The caller writes a relative output path against the process
518    // directory, which can be below the root.
519    let cwd = std::env::current_dir().unwrap_or_else(|_| root.to_path_buf());
520    let outputs = output_paths.iter().map(|path| cwd.join(path));
521    // Only the mutation cache is left out of the status check. The analysis
522    // caches next to it are git-ignored, and an ignored file changes only
523    // in the ignored-file check, so the whole cache is left out there.
524    let exclusions = Exclusions {
525        paths: std::iter::once(cache_dir.join("mutation"))
526            .chain(outputs)
527            .collect(),
528        ignored: vec![cache_dir.to_path_buf()],
529    };
530    snapshot(root, &exclusions, start)
531        .map_err(|message| mutation_error("FALLOW_MUTATION_WORKTREE_CHECK_FAILED", message))
532}
533
534/// The worktree facts at the end of a run.
535struct WorktreeEnd {
536    /// The paths that changed since the start snapshot.
537    changed_paths: Vec<String>,
538    /// Why the end snapshot failed. Stray writes are then unknown.
539    check_error: Option<String>,
540}
541
542/// Compares the worktree with `start`. A failed end snapshot is a fact of
543/// the report, never a reason to drop the run result or its error.
544fn settle_worktree(
545    start: Option<&WorktreeSnapshot>,
546    take_end: impl FnOnce(&WorktreeSnapshot) -> ProgrammaticResult<Option<WorktreeSnapshot>>,
547) -> WorktreeEnd {
548    let Some(start) = start else {
549        return WorktreeEnd {
550            changed_paths: Vec::new(),
551            check_error: None,
552        };
553    };
554    match take_end(start) {
555        Ok(end) => WorktreeEnd {
556            changed_paths: end.map(|end| start.changed_paths(&end)).unwrap_or_default(),
557            check_error: None,
558        },
559        Err(error) => WorktreeEnd {
560            changed_paths: Vec::new(),
561            check_error: Some(error.message),
562        },
563    }
564}
565
566/// Adds the worktree facts to the error of a failed run.
567fn with_worktree_facts(mut error: ProgrammaticError, end: &WorktreeEnd) -> ProgrammaticError {
568    if !end.changed_paths.is_empty() {
569        error.message = format!(
570            "{}; the run changed these worktree paths: {}",
571            error.message,
572            end.changed_paths.join(", ")
573        );
574    }
575    if let Some(check_error) = &end.check_error {
576        error.message = format!(
577            "{}; the end-of-run worktree check failed: {check_error}",
578            error.message
579        );
580    }
581    error
582}
583
584const fn path_noun(count: usize) -> &'static str {
585    if count == 1 { "path" } else { "paths" }
586}
587
588fn guard_worktree(allow_dirty: bool, start: Option<&WorktreeSnapshot>) -> ProgrammaticResult<()> {
589    if allow_dirty {
590        return Ok(());
591    }
592    let Some(start) = start else {
593        return Err(mutation_error(
594            "FALLOW_MUTATION_NOT_A_REPOSITORY",
595            "mutation testing runs the tests against changed code and needs a git worktree to detect stray writes",
596        )
597        .with_help("run inside a git worktree, or pass --allow-dirty"));
598    };
599    let dirty = start.dirty_paths();
600    if dirty.is_empty() {
601        return Ok(());
602    }
603    let shown: Vec<&str> = dirty.iter().take(10).map(String::as_str).collect();
604    Err(mutation_error(
605        "FALLOW_MUTATION_DIRTY_WORKTREE",
606        format!(
607            "the git worktree has {} uncommitted {}: {}",
608            dirty.len(),
609            path_noun(dirty.len()),
610            shown.join(", ")
611        ),
612    )
613    .with_help("commit or stash the changes, or pass --allow-dirty"))
614}
615
616/// The help of a runner version outside `range`. It names the supported
617/// range as an install step. When the minimum is not a `.0.0` release, it
618/// also says that a minor update inside the major version is enough.
619fn runner_version_help(range: &RunnerRange) -> String {
620    let RunnerRange {
621        package,
622        min_version,
623        max_version_exclusive,
624        ..
625    } = range;
626    let install =
627        format!("install {package} {min_version} or a later version below {max_version_exclusive}");
628    match min_version.split_once('.') {
629        Some((major, rest)) if rest != "0.0" => {
630            format!("{install}; a {package} {major}.x release from {min_version} is in the range")
631        }
632        _ => install,
633    }
634}
635
636/// Maps a schedule error to its public error. A setup watchdog fault names
637/// `--setup-timeout`, because a slow or busy host is the usual cause. A
638/// runner version error names the supported range of `runner`.
639fn schedule_error(
640    error: &ScheduleError,
641    runner: &RunnerRange,
642    setup_timeout: Duration,
643) -> ProgrammaticError {
644    let (code, stderr_tail) = match error {
645        ScheduleError::Integrity(_) => ("FALLOW_MUTATION_COMPANION_INTEGRITY", None),
646        ScheduleError::RunnerVersion(_) => ("FALLOW_MUTATION_RUNNER_UNSUPPORTED", None),
647        ScheduleError::Setup { stderr_tail, .. } => {
648            ("FALLOW_MUTATION_RUNNER_FAILED", stderr_tail.clone())
649        }
650        ScheduleError::RunPath { .. } => ("FALLOW_MUTATION_RUNNER_FAILED", None),
651        ScheduleError::UnknownHit(_) => ("FALLOW_MUTATION_PLAN_MISMATCH", None),
652        ScheduleError::Baseline(_) => ("FALLOW_MUTATION_BASELINE_FAILED", None),
653        ScheduleError::UnmatchedTargets(_) | ScheduleError::TargetsNeedTestFilter => {
654            ("FALLOW_MUTATION_TARGET_UNMATCHED", None)
655        }
656    };
657    let mut help = Vec::new();
658    if matches!(error, ScheduleError::RunnerVersion(_)) {
659        help.push(runner_version_help(runner));
660    }
661    if let ScheduleError::RunPath { help: run_path, .. } = error {
662        help.push(run_path.clone());
663    }
664    if matches!(
665        error,
666        ScheduleError::Setup {
667            timed_out: true,
668            ..
669        }
670    ) {
671        help.push(format!(
672            "the runner setup took longer than {}s; on a slow or busy host, pass --setup-timeout with a longer duration, for example 5m",
673            setup_timeout.as_secs()
674        ));
675    }
676    if let Some(tail) = stderr_tail.filter(|tail| !tail.trim().is_empty()) {
677        help.push(format!("companion stderr:\n{}", tail.trim_end()));
678    }
679    let public = mutation_error(code, error.to_string());
680    if help.is_empty() {
681        public
682    } else {
683        public.with_help(help.join("\n"))
684    }
685}
686
687fn default_concurrency() -> usize {
688    std::thread::available_parallelism()
689        .map_or(1, std::num::NonZeroUsize::get)
690        .div_ceil(2)
691        .max(1)
692}
693
694fn runtime_error(runner: Runner, message: String) -> ProgrammaticError {
695    mutation_error("FALLOW_MUTATION_RUNTIME_NOT_FOUND", message)
696        .with_help(runner.runtime_help())
697        .with_context("mutation.runtime")
698}
699
700fn scheduled(plan: &MutationPlan, disposition: MutantDisposition) -> Vec<ScheduledMutant> {
701    plan.mutants
702        .iter()
703        .filter(|mutant| mutant.disposition == disposition)
704        .map(|mutant| ScheduledMutant {
705            id: mutant.mutant.id.as_str().to_owned(),
706            file: mutant.file.clone(),
707        })
708        .collect()
709}
710
711fn schedule_plan(plan: &MutationPlan) -> SchedulePlan {
712    SchedulePlan {
713        mutants: scheduled(plan, MutantDisposition::Planned),
714        unreached: scheduled(plan, MutantDisposition::NoCoverage),
715        pending: scheduled(plan, MutantDisposition::Pending),
716        known_ids: plan
717            .mutants
718            .iter()
719            .map(|mutant| mutant.mutant.id.as_str().to_owned())
720            .collect::<FxHashSet<_>>(),
721        test_files: plan.test_files.clone(),
722        file_test_files: plan
723            .files
724            .iter()
725            .map(|file| (file.path.clone(), file.static_test_files.clone()))
726            .collect(),
727    }
728}
729
730/// The facts of a started run that the report reads.
731struct Execution {
732    outcome: Option<ScheduleOutcome>,
733    runner: Option<MutationRunnerOutput>,
734    cache: Option<MutationCacheOutput>,
735    resume: Option<MutationResumeOutput>,
736    setup_ms: u64,
737}
738
739/// The journal path as the report shows it: relative to the root, with `/`
740/// separators, when the journal is inside the root.
741fn shown_path(root: &Path, path: &Path) -> String {
742    let relative = path.strip_prefix(root).map(Path::to_path_buf).or_else(|_| {
743        canonical_path(path)
744            .strip_prefix(canonical_path(root))
745            .map(Path::to_path_buf)
746    });
747    relative.map_or_else(
748        |_| path.display().to_string(),
749        |relative| {
750            relative
751                .components()
752                .map(|part| part.as_os_str().to_string_lossy())
753                .collect::<Vec<_>>()
754                .join("/")
755        },
756    )
757}
758
759/// The operator names of the journal fingerprint, sorted and without
760/// duplicates, so the order of `--operators` does not change it.
761fn operator_names(operators: &[fallow_engine::mutation::Operator]) -> Vec<String> {
762    let mut names: Vec<String> = operators
763        .iter()
764        .map(|operator| operator.as_str().to_owned())
765        .collect();
766    names.sort_unstable();
767    names.dedup();
768    names
769}
770
771/// A scope path of the journal fingerprint: relative to `root` when it is
772/// inside the root, without `.` parts, with `/` separators.
773fn scope_path(root: &Path, path: &Path) -> String {
774    let relative = path.strip_prefix(root).unwrap_or(path);
775    relative
776        .components()
777        .filter(|part| !matches!(part, std::path::Component::CurDir))
778        .map(|part| part.as_os_str().to_string_lossy())
779        .collect::<Vec<_>>()
780        .join("/")
781}
782
783/// The scope of the journal fingerprint. The paths of a `paths` scope are
784/// normalized, sorted and without duplicates, so `./src/a` and `src/a` give
785/// one fingerprint.
786fn scope_label(options: &MutationRunOptions, base_ref: Option<&str>, root: &Path) -> String {
787    match &options.scope {
788        MutationRunScope::All => "all".to_owned(),
789        MutationRunScope::Paths(paths) => {
790            let mut paths: Vec<String> = paths.iter().map(|path| scope_path(root, path)).collect();
791            paths.sort_unstable();
792            paths.dedup();
793            format!("paths {}", paths.join(","))
794        }
795        MutationRunScope::Changed { .. } => base_ref.map_or_else(
796            || "changed lines of a diff".to_owned(),
797            |base| format!("changed against {base}"),
798        ),
799    }
800}
801
802fn resume_mismatch(mismatch: &JournalMismatch, journal: &str) -> ProgrammaticError {
803    mutation_error(
804        "FALLOW_MUTATION_RESUME_MISMATCH",
805        format!(
806            "the journal {journal} belongs to a run with other inputs: {}",
807            mismatch.differences.join("; ")
808        ),
809    )
810    .with_help("run without --resume to start a new run; that run replaces the journal")
811    .with_context("mutation.resume")
812}
813
814/// The resume facts of a `--resume` run in which no mutant needs a test run.
815/// Such a run reads no journal.
816fn unread_journal(options: &MutationRunOptions, planned: &Planned) -> Option<MutationResumeOutput> {
817    options.resume.then(|| MutationResumeOutput {
818        journal: shown_path(
819            planned.resolved.root(),
820            &Journal::path(&planned.cache_dir.join("mutation")),
821        ),
822        reused: 0,
823        rejected: 0,
824        note: Some("the run read no journal, because no mutant needs a test run".to_owned()),
825    })
826}
827
828/// The result cache (`None` with `--no-cache`) and the outcome journal of a
829/// run. The journal uses the key of the result cache.
830fn open_stores(
831    options: &MutationRunOptions,
832    planned: &Planned,
833    mutation_cache: &Path,
834    runtime: &str,
835    run_dir: &Path,
836) -> ProgrammaticResult<(Option<Arc<ResultCache>>, RunJournal)> {
837    let root = planned.resolved.root();
838    let name = planned.runner.name();
839    let files = key_files(&planned.plan, planned.runner_config.as_deref());
840    let result_cache = open_result_cache(
841        planned.resolved.no_cache,
842        mutation_cache,
843        root,
844        name,
845        files.clone(),
846    );
847    let keys = result_cache
848        .clone()
849        .unwrap_or_else(|| Arc::new(ResultCache::keys_only(mutation_cache, root, name, files)));
850    let header = JournalHeader {
851        journal_format: JOURNAL_FORMAT,
852        fallow_version: env!("CARGO_PKG_VERSION").to_owned(),
853        runner: name.to_owned(),
854        runtime: runtime.to_owned(),
855        run_dir: run_dir
856            .file_name()
857            .map(|hash| hash.to_string_lossy().into_owned())
858            .unwrap_or_default(),
859        runner_config: planned.runner_config.clone(),
860        scope: scope_label(options, planned.base_ref.as_deref(), root),
861        operators: planned.operators.clone(),
862        allow_side_effects: options.allow_side_effects,
863        kill_matrix: options.kill_matrix,
864        kill_matrix_targets: sorted_targets(&options.kill_matrix_targets),
865    };
866    let run_journal = start_journal(options, planned, mutation_cache, &header, keys)?;
867    Ok((result_cache, run_journal))
868}
869
870/// The outcome journal of a started run.
871struct RunJournal {
872    journal: Arc<Journal>,
873    /// The journal path of the report.
874    shown: String,
875    /// Why a `--resume` run started from the beginning.
876    note: Option<String>,
877}
878
879/// Starts the outcome journal of a run. The journal is written with and
880/// without `--no-cache`. `keys` gives the result cache key of each mutant.
881fn start_journal(
882    options: &MutationRunOptions,
883    planned: &Planned,
884    mutation_cache: &Path,
885    header: &JournalHeader,
886    keys: Arc<ResultCache>,
887) -> ProgrammaticResult<RunJournal> {
888    let shown = shown_path(planned.resolved.root(), &Journal::path(mutation_cache));
889    let opened = Journal::open(mutation_cache, header, keys, options.resume)
890        .map_err(|mismatch| resume_mismatch(&mismatch, &shown))?;
891    Ok(RunJournal {
892        journal: Arc::new(opened.journal),
893        shown,
894        note: opened.note,
895    })
896}
897
898/// The resume facts of a `--resume` run, and the issue of a journal that
899/// was not written.
900fn settle_journal(
901    options: &MutationRunOptions,
902    run_journal: RunJournal,
903    outcome: &mut ScheduleOutcome,
904) -> Option<MutationResumeOutput> {
905    if let Some(message) = run_journal.journal.write_error() {
906        outcome.issues.push(ScheduleIssue {
907            code: "journal-write-failed",
908            message: format!(
909                "the outcome journal was not written, so an interrupted run cannot resume each result: {message}"
910            ),
911            mutant_id: None,
912            stderr_tail: None,
913        });
914    }
915    options.resume.then(|| MutationResumeOutput {
916        journal: run_journal.shown,
917        reused: outcome
918            .results
919            .values()
920            .filter(|result| result.resumed)
921            .count(),
922        rejected: run_journal.journal.rejected(),
923        note: run_journal.note,
924    })
925}
926
927/// The result cache of a run. `None` with `--no-cache`.
928fn open_result_cache(
929    no_cache: bool,
930    mutation_cache: &Path,
931    root: &Path,
932    runner: &str,
933    files: KeyFiles,
934) -> Option<Arc<ResultCache>> {
935    (!no_cache).then(|| Arc::new(ResultCache::open(mutation_cache, root, runner, files)))
936}
937
938/// The key files of the result cache. A selected runner config file is a
939/// support file of the key, so a result of one config content is never the
940/// result of another.
941fn key_files(plan: &MutationPlan, runner_config: Option<&str>) -> KeyFiles {
942    let mut files = KeyFiles::from_plan(plan);
943    if let Some(config) = runner_config
944        && !files.support_files.iter().any(|file| file == config)
945    {
946        files.support_files.push(config.to_owned());
947    }
948    files
949}
950
951/// Stores the new results of `outcome` in `cache` and writes the cache file.
952/// A failed write adds a `cache-write-failed` issue and keeps the run result.
953fn store_results(cache: &ResultCache, outcome: &mut ScheduleOutcome) -> MutationCacheOutput {
954    let counts = cache.record(outcome);
955    if let Err(message) = cache.save() {
956        outcome.issues.push(ScheduleIssue {
957            code: "cache-write-failed",
958            message: format!("the mutation result cache was not saved: {message}"),
959            mutant_id: None,
960            stderr_tail: None,
961        });
962    }
963    MutationCacheOutput {
964        hits: counts.hits,
965        stored: counts.stored,
966        not_keyed: NOT_KEYED.iter().map(|&item| item.to_owned()).collect(),
967    }
968}
969
970/// The `init` options of the runner. The `node:test` runner gets the module
971/// loading flags of the `node --test` command in the project scripts. The
972/// `node:test` and `bun:test` runners get the static test files, because
973/// their glob discovery does not go into dot directories. Vitest has its own
974/// include configuration.
975fn init_options(runner: Runner, root: &Path, static_test_files: &[String]) -> InitOptions {
976    let node_args = match runner {
977        Runner::NodeTest => node_test_args(root),
978        Runner::Vitest | Runner::BunTest => Vec::new(),
979    };
980    let extra_test_files = match runner {
981        Runner::NodeTest | Runner::BunTest => static_test_files.to_vec(),
982        Runner::Vitest => Vec::new(),
983    };
984    InitOptions {
985        extra_test_files,
986        node_args,
987        ..InitOptions::default()
988    }
989}
990
991/// The runner facts of the report. `None` when no companion started.
992fn runner_output(
993    outcome: &ScheduleOutcome,
994    name: &str,
995    manifest: &Manifest,
996    runtime: &JsRuntime,
997) -> Option<MutationRunnerOutput> {
998    outcome.ready.as_ref().map(|ready| MutationRunnerOutput {
999        name: name.to_owned(),
1000        version: ready.runner_version.clone(),
1001        protocol_version: manifest.wire_protocol_version,
1002        runtime: MutationRuntimeOutput {
1003            name: runtime.kind.name().to_owned(),
1004            version: runtime.version.clone(),
1005        },
1006        concurrency: outcome.workers,
1007        notes: ready
1008            .notes
1009            .iter()
1010            .filter(|note| manifest.ready_notes.contains(note))
1011            .cloned()
1012            .collect(),
1013    })
1014}
1015
1016/// The public error of a schedule that stopped the run.
1017fn execute(
1018    options: &MutationRunOptions,
1019    planned: &Planned,
1020    deadline: Option<Instant>,
1021    progress: MutationProgressSink<'_>,
1022) -> ProgrammaticResult<Execution> {
1023    let plan = &planned.plan;
1024    let schedule = schedule_plan(plan);
1025    // With no planned mutant the dry run still runs the static test files,
1026    // because a hit on a statically unreached mutant is a static map miss.
1027    if schedule.mutants.is_empty()
1028        && (schedule.unreached.is_empty() || schedule.test_files.is_empty())
1029    {
1030        return Ok(Execution {
1031            outcome: None,
1032            runner: None,
1033            cache: None,
1034            resume: unread_journal(options, planned),
1035            setup_ms: 0,
1036        });
1037    }
1038    progress(MutationProgress::Setup {
1039        mutants: schedule.mutants.len(),
1040    });
1041    let setup_started = Instant::now();
1042    let manifest = manifest()
1043        .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
1044    let runner = planned.runner;
1045    let name = runner.name();
1046    let range = manifest.runner(name).ok_or_else(|| {
1047        mutation_error(
1048            "FALLOW_MUTATION_PROTOCOL_INVALID",
1049            format!("the protocol manifest has no `{name}` runner"),
1050        )
1051    })?;
1052    let runtime = discover_runtime(options.runtime.as_deref(), runner.runtimes())
1053        .map_err(|message| runtime_error(runner, message))?;
1054    let cache_error =
1055        |message: String| mutation_error("FALLOW_MUTATION_CACHE_WRITE_FAILED", message);
1056    ignore_cache_dir(&planned.cache_dir).map_err(|error| cache_error(error.to_string()))?;
1057    let mutation_cache = planned.cache_dir.join("mutation");
1058    let companion = install(&mutation_cache, COMPANION_FILES)
1059        .map_err(|message| mutation_error("FALLOW_MUTATION_COMPANION_INTEGRITY", message))?;
1060    let files: Vec<RunFile<'_>> = plan
1061        .files
1062        .iter()
1063        .map(|file| RunFile {
1064            path: &file.path,
1065            code: &file.instrumented_code,
1066        })
1067        .collect();
1068    let run_dir = write_run_dir(&mutation_cache, &files, Some(&companion)).map_err(cache_error)?;
1069    let root = planned.resolved.root().to_path_buf();
1070    let runtime_label = format!("{} {}", runtime.kind.name(), runtime.version);
1071    let (result_cache, run_journal) = open_stores(
1072        options,
1073        planned,
1074        &mutation_cache,
1075        &runtime_label,
1076        &run_dir.dir,
1077    )?;
1078    let config = ScheduleConfig {
1079        init: InitRequest {
1080            root: root.to_string_lossy().into_owned(),
1081            runner: name.to_owned(),
1082            config_path: planned.runner_config.clone(),
1083            run_dir: run_dir.dir.to_string_lossy().into_owned(),
1084            path_map: run_dir.path_map.clone(),
1085            options: init_options(runner, &root, &plan.test_files),
1086        },
1087        runner: range.clone(),
1088        kill_matrix: options.kill_matrix,
1089        targets: options.kill_matrix_targets.clone(),
1090        concurrency: options.concurrency.unwrap_or_else(default_concurrency),
1091        runner_timeout: options.runner_timeout.unwrap_or(DEFAULT_RUNNER_TIMEOUT),
1092        deadline,
1093        cache: result_cache
1094            .clone()
1095            .map(|cache| cache as Arc<dyn ResultLookup>),
1096        journal: Some(Arc::clone(&run_journal.journal) as Arc<dyn OutcomeJournal>),
1097    };
1098    let spawner = ProcessSpawner {
1099        runtime: runtime.path.clone(),
1100        companion,
1101        root,
1102        wire_version: manifest.wire_protocol_version,
1103        session_token_env: manifest.session_token_env.clone(),
1104    };
1105    let setup_ms = millis(setup_started.elapsed());
1106    let mut outcome = run_schedule_with_progress(&spawner, &schedule, &config, progress)
1107        .map_err(|error| schedule_error(&error, &config.runner, config.runner_timeout))?;
1108    let runner = runner_output(&outcome, name, manifest, &runtime);
1109    let cache = match (&result_cache, outcome.ready.is_some()) {
1110        (Some(result_cache), true) => Some(store_results(result_cache, &mut outcome)),
1111        _ => None,
1112    };
1113    let resume = settle_journal(options, run_journal, &mut outcome);
1114    Ok(Execution {
1115        outcome: Some(outcome),
1116        runner,
1117        cache,
1118        resume,
1119        setup_ms,
1120    })
1121}
1122
1123/// The errors of a finished run: the scheduler issues and the worktree facts.
1124fn run_issues(
1125    outcome: Option<&ScheduleOutcome>,
1126    changed_paths: &[String],
1127    check_error: Option<String>,
1128) -> Vec<fallow_output::MutationRunIssue> {
1129    let mut errors = issues(outcome);
1130    if !changed_paths.is_empty() {
1131        errors.push(fallow_output::MutationRunIssue {
1132            code: "worktree-changed".to_owned(),
1133            message: format!(
1134                "the run changed {} worktree {}; a mutant or a test wrote to the project",
1135                changed_paths.len(),
1136                path_noun(changed_paths.len())
1137            ),
1138            mutant_id: None,
1139            stderr_tail: None,
1140        });
1141    }
1142    if let Some(message) = check_error {
1143        errors.push(fallow_output::MutationRunIssue {
1144            code: "worktree-check-failed".to_owned(),
1145            message: format!(
1146                "the end-of-run worktree check failed, so stray writes are unknown: {message}"
1147            ),
1148            mutant_id: None,
1149            stderr_tail: None,
1150        });
1151    }
1152    errors
1153}
1154
1155/// The wall time of each phase. A run that started no companion has only
1156/// the plan and the type check times.
1157fn run_timings(
1158    outcome: Option<&ScheduleOutcome>,
1159    setup_ms: u64,
1160    plan_ms: u64,
1161    typecheck_ms: u64,
1162) -> MutationTimings {
1163    outcome.map_or_else(
1164        || MutationTimings {
1165            plan_ms,
1166            typecheck_ms,
1167            ..MutationTimings::default()
1168        },
1169        |outcome| MutationTimings {
1170            plan_ms,
1171            setup_ms: setup_ms + millis(outcome.timings.setup),
1172            dry_run_ms: millis(outcome.timings.dry_run),
1173            mutants_ms: millis(outcome.timings.mutants),
1174            retry_ms: millis(outcome.timings.retry),
1175            typecheck_ms,
1176        },
1177    )
1178}
1179
1180/// Refuses a run with the survivor type check before the tests start when no
1181/// trusted type-aware companion exists.
1182fn guard_typecheck_companion(enabled: bool, root: &Path) -> ProgrammaticResult<()> {
1183    if !enabled {
1184        return Ok(());
1185    }
1186    crate::type_aware::check_typecheck_companion(root).map_err(|message| {
1187        mutation_error("FALLOW_MUTATION_TYPECHECK_UNAVAILABLE", message)
1188            .with_help("install the fallow-type-aware companion, or run without --typecheck")
1189            .with_context("mutation.typecheck")
1190    })
1191}
1192
1193/// Plans the mutants, runs the project tests against each planned mutant,
1194/// and reports the result.
1195///
1196/// The run refuses a dirty git worktree unless
1197/// [`MutationRunOptions::allow_dirty`] is set. After the run it compares the
1198/// worktree with the start state and reports each changed path.
1199///
1200/// # Errors
1201///
1202/// Returns an error for invalid options, a dirty worktree, a failed plan, a
1203/// missing runtime, a companion that does not start or load the runner, a
1204/// companion file that changed after install, or a test suite that fails
1205/// with no active mutant outside each test file.
1206pub fn run_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationReport> {
1207    run_mutation_with_progress(options, &|_| {})
1208}
1209
1210/// [`run_mutation`] that sends a [`MutationProgress`] event at the start of
1211/// each run phase and after each finished mutant.
1212///
1213/// The events arrive on the calling thread and on the scheduler worker
1214/// threads. A sink must return quickly, because a worker waits for it.
1215///
1216/// # Errors
1217///
1218/// Returns the same errors as [`run_mutation`].
1219pub fn run_mutation_with_progress(
1220    options: &MutationRunOptions,
1221    progress: MutationProgressSink<'_>,
1222) -> ProgrammaticResult<MutationReport> {
1223    let started = Instant::now();
1224    let deadline = options.time_budget.map(|budget| started + budget);
1225    let mut start_snapshot = None;
1226    let planned = plan_for(options, |root, cache_dir| {
1227        guard_cache_dir(root, cache_dir)?;
1228        start_snapshot = take_worktree_snapshot(root, cache_dir, &options.output_paths, None)?;
1229        guard_worktree(options.allow_dirty, start_snapshot.as_ref())
1230    })?;
1231    guard_cache_holds_no_planned_file(planned.resolved.root(), &planned.cache_dir, &planned.plan)?;
1232    guard_typecheck_companion(options.typecheck, planned.resolved.root())?;
1233    let normalized = with_normalized_targets(options, planned.resolved.root())?;
1234    let options = normalized.as_ref().unwrap_or(options);
1235    let plan_ms = millis(started.elapsed());
1236    let execution = execute(options, &planned, deadline, progress);
1237    progress(MutationProgress::Finalize);
1238    let worktree_end = settle_worktree(start_snapshot.as_ref(), |start| {
1239        take_worktree_snapshot(
1240            planned.resolved.root(),
1241            &planned.cache_dir,
1242            &options.output_paths,
1243            Some(start),
1244        )
1245    });
1246    let execution = execution.map_err(|error| with_worktree_facts(error, &worktree_end))?;
1247    let WorktreeEnd {
1248        changed_paths,
1249        check_error,
1250    } = worktree_end;
1251    let plan = &planned.plan;
1252    let outcome = execution.outcome.as_ref();
1253    let mut results = mutant_results(plan, outcome);
1254    let typecheck = typecheck_survivors(
1255        options.typecheck,
1256        planned.resolved.root(),
1257        plan,
1258        &mut results,
1259    );
1260    let typecheck_ms = millis(typecheck.elapsed);
1261    let baseline = baseline_failures(outcome);
1262    let completion = completion(&CompletionFacts {
1263        plan,
1264        results: &results,
1265        baseline_failures: &baseline,
1266        worktree_changed: !changed_paths.is_empty(),
1267        worktree_unchecked: check_error.is_some(),
1268        unretried: outcome.is_some_and(|outcome| !outcome.unretried.is_empty()),
1269        unloaded_paths: outcome.map_or(&[], |outcome| outcome.unloaded_paths.as_slice()),
1270        undiscovered_test_files: outcome
1271            .map_or(&[], |outcome| outcome.undiscovered_test_files.as_slice()),
1272        typecheck_failed: typecheck.issue.is_some(),
1273        promoted: outcome.map_or(&[], |outcome| outcome.promoted.as_slice()),
1274    });
1275    let mut errors = run_issues(outcome, &changed_paths, check_error);
1276    errors.extend(typecheck.issue);
1277    let timings = run_timings(outcome, execution.setup_ms, plan_ms, typecheck_ms);
1278    Ok(MutationReport {
1279        schema_version: MutationSchemaVersion::V2,
1280        version: tool_version(),
1281        elapsed_ms: ElapsedMs(millis(started.elapsed())),
1282        kill_matrix: crate::mutation::kill_matrix::build(
1283            &kill_matrix_mode(options, outcome),
1284            &results,
1285            &baseline,
1286            &completion,
1287            &plan.mutants,
1288            outcome.map(|outcome| &outcome.test_files),
1289        ),
1290        completion,
1291        scope: scope_output(options, planned.base_ref.clone()),
1292        runner: execution.runner,
1293        cache: execution.cache,
1294        resume: execution.resume,
1295        summary: summary(&results),
1296        functions: function_results(plan, &results),
1297        mutants: results,
1298        no_test_files: plan.no_test_files,
1299        baseline_failures: baseline,
1300        skipped_files: skipped_files(plan),
1301        unmatched_paths: plan.unmatched_paths.clone(),
1302        unloaded_paths: outcome
1303            .map(|outcome| outcome.unloaded_paths.clone())
1304            .unwrap_or_default(),
1305        worktree: MutationWorktreeCheck {
1306            checked: start_snapshot.is_some(),
1307            allow_dirty: options.allow_dirty,
1308            dirty_at_start: start_snapshot
1309                .as_ref()
1310                .map(WorktreeSnapshot::dirty_paths)
1311                .unwrap_or_default(),
1312            changed_paths,
1313        },
1314        errors,
1315        timings,
1316        files: plan_files(plan),
1317        verdicts: None,
1318        typecheck: typecheck.output,
1319    })
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324    use super::*;
1325
1326    fn vitest_range() -> &'static RunnerRange {
1327        manifest()
1328            .expect("manifest")
1329            .runner("vitest")
1330            .expect("vitest range")
1331    }
1332
1333    #[test]
1334    fn a_runner_version_error_names_the_supported_range_as_the_install_step() {
1335        let error = schedule_error(
1336            &ScheduleError::RunnerVersion(
1337                "vitest 4.0.18 is not supported; the supported range is >=4.1.0 <6.0.0".to_owned(),
1338            ),
1339            vitest_range(),
1340            Duration::from_secs(120),
1341        );
1342        assert_eq!(
1343            error.code.as_deref(),
1344            Some("FALLOW_MUTATION_RUNNER_UNSUPPORTED")
1345        );
1346        assert_eq!(
1347            error.help.as_deref(),
1348            Some(
1349                "install vitest 4.1.0 or a later version below 6.0.0; a vitest 4.x release from 4.1.0 is in the range"
1350            )
1351        );
1352
1353        let help: Vec<String> = manifest()
1354            .expect("manifest")
1355            .runners
1356            .iter()
1357            .map(runner_version_help)
1358            .collect();
1359        assert_eq!(
1360            help,
1361            [
1362                "install vitest 4.1.0 or a later version below 6.0.0; a vitest 4.x release from 4.1.0 is in the range",
1363                "install node 22.18.0 or a later version below 27.0.0; a node 22.x release from 22.18.0 is in the range",
1364                "install bun 1.4.0 or a later version below 2.0.0; a bun 1.x release from 1.4.0 is in the range",
1365            ]
1366        );
1367
1368        let major_start = RunnerRange {
1369            name: "vitest".to_owned(),
1370            package: "vitest".to_owned(),
1371            min_version: "5.0.0".to_owned(),
1372            max_version_exclusive: "6.0.0".to_owned(),
1373        };
1374        assert_eq!(
1375            runner_version_help(&major_start),
1376            "install vitest 5.0.0 or a later version below 6.0.0"
1377        );
1378    }
1379
1380    #[test]
1381    fn a_setup_watchdog_error_names_the_setup_timeout_flag() {
1382        let error = schedule_error(
1383            &ScheduleError::Setup {
1384                message: "the mutation companion dry_run failed".to_owned(),
1385                stderr_tail: Some("vitest started\n".to_owned()),
1386                timed_out: true,
1387            },
1388            vitest_range(),
1389            Duration::from_secs(120),
1390        );
1391        let help = error.help.as_deref().unwrap_or_default();
1392        assert!(help.contains("longer than 120s"), "{help}");
1393        assert!(help.contains("--setup-timeout"), "{help}");
1394        assert!(help.contains("companion stderr:\nvitest started"), "{help}");
1395
1396        let other = schedule_error(
1397            &ScheduleError::Setup {
1398                message: "the mutation companion init failed".to_owned(),
1399                stderr_tail: None,
1400                timed_out: false,
1401            },
1402            vitest_range(),
1403            Duration::from_secs(120),
1404        );
1405        assert_eq!(other.help, None);
1406    }
1407
1408    #[test]
1409    fn a_failed_self_check_is_a_runner_failure_with_its_own_help() {
1410        let error = schedule_error(
1411            &ScheduleError::RunPath {
1412                message: "vitest 5.0.4 executes no tests in a mutant run".to_owned(),
1413                help: "report this with the runner name and version (vitest 5.0.4)".to_owned(),
1414            },
1415            vitest_range(),
1416            Duration::from_secs(120),
1417        );
1418        assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_RUNNER_FAILED"));
1419        assert_eq!(error.exit_code, 2);
1420        assert_eq!(
1421            error.message,
1422            "vitest 5.0.4 executes no tests in a mutant run"
1423        );
1424        assert_eq!(
1425            error.help.as_deref(),
1426            Some("report this with the runner name and version (vitest 5.0.4)")
1427        );
1428    }
1429
1430    #[test]
1431    fn a_failed_end_check_keeps_the_execute_error_and_reports_the_check_error() {
1432        let start = WorktreeSnapshot::default();
1433        let end = settle_worktree(Some(&start), |_| {
1434            Err(mutation_error(
1435                "FALLOW_MUTATION_WORKTREE_CHECK_FAILED",
1436                "git status failed",
1437            ))
1438        });
1439        assert!(end.changed_paths.is_empty());
1440        assert_eq!(end.check_error.as_deref(), Some("git status failed"));
1441
1442        let error = with_worktree_facts(
1443            mutation_error(
1444                "FALLOW_MUTATION_SETUP_FAILED",
1445                "the companion did not start",
1446            ),
1447            &end,
1448        );
1449        assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_SETUP_FAILED"));
1450        assert!(
1451            error.message.starts_with("the companion did not start"),
1452            "{}",
1453            error.message
1454        );
1455        assert!(
1456            error.message.contains("git status failed"),
1457            "{}",
1458            error.message
1459        );
1460    }
1461
1462    #[test]
1463    fn every_config_operator_name_maps_to_an_engine_operator() {
1464        for operator in fallow_engine::mutation::Operator::ALL {
1465            let name: fallow_config::MutationOperatorName =
1466                serde_json::from_value(serde_json::json!(operator.as_str()))
1467                    .expect("a config operator name");
1468            assert_eq!(
1469                fallow_engine::mutation::Operator::from_name(name.as_str()),
1470                Some(operator)
1471            );
1472        }
1473    }
1474
1475    #[test]
1476    fn no_cache_opens_no_result_cache() {
1477        let dir = tempfile::tempdir().expect("dir");
1478        let plan = MutationPlan {
1479            files: Vec::new(),
1480            mutants: Vec::new(),
1481            test_files: Vec::new(),
1482            reach_files: Vec::new(),
1483            test_file_reach: std::collections::BTreeMap::new(),
1484            support_files: Vec::new(),
1485            counts: fallow_engine::mutation::MutationPlanCounts::default(),
1486            no_test_files: false,
1487            framework_config_checked: false,
1488            skipped_files: Vec::new(),
1489            unmatched_paths: Vec::new(),
1490        };
1491        assert!(
1492            open_result_cache(
1493                true,
1494                dir.path(),
1495                dir.path(),
1496                "vitest",
1497                KeyFiles::from_plan(&plan)
1498            )
1499            .is_none()
1500        );
1501        assert!(
1502            open_result_cache(
1503                false,
1504                dir.path(),
1505                dir.path(),
1506                "vitest",
1507                KeyFiles::from_plan(&plan)
1508            )
1509            .is_some()
1510        );
1511    }
1512
1513    fn empty_plan() -> MutationPlan {
1514        MutationPlan {
1515            files: Vec::new(),
1516            mutants: Vec::new(),
1517            test_files: Vec::new(),
1518            reach_files: Vec::new(),
1519            test_file_reach: std::collections::BTreeMap::new(),
1520            support_files: Vec::new(),
1521            counts: fallow_engine::mutation::MutationPlanCounts::default(),
1522            no_test_files: false,
1523            framework_config_checked: false,
1524            skipped_files: Vec::new(),
1525            unmatched_paths: Vec::new(),
1526        }
1527    }
1528
1529    #[test]
1530    fn a_cache_dir_at_or_above_the_root_is_refused() {
1531        let dir = tempfile::tempdir().expect("dir");
1532        let root = dir.path().join("project");
1533        std::fs::create_dir_all(root.join("src")).expect("dir");
1534        for cache in [root.clone(), root.join("."), dir.path().to_path_buf()] {
1535            let error = guard_cache_dir(&root, &cache).expect_err("refused");
1536            assert_eq!(
1537                error.code.as_deref(),
1538                Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1539            );
1540            assert_eq!(error.exit_code, 2);
1541            assert_eq!(error.context.as_deref(), Some("cache.dir"));
1542        }
1543        assert!(guard_cache_dir(&root, &root.join(".fallow")).is_ok());
1544        assert!(guard_cache_dir(&root, &root.join("src")).is_ok());
1545    }
1546
1547    #[test]
1548    fn a_cache_dir_that_holds_a_planned_file_is_refused() {
1549        let dir = tempfile::tempdir().expect("dir");
1550        let root = dir.path();
1551        let mut plan = empty_plan();
1552        plan.files.push(fallow_engine::mutation::PlannedFile {
1553            path: "src/a.ts".to_owned(),
1554            source_sha256: String::new(),
1555            instrumented_code: String::new(),
1556            static_test_files: Vec::new(),
1557        });
1558        plan.test_files.push("test/a.test.ts".to_owned());
1559
1560        let error = guard_cache_holds_no_planned_file(root, &root.join("src"), &plan)
1561            .expect_err("the cache holds a planned source file");
1562        assert_eq!(
1563            error.code.as_deref(),
1564            Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1565        );
1566        assert!(error.message.contains("src/a.ts"), "{}", error.message);
1567        let error = guard_cache_holds_no_planned_file(root, &root.join("test"), &plan)
1568            .expect_err("the cache holds a planned test file");
1569        assert!(
1570            error.message.contains("test/a.test.ts"),
1571            "{}",
1572            error.message
1573        );
1574        assert!(guard_cache_holds_no_planned_file(root, &root.join(".fallow"), &plan).is_ok());
1575    }
1576
1577    #[test]
1578    fn kill_matrix_targets_take_the_form_of_runner_test_ids() {
1579        let root = Path::new("/project");
1580        assert_eq!(normalize_target(root, "./test/a.test.ts"), "test/a.test.ts");
1581        assert_eq!(
1582            normalize_target(root, "test\\a.test.ts::adds > two"),
1583            "test/a.test.ts::adds > two"
1584        );
1585        if cfg!(unix) {
1586            assert_eq!(
1587                normalize_target(root, "/project/test/a.test.ts::a::b"),
1588                "test/a.test.ts::a::b"
1589            );
1590            assert_eq!(
1591                normalize_target(root, "/other/a.test.ts"),
1592                "/other/a.test.ts"
1593            );
1594        }
1595    }
1596
1597    #[test]
1598    fn a_target_that_normalizes_to_no_file_is_refused_and_order_does_not_matter() {
1599        let root = Path::new("/project");
1600        for raw in ["./", "././", "::name"] {
1601            let options = MutationRunOptions {
1602                kill_matrix_targets: vec![raw.to_owned()],
1603                ..MutationRunOptions::default()
1604            };
1605            let error = with_normalized_targets(&options, root).expect_err(raw);
1606            assert!(error.message.contains("names no test file"), "{raw}");
1607        }
1608        let options = MutationRunOptions {
1609            kill_matrix_targets: vec!["./b.test.ts".to_owned(), "b.test.ts".to_owned()],
1610            ..MutationRunOptions::default()
1611        };
1612        let normalized = with_normalized_targets(&options, root)
1613            .expect("valid")
1614            .expect("target mode");
1615        assert_eq!(normalized.kill_matrix_targets, ["b.test.ts"]);
1616        assert_eq!(
1617            sorted_targets(&["b".to_owned(), "a".to_owned()]),
1618            sorted_targets(&["a".to_owned(), "b".to_owned()])
1619        );
1620    }
1621
1622    #[test]
1623    fn the_full_and_the_target_kill_matrix_are_exclusive() {
1624        let both = MutationRunOptions {
1625            kill_matrix: true,
1626            kill_matrix_targets: vec!["test/a.test.ts".to_owned()],
1627            ..MutationRunOptions::default()
1628        };
1629        assert!(validate(&both).is_err());
1630        let blank = MutationRunOptions {
1631            kill_matrix_targets: vec![" ".to_owned()],
1632            ..MutationRunOptions::default()
1633        };
1634        assert!(validate(&blank).is_err());
1635    }
1636
1637    #[test]
1638    fn no_start_snapshot_needs_no_end_check() {
1639        let end = settle_worktree(None, |_| panic!("no end check without a start snapshot"));
1640        assert!(end.changed_paths.is_empty());
1641        assert!(end.check_error.is_none());
1642    }
1643
1644    #[test]
1645    fn the_glob_runners_get_the_static_test_files_and_vitest_does_not() {
1646        let dir = tempfile::tempdir().expect("dir");
1647        let files = vec![".github/tests/math.test.mjs".to_owned()];
1648        for runner in [Runner::NodeTest, Runner::BunTest] {
1649            let options = init_options(runner, dir.path(), &files);
1650            assert_eq!(options.extra_test_files, files, "{runner:?}");
1651            assert!(options.test_files.is_empty(), "{runner:?}");
1652        }
1653        let vitest = init_options(Runner::Vitest, dir.path(), &files);
1654        assert!(vitest.extra_test_files.is_empty());
1655    }
1656
1657    #[test]
1658    fn equal_scopes_and_operators_give_one_fingerprint() {
1659        let root = Path::new("/project");
1660        let paths = |paths: &[&str]| MutationRunOptions {
1661            scope: MutationRunScope::Paths(paths.iter().map(PathBuf::from).collect()),
1662            ..MutationRunOptions::default()
1663        };
1664        let label = scope_label(&paths(&["src/a", "lib"]), None, root);
1665        for same in [
1666            paths(&["./src/a", "lib"]),
1667            paths(&["lib/", "src/a"]),
1668            paths(&["/project/src/a", "lib", "./lib"]),
1669        ] {
1670            assert_eq!(scope_label(&same, None, root), label, "{:?}", same.scope);
1671        }
1672        assert_ne!(scope_label(&paths(&["src/b"]), None, root), label);
1673
1674        use fallow_engine::mutation::Operator;
1675        let names = operator_names(&[
1676            Operator::RelationalOperator,
1677            Operator::ArithmeticOperator,
1678            Operator::RelationalOperator,
1679        ]);
1680        assert_eq!(
1681            names,
1682            operator_names(&[Operator::ArithmeticOperator, Operator::RelationalOperator,])
1683        );
1684    }
1685}