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