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        mutant_ids: (!options.mutant_ids.is_empty())
414            .then(|| options.mutant_ids.iter().cloned().collect()),
415    };
416    // The runner decision reads the test files of the first plan. A second
417    // plan without the component files keeps that decision.
418    let mut selected = None;
419    let plan = resolved
420        .install(|| {
421            plan_mutations_for_session_with(&session, &request, |plan| {
422                let runner = select_runner(configured, resolved.root(), &plan.test_files);
423                selected = Some(runner);
424                !runner.loads_component_files()
425            })
426        })
427        .map_err(|error| mutation_error("FALLOW_MUTATION_PLAN_FAILED", error.to_string()))?;
428    let runner =
429        selected.unwrap_or_else(|| select_runner(configured, resolved.root(), &plan.test_files));
430    let runner_config = runner_config(options, &session, resolved.root(), runner)?;
431    Ok(Planned {
432        resolved,
433        cache_dir,
434        runner,
435        plan,
436        base_ref,
437        runner_config,
438        operators: operator_names,
439    })
440}
441
442/// Builds the static mutation plan. It runs no user code.
443///
444/// # Errors
445///
446/// Returns an error for invalid options, a base ref that does not resolve,
447/// or a failed analysis.
448pub fn plan_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationPlanOutput> {
449    let started = Instant::now();
450    let planned = plan_for(options, |_, _| Ok(()))?;
451    let plan = &planned.plan;
452    Ok(MutationPlanOutput {
453        schema_version: MutationPlanSchemaVersion::V1,
454        version: tool_version(),
455        elapsed_ms: ElapsedMs(millis(started.elapsed())),
456        scope: scope_output(options, planned.base_ref.clone()),
457        counts: plan_counts(plan),
458        mutants: plan_mutants(plan),
459        files: plan_files(plan),
460        test_files: plan.test_files.clone(),
461        no_test_files: plan.no_test_files,
462        framework_config_checked: plan.framework_config_checked,
463        skipped_files: skipped_files(plan),
464        unmatched_paths: plan.unmatched_paths.clone(),
465    })
466}
467
468fn unsafe_cache_dir(message: String) -> ProgrammaticError {
469    mutation_error("FALLOW_MUTATION_UNSAFE_CACHE_DIR", message)
470        .with_help(
471            "set cache.dir or FALLOW_CACHE_DIR to a directory that holds no project file, such as .fallow",
472        )
473        .with_context("cache.dir")
474}
475
476/// Refuses a cache directory that is the root or a directory above it. The
477/// worktree check leaves the mutation cache out, and the analysis writes a
478/// `.gitignore` that ignores the whole cache directory, so such a cache
479/// directory hides each stray write from the check.
480fn guard_cache_dir(root: &Path, cache_dir: &Path) -> ProgrammaticResult<()> {
481    if !canonical_path(root).starts_with(canonical_path(cache_dir)) {
482        return Ok(());
483    }
484    Err(unsafe_cache_dir(format!(
485        "the cache directory `{}` is the project root or a directory above it, so the worktree check cannot see stray writes",
486        cache_dir.display()
487    )))
488}
489
490/// Refuses a cache directory that holds a planned source or test file.
491fn guard_cache_holds_no_planned_file(
492    root: &Path,
493    cache_dir: &Path,
494    plan: &MutationPlan,
495) -> ProgrammaticResult<()> {
496    let root = canonical_path(root);
497    let cache = canonical_path(cache_dir);
498    let inside = plan
499        .files
500        .iter()
501        .map(|file| file.path.as_str())
502        .chain(plan.test_files.iter().map(String::as_str))
503        .find(|path| root.join(path).starts_with(&cache));
504    let Some(path) = inside else {
505        return Ok(());
506    };
507    Err(unsafe_cache_dir(format!(
508        "the cache directory `{}` holds the project file `{path}`, so the worktree check cannot see stray writes",
509        cache_dir.display()
510    )))
511}
512
513fn take_worktree_snapshot(
514    root: &Path,
515    cache_dir: &Path,
516    output_paths: &[PathBuf],
517    start: Option<&WorktreeSnapshot>,
518) -> ProgrammaticResult<Option<WorktreeSnapshot>> {
519    // The caller writes a relative output path against the process
520    // directory, which can be below the root.
521    let cwd = std::env::current_dir().unwrap_or_else(|_| root.to_path_buf());
522    let outputs = output_paths.iter().map(|path| cwd.join(path));
523    // Only the mutation cache is left out of the status check. The analysis
524    // caches next to it are git-ignored, and an ignored file changes only
525    // in the ignored-file check, so the whole cache is left out there.
526    let exclusions = Exclusions {
527        paths: std::iter::once(cache_dir.join("mutation"))
528            .chain(outputs)
529            .collect(),
530        ignored: vec![cache_dir.to_path_buf()],
531    };
532    snapshot(root, &exclusions, start)
533        .map_err(|message| mutation_error("FALLOW_MUTATION_WORKTREE_CHECK_FAILED", message))
534}
535
536/// The worktree facts at the end of a run.
537struct WorktreeEnd {
538    /// The paths that changed since the start snapshot.
539    changed_paths: Vec<String>,
540    /// Why the end snapshot failed. Stray writes are then unknown.
541    check_error: Option<String>,
542}
543
544/// Compares the worktree with `start`. A failed end snapshot is a fact of
545/// the report, never a reason to drop the run result or its error.
546fn settle_worktree(
547    start: Option<&WorktreeSnapshot>,
548    take_end: impl FnOnce(&WorktreeSnapshot) -> ProgrammaticResult<Option<WorktreeSnapshot>>,
549) -> WorktreeEnd {
550    let Some(start) = start else {
551        return WorktreeEnd {
552            changed_paths: Vec::new(),
553            check_error: None,
554        };
555    };
556    match take_end(start) {
557        Ok(end) => WorktreeEnd {
558            changed_paths: end.map(|end| start.changed_paths(&end)).unwrap_or_default(),
559            check_error: None,
560        },
561        Err(error) => WorktreeEnd {
562            changed_paths: Vec::new(),
563            check_error: Some(error.message),
564        },
565    }
566}
567
568/// Adds the worktree facts to the error of a failed run.
569fn with_worktree_facts(mut error: ProgrammaticError, end: &WorktreeEnd) -> ProgrammaticError {
570    if !end.changed_paths.is_empty() {
571        error.message = format!(
572            "{}; the run changed these worktree paths: {}",
573            error.message,
574            end.changed_paths.join(", ")
575        );
576    }
577    if let Some(check_error) = &end.check_error {
578        error.message = format!(
579            "{}; the end-of-run worktree check failed: {check_error}",
580            error.message
581        );
582    }
583    error
584}
585
586const fn path_noun(count: usize) -> &'static str {
587    if count == 1 { "path" } else { "paths" }
588}
589
590fn guard_worktree(allow_dirty: bool, start: Option<&WorktreeSnapshot>) -> ProgrammaticResult<()> {
591    if allow_dirty {
592        return Ok(());
593    }
594    let Some(start) = start else {
595        return Err(mutation_error(
596            "FALLOW_MUTATION_NOT_A_REPOSITORY",
597            "mutation testing runs the tests against changed code and needs a git worktree to detect stray writes",
598        )
599        .with_help("run inside a git worktree, or pass --allow-dirty"));
600    };
601    let dirty = start.dirty_paths();
602    if dirty.is_empty() {
603        return Ok(());
604    }
605    let shown: Vec<&str> = dirty.iter().take(10).map(String::as_str).collect();
606    Err(mutation_error(
607        "FALLOW_MUTATION_DIRTY_WORKTREE",
608        format!(
609            "the git worktree has {} uncommitted {}: {}",
610            dirty.len(),
611            path_noun(dirty.len()),
612            shown.join(", ")
613        ),
614    )
615    .with_help("commit or stash the changes, or pass --allow-dirty"))
616}
617
618/// The guards that need the plan: the test-only worktree of a recheck, the
619/// requested mutant ids, the cache directory and the type-check companion.
620fn guard_planned(
621    options: &MutationRunOptions,
622    planned: &Planned,
623    start: Option<&WorktreeSnapshot>,
624) -> ProgrammaticResult<()> {
625    if options.test_changes_only && !options.allow_dirty {
626        guard_test_changes_only(planned, start)?;
627    }
628    guard_mutant_ids(options, &planned.plan)?;
629    guard_cache_holds_no_planned_file(planned.resolved.root(), &planned.cache_dir, &planned.plan)?;
630    guard_typecheck_companion(options.typecheck, planned.resolved.root())
631}
632
633/// Refuses a dirty path that is not a test file, so a run with
634/// [`MutationRunOptions::test_changes_only`] proves a change of the tests
635/// only. A test file is a path that the test path rules match, or a test
636/// file of the plan.
637fn guard_test_changes_only(
638    planned: &Planned,
639    start: Option<&WorktreeSnapshot>,
640) -> ProgrammaticResult<()> {
641    let Some(start) = start else {
642        return Ok(());
643    };
644    let root = planned.resolved.root();
645    let test_files: FxHashSet<&str> = planned.plan.test_files.iter().map(String::as_str).collect();
646    let changed: Vec<String> = start
647        .dirty_paths()
648        .into_iter()
649        .filter(|path| {
650            !test_files.contains(path.as_str())
651                && !fallow_engine::test_paths::is_test_path_str(root, path)
652        })
653        .collect();
654    if changed.is_empty() {
655        return Ok(());
656    }
657    let shown: Vec<&str> = changed.iter().take(10).map(String::as_str).collect();
658    Err(mutation_error(
659        "FALLOW_MUTATION_NON_TEST_CHANGE",
660        format!(
661            "the git worktree changes {} {} that {} not a test file: {}",
662            changed.len(),
663            path_noun(changed.len()),
664            if changed.len() == 1 { "is" } else { "are" },
665            shown.join(", ")
666        ),
667    )
668    .with_help(
669        "a recheck proves a change of the tests only; commit or stash the other changes, then run `fallow mutation` again for new results",
670    ))
671}
672
673/// Refuses a requested mutant id that the plan does not have. The id of a
674/// mutant changes when its source changes.
675fn guard_mutant_ids(options: &MutationRunOptions, plan: &MutationPlan) -> ProgrammaticResult<()> {
676    if options.mutant_ids.is_empty() {
677        return Ok(());
678    }
679    let planned: FxHashSet<&str> = plan
680        .mutants
681        .iter()
682        .map(|mutant| mutant.mutant.id.as_str())
683        .collect();
684    let mut missing: Vec<&str> = options
685        .mutant_ids
686        .iter()
687        .map(String::as_str)
688        .filter(|id| !planned.contains(id))
689        .collect();
690    if missing.is_empty() {
691        return Ok(());
692    }
693    missing.sort_unstable();
694    missing.dedup();
695    Err(mutation_error(
696        "FALLOW_MUTATION_UNKNOWN_MUTANT",
697        format!(
698            "the plan has no mutant with the {} {}",
699            if missing.len() == 1 { "id" } else { "ids" },
700            missing.join(", ")
701        ),
702    )
703    .with_context("mutation.mutantId")
704    .with_help(
705        "a mutant id changes when its source changes; run `fallow mutation` again for new ids",
706    ))
707}
708
709/// The help of a runner version outside `range`. It names the supported
710/// range as an install step. When the minimum is not a `.0.0` release, it
711/// also says that a minor update inside the major version is enough.
712fn runner_version_help(range: &RunnerRange) -> String {
713    let RunnerRange {
714        package,
715        min_version,
716        max_version_exclusive,
717        ..
718    } = range;
719    let install =
720        format!("install {package} {min_version} or a later version below {max_version_exclusive}");
721    match min_version.split_once('.') {
722        Some((major, rest)) if rest != "0.0" => {
723            format!("{install}; a {package} {major}.x release from {min_version} is in the range")
724        }
725        _ => install,
726    }
727}
728
729/// Maps a schedule error to its public error. A setup watchdog fault names
730/// `--setup-timeout`, because a slow or busy host is the usual cause. A
731/// runner version error names the supported range of `runner`.
732fn schedule_error(
733    error: &ScheduleError,
734    runner: &RunnerRange,
735    setup_timeout: Duration,
736) -> ProgrammaticError {
737    let (code, stderr_tail) = match error {
738        ScheduleError::Integrity(_) => ("FALLOW_MUTATION_COMPANION_INTEGRITY", None),
739        ScheduleError::RunnerVersion(_) => ("FALLOW_MUTATION_RUNNER_UNSUPPORTED", None),
740        ScheduleError::Setup { stderr_tail, .. } => {
741            ("FALLOW_MUTATION_RUNNER_FAILED", stderr_tail.clone())
742        }
743        ScheduleError::RunPath { .. } => ("FALLOW_MUTATION_RUNNER_FAILED", None),
744        ScheduleError::UnknownHit(_) => ("FALLOW_MUTATION_PLAN_MISMATCH", None),
745        ScheduleError::Baseline(_) => ("FALLOW_MUTATION_BASELINE_FAILED", None),
746        ScheduleError::UnmatchedTargets(_) | ScheduleError::TargetsNeedTestFilter => {
747            ("FALLOW_MUTATION_TARGET_UNMATCHED", None)
748        }
749    };
750    let mut help = Vec::new();
751    if matches!(error, ScheduleError::RunnerVersion(_)) {
752        help.push(runner_version_help(runner));
753    }
754    if let ScheduleError::RunPath { help: run_path, .. } = error {
755        help.push(run_path.clone());
756    }
757    if matches!(
758        error,
759        ScheduleError::Setup {
760            timed_out: true,
761            ..
762        }
763    ) {
764        help.push(format!(
765            "the runner setup took longer than {}s; on a slow or busy host, pass --setup-timeout with a longer duration, for example 5m",
766            setup_timeout.as_secs()
767        ));
768    }
769    if let Some(tail) = stderr_tail.filter(|tail| !tail.trim().is_empty()) {
770        help.push(format!("companion stderr:\n{}", tail.trim_end()));
771    }
772    let public = mutation_error(code, error.to_string());
773    if help.is_empty() {
774        public
775    } else {
776        public.with_help(help.join("\n"))
777    }
778}
779
780fn default_concurrency() -> usize {
781    std::thread::available_parallelism()
782        .map_or(1, std::num::NonZeroUsize::get)
783        .div_ceil(2)
784        .max(1)
785}
786
787fn runtime_error(runner: Runner, message: String) -> ProgrammaticError {
788    mutation_error("FALLOW_MUTATION_RUNTIME_NOT_FOUND", message)
789        .with_help(runner.runtime_help())
790        .with_context("mutation.runtime")
791}
792
793fn scheduled(plan: &MutationPlan, disposition: MutantDisposition) -> Vec<ScheduledMutant> {
794    plan.mutants
795        .iter()
796        .filter(|mutant| mutant.disposition == disposition)
797        .map(|mutant| ScheduledMutant {
798            id: mutant.mutant.id.as_str().to_owned(),
799            file: mutant.file.clone(),
800        })
801        .collect()
802}
803
804fn schedule_plan(plan: &MutationPlan) -> SchedulePlan {
805    SchedulePlan {
806        mutants: scheduled(plan, MutantDisposition::Planned),
807        unreached: scheduled(plan, MutantDisposition::NoCoverage),
808        pending: scheduled(plan, MutantDisposition::Pending),
809        known_ids: plan
810            .mutants
811            .iter()
812            .map(|mutant| mutant.mutant.id.as_str().to_owned())
813            .collect::<FxHashSet<_>>(),
814        test_files: plan.test_files.clone(),
815        file_test_files: plan
816            .files
817            .iter()
818            .map(|file| (file.path.clone(), file.static_test_files.clone()))
819            .collect(),
820    }
821}
822
823/// The facts of a started run that the report reads.
824struct Execution {
825    outcome: Option<ScheduleOutcome>,
826    runner: Option<MutationRunnerOutput>,
827    cache: Option<MutationCacheOutput>,
828    resume: Option<MutationResumeOutput>,
829    setup_ms: u64,
830}
831
832/// The journal path as the report shows it: relative to the root, with `/`
833/// separators, when the journal is inside the root.
834fn shown_path(root: &Path, path: &Path) -> String {
835    let relative = path.strip_prefix(root).map(Path::to_path_buf).or_else(|_| {
836        canonical_path(path)
837            .strip_prefix(canonical_path(root))
838            .map(Path::to_path_buf)
839    });
840    relative.map_or_else(
841        |_| path.display().to_string(),
842        |relative| {
843            relative
844                .components()
845                .map(|part| part.as_os_str().to_string_lossy())
846                .collect::<Vec<_>>()
847                .join("/")
848        },
849    )
850}
851
852/// The operator names of the journal fingerprint, sorted and without
853/// duplicates, so the order of `--operators` does not change it.
854fn operator_names(operators: &[fallow_engine::mutation::Operator]) -> Vec<String> {
855    let mut names: Vec<String> = operators
856        .iter()
857        .map(|operator| operator.as_str().to_owned())
858        .collect();
859    names.sort_unstable();
860    names.dedup();
861    names
862}
863
864/// A scope path of the journal fingerprint: relative to `root` when it is
865/// inside the root, without `.` parts, with `/` separators.
866fn scope_path(root: &Path, path: &Path) -> String {
867    let relative = path.strip_prefix(root).unwrap_or(path);
868    relative
869        .components()
870        .filter(|part| !matches!(part, std::path::Component::CurDir))
871        .map(|part| part.as_os_str().to_string_lossy())
872        .collect::<Vec<_>>()
873        .join("/")
874}
875
876/// The scope of the journal fingerprint. The paths of a `paths` scope are
877/// normalized, sorted and without duplicates, so `./src/a` and `src/a` give
878/// one fingerprint.
879fn scope_label(options: &MutationRunOptions, base_ref: Option<&str>, root: &Path) -> String {
880    match &options.scope {
881        MutationRunScope::All => "all".to_owned(),
882        MutationRunScope::Paths(paths) => {
883            let mut paths: Vec<String> = paths.iter().map(|path| scope_path(root, path)).collect();
884            paths.sort_unstable();
885            paths.dedup();
886            format!("paths {}", paths.join(","))
887        }
888        MutationRunScope::Changed { .. } => base_ref.map_or_else(
889            || "changed lines of a diff".to_owned(),
890            |base| format!("changed against {base}"),
891        ),
892    }
893}
894
895fn resume_mismatch(mismatch: &JournalMismatch, journal: &str) -> ProgrammaticError {
896    mutation_error(
897        "FALLOW_MUTATION_RESUME_MISMATCH",
898        format!(
899            "the journal {journal} belongs to a run with other inputs: {}",
900            mismatch.differences.join("; ")
901        ),
902    )
903    .with_help("run without --resume to start a new run; that run replaces the journal")
904    .with_context("mutation.resume")
905}
906
907/// The resume facts of a `--resume` run in which no mutant needs a test run.
908/// Such a run reads no journal.
909fn unread_journal(options: &MutationRunOptions, planned: &Planned) -> Option<MutationResumeOutput> {
910    options.resume.then(|| MutationResumeOutput {
911        journal: shown_path(
912            planned.resolved.root(),
913            &Journal::path(&planned.cache_dir.join("mutation")),
914        ),
915        reused: 0,
916        rejected: 0,
917        note: Some("the run read no journal, because no mutant needs a test run".to_owned()),
918    })
919}
920
921/// The result cache (`None` with `--no-cache`) and the outcome journal of a
922/// run. The journal uses the key of the result cache.
923fn open_stores(
924    options: &MutationRunOptions,
925    planned: &Planned,
926    mutation_cache: &Path,
927    runtime: &str,
928    run_dir: &Path,
929) -> ProgrammaticResult<(Option<Arc<ResultCache>>, RunJournal)> {
930    let root = planned.resolved.root();
931    let name = planned.runner.name();
932    let files = key_files(&planned.plan, planned.runner_config.as_deref());
933    let result_cache = open_result_cache(
934        planned.resolved.no_cache,
935        mutation_cache,
936        root,
937        name,
938        files.clone(),
939    );
940    let keys = result_cache
941        .clone()
942        .unwrap_or_else(|| Arc::new(ResultCache::keys_only(mutation_cache, root, name, files)));
943    let header = JournalHeader {
944        journal_format: JOURNAL_FORMAT,
945        fallow_version: env!("CARGO_PKG_VERSION").to_owned(),
946        runner: name.to_owned(),
947        runtime: runtime.to_owned(),
948        run_dir: run_dir
949            .file_name()
950            .map(|hash| hash.to_string_lossy().into_owned())
951            .unwrap_or_default(),
952        runner_config: planned.runner_config.clone(),
953        scope: scope_label(options, planned.base_ref.as_deref(), root),
954        operators: planned.operators.clone(),
955        allow_side_effects: options.allow_side_effects,
956        kill_matrix: options.kill_matrix,
957        kill_matrix_targets: sorted_targets(&options.kill_matrix_targets),
958    };
959    let run_journal = start_journal(options, planned, mutation_cache, &header, keys)?;
960    Ok((result_cache, run_journal))
961}
962
963/// The outcome journal of a started run.
964struct RunJournal {
965    journal: Arc<Journal>,
966    /// The journal path of the report.
967    shown: String,
968    /// Why a `--resume` run started from the beginning.
969    note: Option<String>,
970}
971
972/// Starts the outcome journal of a run. The journal is written with and
973/// without `--no-cache`. `keys` gives the result cache key of each mutant.
974fn start_journal(
975    options: &MutationRunOptions,
976    planned: &Planned,
977    mutation_cache: &Path,
978    header: &JournalHeader,
979    keys: Arc<ResultCache>,
980) -> ProgrammaticResult<RunJournal> {
981    let shown = shown_path(planned.resolved.root(), &Journal::path(mutation_cache));
982    let opened = Journal::open(mutation_cache, header, keys, options.resume)
983        .map_err(|mismatch| resume_mismatch(&mismatch, &shown))?;
984    Ok(RunJournal {
985        journal: Arc::new(opened.journal),
986        shown,
987        note: opened.note,
988    })
989}
990
991/// The resume facts of a `--resume` run, and the issue of a journal that
992/// was not written.
993fn settle_journal(
994    options: &MutationRunOptions,
995    run_journal: RunJournal,
996    outcome: &mut ScheduleOutcome,
997) -> Option<MutationResumeOutput> {
998    if let Some(message) = run_journal.journal.write_error() {
999        outcome.issues.push(ScheduleIssue {
1000            code: "journal-write-failed",
1001            message: format!(
1002                "the outcome journal was not written, so an interrupted run cannot resume each result: {message}"
1003            ),
1004            mutant_id: None,
1005            stderr_tail: None,
1006        });
1007    }
1008    options.resume.then(|| MutationResumeOutput {
1009        journal: run_journal.shown,
1010        reused: outcome
1011            .results
1012            .values()
1013            .filter(|result| result.resumed)
1014            .count(),
1015        rejected: run_journal.journal.rejected(),
1016        note: run_journal.note,
1017    })
1018}
1019
1020/// The result cache of a run. `None` with `--no-cache`.
1021fn open_result_cache(
1022    no_cache: bool,
1023    mutation_cache: &Path,
1024    root: &Path,
1025    runner: &str,
1026    files: KeyFiles,
1027) -> Option<Arc<ResultCache>> {
1028    (!no_cache).then(|| Arc::new(ResultCache::open(mutation_cache, root, runner, files)))
1029}
1030
1031/// The key files of the result cache. A selected runner config file is a
1032/// support file of the key, so a result of one config content is never the
1033/// result of another.
1034fn key_files(plan: &MutationPlan, runner_config: Option<&str>) -> KeyFiles {
1035    let mut files = KeyFiles::from_plan(plan);
1036    if let Some(config) = runner_config
1037        && !files.support_files.iter().any(|file| file == config)
1038    {
1039        files.support_files.push(config.to_owned());
1040    }
1041    files
1042}
1043
1044/// Stores the new results of `outcome` in `cache` and writes the cache file.
1045/// A failed write adds a `cache-write-failed` issue and keeps the run result.
1046fn store_results(cache: &ResultCache, outcome: &mut ScheduleOutcome) -> MutationCacheOutput {
1047    let counts = cache.record(outcome);
1048    if let Err(message) = cache.save() {
1049        outcome.issues.push(ScheduleIssue {
1050            code: "cache-write-failed",
1051            message: format!("the mutation result cache was not saved: {message}"),
1052            mutant_id: None,
1053            stderr_tail: None,
1054        });
1055    }
1056    MutationCacheOutput {
1057        hits: counts.hits,
1058        stored: counts.stored,
1059        not_keyed: NOT_KEYED.iter().map(|&item| item.to_owned()).collect(),
1060    }
1061}
1062
1063/// The `init` options of the runner. The `node:test` runner gets the module
1064/// loading flags of the `node --test` command in the project scripts. The
1065/// `node:test` and `bun:test` runners get the static test files, because
1066/// their glob discovery does not go into dot directories. Vitest has its own
1067/// include configuration.
1068fn init_options(runner: Runner, root: &Path, static_test_files: &[String]) -> InitOptions {
1069    let node_args = match runner {
1070        Runner::NodeTest => node_test_args(root),
1071        Runner::Vitest | Runner::BunTest => Vec::new(),
1072    };
1073    let extra_test_files = match runner {
1074        Runner::NodeTest | Runner::BunTest => static_test_files.to_vec(),
1075        Runner::Vitest => Vec::new(),
1076    };
1077    InitOptions {
1078        extra_test_files,
1079        node_args,
1080        ..InitOptions::default()
1081    }
1082}
1083
1084/// The runner facts of the report. `None` when no companion started.
1085fn runner_output(
1086    outcome: &ScheduleOutcome,
1087    name: &str,
1088    manifest: &Manifest,
1089    runtime: &JsRuntime,
1090) -> Option<MutationRunnerOutput> {
1091    outcome.ready.as_ref().map(|ready| MutationRunnerOutput {
1092        name: name.to_owned(),
1093        version: ready.runner_version.clone(),
1094        protocol_version: manifest.wire_protocol_version,
1095        runtime: MutationRuntimeOutput {
1096            name: runtime.kind.name().to_owned(),
1097            version: runtime.version.clone(),
1098        },
1099        concurrency: outcome.workers,
1100        notes: ready
1101            .notes
1102            .iter()
1103            .filter(|note| manifest.ready_notes.contains(note))
1104            .cloned()
1105            .collect(),
1106    })
1107}
1108
1109/// The public error of a schedule that stopped the run.
1110fn execute(
1111    options: &MutationRunOptions,
1112    planned: &Planned,
1113    deadline: Option<Instant>,
1114    progress: MutationProgressSink<'_>,
1115) -> ProgrammaticResult<Execution> {
1116    let plan = &planned.plan;
1117    let schedule = schedule_plan(plan);
1118    // With no planned mutant the dry run still runs the static test files,
1119    // because a hit on a statically unreached mutant is a static map miss.
1120    if schedule.mutants.is_empty()
1121        && (schedule.unreached.is_empty() || schedule.test_files.is_empty())
1122    {
1123        return Ok(Execution {
1124            outcome: None,
1125            runner: None,
1126            cache: None,
1127            resume: unread_journal(options, planned),
1128            setup_ms: 0,
1129        });
1130    }
1131    progress(MutationProgress::Setup {
1132        mutants: schedule.mutants.len(),
1133    });
1134    let setup_started = Instant::now();
1135    let manifest = manifest()
1136        .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
1137    let runner = planned.runner;
1138    let name = runner.name();
1139    let range = manifest.runner(name).ok_or_else(|| {
1140        mutation_error(
1141            "FALLOW_MUTATION_PROTOCOL_INVALID",
1142            format!("the protocol manifest has no `{name}` runner"),
1143        )
1144    })?;
1145    let runtime = discover_runtime(options.runtime.as_deref(), runner.runtimes())
1146        .map_err(|message| runtime_error(runner, message))?;
1147    let cache_error =
1148        |message: String| mutation_error("FALLOW_MUTATION_CACHE_WRITE_FAILED", message);
1149    ignore_cache_dir(&planned.cache_dir).map_err(|error| cache_error(error.to_string()))?;
1150    let mutation_cache = planned.cache_dir.join("mutation");
1151    let companion = install(&mutation_cache, COMPANION_FILES)
1152        .map_err(|message| mutation_error("FALLOW_MUTATION_COMPANION_INTEGRITY", message))?;
1153    let files: Vec<RunFile<'_>> = plan
1154        .files
1155        .iter()
1156        .map(|file| RunFile {
1157            path: &file.path,
1158            code: &file.instrumented_code,
1159        })
1160        .collect();
1161    let run_dir = write_run_dir(&mutation_cache, &files, Some(&companion)).map_err(cache_error)?;
1162    let root = planned.resolved.root().to_path_buf();
1163    let runtime_label = format!("{} {}", runtime.kind.name(), runtime.version);
1164    let (result_cache, run_journal) = open_stores(
1165        options,
1166        planned,
1167        &mutation_cache,
1168        &runtime_label,
1169        &run_dir.dir,
1170    )?;
1171    let config = ScheduleConfig {
1172        init: InitRequest {
1173            root: root.to_string_lossy().into_owned(),
1174            runner: name.to_owned(),
1175            config_path: planned.runner_config.clone(),
1176            run_dir: run_dir.dir.to_string_lossy().into_owned(),
1177            path_map: run_dir.path_map.clone(),
1178            options: init_options(runner, &root, &plan.test_files),
1179        },
1180        runner: range.clone(),
1181        kill_matrix: options.kill_matrix,
1182        targets: options.kill_matrix_targets.clone(),
1183        concurrency: options.concurrency.unwrap_or_else(default_concurrency),
1184        runner_timeout: options.runner_timeout.unwrap_or(DEFAULT_RUNNER_TIMEOUT),
1185        deadline,
1186        cache: result_cache
1187            .clone()
1188            .map(|cache| cache as Arc<dyn ResultLookup>),
1189        journal: Some(Arc::clone(&run_journal.journal) as Arc<dyn OutcomeJournal>),
1190    };
1191    let spawner = ProcessSpawner {
1192        runtime: runtime.path.clone(),
1193        companion,
1194        root,
1195        wire_version: manifest.wire_protocol_version,
1196        session_token_env: manifest.session_token_env.clone(),
1197    };
1198    let setup_ms = millis(setup_started.elapsed());
1199    let mut outcome = run_schedule_with_progress(&spawner, &schedule, &config, progress)
1200        .map_err(|error| schedule_error(&error, &config.runner, config.runner_timeout))?;
1201    let runner = runner_output(&outcome, name, manifest, &runtime);
1202    let cache = match (&result_cache, outcome.ready.is_some()) {
1203        (Some(result_cache), true) => Some(store_results(result_cache, &mut outcome)),
1204        _ => None,
1205    };
1206    let resume = settle_journal(options, run_journal, &mut outcome);
1207    Ok(Execution {
1208        outcome: Some(outcome),
1209        runner,
1210        cache,
1211        resume,
1212        setup_ms,
1213    })
1214}
1215
1216/// The errors of a finished run: the scheduler issues and the worktree facts.
1217fn run_issues(
1218    outcome: Option<&ScheduleOutcome>,
1219    changed_paths: &[String],
1220    check_error: Option<String>,
1221) -> Vec<fallow_output::MutationRunIssue> {
1222    let mut errors = issues(outcome);
1223    if !changed_paths.is_empty() {
1224        errors.push(fallow_output::MutationRunIssue {
1225            code: "worktree-changed".to_owned(),
1226            message: format!(
1227                "the run changed {} worktree {}; a mutant or a test wrote to the project",
1228                changed_paths.len(),
1229                path_noun(changed_paths.len())
1230            ),
1231            mutant_id: None,
1232            stderr_tail: None,
1233        });
1234    }
1235    if let Some(message) = check_error {
1236        errors.push(fallow_output::MutationRunIssue {
1237            code: "worktree-check-failed".to_owned(),
1238            message: format!(
1239                "the end-of-run worktree check failed, so stray writes are unknown: {message}"
1240            ),
1241            mutant_id: None,
1242            stderr_tail: None,
1243        });
1244    }
1245    errors
1246}
1247
1248/// The wall time of each phase. A run that started no companion has only
1249/// the plan and the type check times.
1250fn run_timings(
1251    outcome: Option<&ScheduleOutcome>,
1252    setup_ms: u64,
1253    plan_ms: u64,
1254    typecheck_ms: u64,
1255) -> MutationTimings {
1256    outcome.map_or_else(
1257        || MutationTimings {
1258            plan_ms,
1259            typecheck_ms,
1260            ..MutationTimings::default()
1261        },
1262        |outcome| MutationTimings {
1263            plan_ms,
1264            setup_ms: setup_ms + millis(outcome.timings.setup),
1265            dry_run_ms: millis(outcome.timings.dry_run),
1266            mutants_ms: millis(outcome.timings.mutants),
1267            retry_ms: millis(outcome.timings.retry),
1268            typecheck_ms,
1269        },
1270    )
1271}
1272
1273/// Refuses a run with the survivor type check before the tests start when no
1274/// trusted type-aware companion exists.
1275fn guard_typecheck_companion(enabled: bool, root: &Path) -> ProgrammaticResult<()> {
1276    if !enabled {
1277        return Ok(());
1278    }
1279    crate::type_aware::check_typecheck_companion(root).map_err(|message| {
1280        mutation_error("FALLOW_MUTATION_TYPECHECK_UNAVAILABLE", message)
1281            .with_help("install the fallow-type-aware companion, or run without --typecheck")
1282            .with_context("mutation.typecheck")
1283    })
1284}
1285
1286/// Plans the mutants, runs the project tests against each planned mutant,
1287/// and reports the result.
1288///
1289/// The run refuses a dirty git worktree unless
1290/// [`MutationRunOptions::allow_dirty`] is set. After the run it compares the
1291/// worktree with the start state and reports each changed path.
1292///
1293/// # Errors
1294///
1295/// Returns an error for invalid options, a dirty worktree, a failed plan, a
1296/// missing runtime, a companion that does not start or load the runner, a
1297/// companion file that changed after install, or a test suite that fails
1298/// with no active mutant outside each test file.
1299pub fn run_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationReport> {
1300    run_mutation_with_progress(options, &|_| {})
1301}
1302
1303/// The worktree check of the report: the dirty paths at the start and the
1304/// paths that the run changed.
1305fn worktree_check(
1306    start: Option<&WorktreeSnapshot>,
1307    allow_dirty: bool,
1308    changed_paths: Vec<String>,
1309) -> MutationWorktreeCheck {
1310    MutationWorktreeCheck {
1311        checked: start.is_some(),
1312        allow_dirty,
1313        dirty_at_start: start.map(WorktreeSnapshot::dirty_paths).unwrap_or_default(),
1314        changed_paths,
1315    }
1316}
1317
1318/// [`run_mutation`] that sends a [`MutationProgress`] event at the start of
1319/// each run phase and after each finished mutant.
1320///
1321/// The events arrive on the calling thread and on the scheduler worker
1322/// threads. A sink must return quickly, because a worker waits for it.
1323///
1324/// # Errors
1325///
1326/// Returns the same errors as [`run_mutation`].
1327pub fn run_mutation_with_progress(
1328    options: &MutationRunOptions,
1329    progress: MutationProgressSink<'_>,
1330) -> ProgrammaticResult<MutationReport> {
1331    let started = Instant::now();
1332    let deadline = options.time_budget.map(|budget| started + budget);
1333    let mut start_snapshot = None;
1334    let planned = plan_for(options, |root, cache_dir| {
1335        guard_cache_dir(root, cache_dir)?;
1336        start_snapshot = take_worktree_snapshot(root, cache_dir, &options.output_paths, None)?;
1337        if options.test_changes_only && !options.allow_dirty && start_snapshot.is_some() {
1338            return Ok(());
1339        }
1340        guard_worktree(options.allow_dirty, start_snapshot.as_ref())
1341    })?;
1342    guard_planned(options, &planned, start_snapshot.as_ref())?;
1343    let normalized = with_normalized_targets(options, planned.resolved.root())?;
1344    let options = normalized.as_ref().unwrap_or(options);
1345    let plan_ms = millis(started.elapsed());
1346    let execution = execute(options, &planned, deadline, progress);
1347    progress(MutationProgress::Finalize);
1348    let worktree_end = settle_worktree(start_snapshot.as_ref(), |start| {
1349        take_worktree_snapshot(
1350            planned.resolved.root(),
1351            &planned.cache_dir,
1352            &options.output_paths,
1353            Some(start),
1354        )
1355    });
1356    let execution = execution.map_err(|error| with_worktree_facts(error, &worktree_end))?;
1357    let WorktreeEnd {
1358        changed_paths,
1359        check_error,
1360    } = worktree_end;
1361    let plan = &planned.plan;
1362    let outcome = execution.outcome.as_ref();
1363    let mut results = mutant_results(plan, outcome);
1364    let typecheck = typecheck_survivors(
1365        options.typecheck,
1366        planned.resolved.root(),
1367        plan,
1368        &mut results,
1369    );
1370    let typecheck_ms = millis(typecheck.elapsed);
1371    let baseline = baseline_failures(outcome);
1372    let completion = completion(&CompletionFacts {
1373        plan,
1374        results: &results,
1375        baseline_failures: &baseline,
1376        worktree_changed: !changed_paths.is_empty(),
1377        worktree_unchecked: check_error.is_some(),
1378        unretried: outcome.is_some_and(|outcome| !outcome.unretried.is_empty()),
1379        unloaded_paths: outcome.map_or(&[], |outcome| outcome.unloaded_paths.as_slice()),
1380        undiscovered_test_files: outcome
1381            .map_or(&[], |outcome| outcome.undiscovered_test_files.as_slice()),
1382        typecheck_failed: typecheck.issue.is_some(),
1383        promoted: outcome.map_or(&[], |outcome| outcome.promoted.as_slice()),
1384    });
1385    let mut errors = run_issues(outcome, &changed_paths, check_error);
1386    errors.extend(typecheck.issue);
1387    let timings = run_timings(outcome, execution.setup_ms, plan_ms, typecheck_ms);
1388    Ok(MutationReport {
1389        schema_version: MutationSchemaVersion::V2,
1390        version: tool_version(),
1391        elapsed_ms: ElapsedMs(millis(started.elapsed())),
1392        kill_matrix: crate::mutation::kill_matrix::build(
1393            &kill_matrix_mode(options, outcome),
1394            &results,
1395            &baseline,
1396            &completion,
1397            &plan.mutants,
1398            outcome.map(|outcome| &outcome.test_files),
1399        ),
1400        completion,
1401        scope: scope_output(options, planned.base_ref.clone()),
1402        runner: execution.runner,
1403        cache: execution.cache,
1404        resume: execution.resume,
1405        summary: summary(&results),
1406        functions: function_results(plan, &results),
1407        mutants: results,
1408        no_test_files: plan.no_test_files,
1409        baseline_failures: baseline,
1410        skipped_files: skipped_files(plan),
1411        unmatched_paths: plan.unmatched_paths.clone(),
1412        unloaded_paths: outcome
1413            .map(|outcome| outcome.unloaded_paths.clone())
1414            .unwrap_or_default(),
1415        worktree: worktree_check(start_snapshot.as_ref(), options.allow_dirty, changed_paths),
1416        errors,
1417        timings,
1418        files: plan_files(plan),
1419        verdicts: None,
1420        typecheck: typecheck.output,
1421        recheck: None,
1422        compare: None,
1423    })
1424}
1425
1426#[cfg(test)]
1427mod tests {
1428    use super::*;
1429
1430    fn vitest_range() -> &'static RunnerRange {
1431        manifest()
1432            .expect("manifest")
1433            .runner("vitest")
1434            .expect("vitest range")
1435    }
1436
1437    #[test]
1438    fn a_runner_version_error_names_the_supported_range_as_the_install_step() {
1439        let error = schedule_error(
1440            &ScheduleError::RunnerVersion(
1441                "vitest 4.0.18 is not supported; the supported range is >=4.1.0 <6.0.0".to_owned(),
1442            ),
1443            vitest_range(),
1444            Duration::from_secs(120),
1445        );
1446        assert_eq!(
1447            error.code.as_deref(),
1448            Some("FALLOW_MUTATION_RUNNER_UNSUPPORTED")
1449        );
1450        assert_eq!(
1451            error.help.as_deref(),
1452            Some(
1453                "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"
1454            )
1455        );
1456
1457        let help: Vec<String> = manifest()
1458            .expect("manifest")
1459            .runners
1460            .iter()
1461            .map(runner_version_help)
1462            .collect();
1463        assert_eq!(
1464            help,
1465            [
1466                "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",
1467                "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",
1468                "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",
1469            ]
1470        );
1471
1472        let major_start = RunnerRange {
1473            name: "vitest".to_owned(),
1474            package: "vitest".to_owned(),
1475            min_version: "5.0.0".to_owned(),
1476            max_version_exclusive: "6.0.0".to_owned(),
1477        };
1478        assert_eq!(
1479            runner_version_help(&major_start),
1480            "install vitest 5.0.0 or a later version below 6.0.0"
1481        );
1482    }
1483
1484    #[test]
1485    fn a_setup_watchdog_error_names_the_setup_timeout_flag() {
1486        let error = schedule_error(
1487            &ScheduleError::Setup {
1488                message: "the mutation companion dry_run failed".to_owned(),
1489                stderr_tail: Some("vitest started\n".to_owned()),
1490                timed_out: true,
1491            },
1492            vitest_range(),
1493            Duration::from_secs(120),
1494        );
1495        let help = error.help.as_deref().unwrap_or_default();
1496        assert!(help.contains("longer than 120s"), "{help}");
1497        assert!(help.contains("--setup-timeout"), "{help}");
1498        assert!(help.contains("companion stderr:\nvitest started"), "{help}");
1499
1500        let other = schedule_error(
1501            &ScheduleError::Setup {
1502                message: "the mutation companion init failed".to_owned(),
1503                stderr_tail: None,
1504                timed_out: false,
1505            },
1506            vitest_range(),
1507            Duration::from_secs(120),
1508        );
1509        assert_eq!(other.help, None);
1510    }
1511
1512    #[test]
1513    fn a_failed_self_check_is_a_runner_failure_with_its_own_help() {
1514        let error = schedule_error(
1515            &ScheduleError::RunPath {
1516                message: "vitest 5.0.4 executes no tests in a mutant run".to_owned(),
1517                help: "report this with the runner name and version (vitest 5.0.4)".to_owned(),
1518            },
1519            vitest_range(),
1520            Duration::from_secs(120),
1521        );
1522        assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_RUNNER_FAILED"));
1523        assert_eq!(error.exit_code, 2);
1524        assert_eq!(
1525            error.message,
1526            "vitest 5.0.4 executes no tests in a mutant run"
1527        );
1528        assert_eq!(
1529            error.help.as_deref(),
1530            Some("report this with the runner name and version (vitest 5.0.4)")
1531        );
1532    }
1533
1534    #[test]
1535    fn a_failed_end_check_keeps_the_execute_error_and_reports_the_check_error() {
1536        let start = WorktreeSnapshot::default();
1537        let end = settle_worktree(Some(&start), |_| {
1538            Err(mutation_error(
1539                "FALLOW_MUTATION_WORKTREE_CHECK_FAILED",
1540                "git status failed",
1541            ))
1542        });
1543        assert!(end.changed_paths.is_empty());
1544        assert_eq!(end.check_error.as_deref(), Some("git status failed"));
1545
1546        let error = with_worktree_facts(
1547            mutation_error(
1548                "FALLOW_MUTATION_SETUP_FAILED",
1549                "the companion did not start",
1550            ),
1551            &end,
1552        );
1553        assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_SETUP_FAILED"));
1554        assert!(
1555            error.message.starts_with("the companion did not start"),
1556            "{}",
1557            error.message
1558        );
1559        assert!(
1560            error.message.contains("git status failed"),
1561            "{}",
1562            error.message
1563        );
1564    }
1565
1566    #[test]
1567    fn every_config_operator_name_maps_to_an_engine_operator() {
1568        for operator in fallow_engine::mutation::Operator::ALL {
1569            let name: fallow_config::MutationOperatorName =
1570                serde_json::from_value(serde_json::json!(operator.as_str()))
1571                    .expect("a config operator name");
1572            assert_eq!(
1573                fallow_engine::mutation::Operator::from_name(name.as_str()),
1574                Some(operator)
1575            );
1576        }
1577    }
1578
1579    #[test]
1580    fn no_cache_opens_no_result_cache() {
1581        let dir = tempfile::tempdir().expect("dir");
1582        let plan = MutationPlan {
1583            files: Vec::new(),
1584            mutants: Vec::new(),
1585            test_files: Vec::new(),
1586            reach_files: Vec::new(),
1587            test_file_reach: std::collections::BTreeMap::new(),
1588            support_files: Vec::new(),
1589            counts: fallow_engine::mutation::MutationPlanCounts::default(),
1590            no_test_files: false,
1591            framework_config_checked: false,
1592            skipped_files: Vec::new(),
1593            unmatched_paths: Vec::new(),
1594        };
1595        assert!(
1596            open_result_cache(
1597                true,
1598                dir.path(),
1599                dir.path(),
1600                "vitest",
1601                KeyFiles::from_plan(&plan)
1602            )
1603            .is_none()
1604        );
1605        assert!(
1606            open_result_cache(
1607                false,
1608                dir.path(),
1609                dir.path(),
1610                "vitest",
1611                KeyFiles::from_plan(&plan)
1612            )
1613            .is_some()
1614        );
1615    }
1616
1617    fn empty_plan() -> MutationPlan {
1618        MutationPlan {
1619            files: Vec::new(),
1620            mutants: Vec::new(),
1621            test_files: Vec::new(),
1622            reach_files: Vec::new(),
1623            test_file_reach: std::collections::BTreeMap::new(),
1624            support_files: Vec::new(),
1625            counts: fallow_engine::mutation::MutationPlanCounts::default(),
1626            no_test_files: false,
1627            framework_config_checked: false,
1628            skipped_files: Vec::new(),
1629            unmatched_paths: Vec::new(),
1630        }
1631    }
1632
1633    #[test]
1634    fn a_cache_dir_at_or_above_the_root_is_refused() {
1635        let dir = tempfile::tempdir().expect("dir");
1636        let root = dir.path().join("project");
1637        std::fs::create_dir_all(root.join("src")).expect("dir");
1638        for cache in [root.clone(), root.join("."), dir.path().to_path_buf()] {
1639            let error = guard_cache_dir(&root, &cache).expect_err("refused");
1640            assert_eq!(
1641                error.code.as_deref(),
1642                Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1643            );
1644            assert_eq!(error.exit_code, 2);
1645            assert_eq!(error.context.as_deref(), Some("cache.dir"));
1646        }
1647        assert!(guard_cache_dir(&root, &root.join(".fallow")).is_ok());
1648        assert!(guard_cache_dir(&root, &root.join("src")).is_ok());
1649    }
1650
1651    #[test]
1652    fn a_cache_dir_that_holds_a_planned_file_is_refused() {
1653        let dir = tempfile::tempdir().expect("dir");
1654        let root = dir.path();
1655        let mut plan = empty_plan();
1656        plan.files.push(fallow_engine::mutation::PlannedFile {
1657            path: "src/a.ts".to_owned(),
1658            source_sha256: String::new(),
1659            instrumented_code: String::new(),
1660            static_test_files: Vec::new(),
1661        });
1662        plan.test_files.push("test/a.test.ts".to_owned());
1663
1664        let error = guard_cache_holds_no_planned_file(root, &root.join("src"), &plan)
1665            .expect_err("the cache holds a planned source file");
1666        assert_eq!(
1667            error.code.as_deref(),
1668            Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1669        );
1670        assert!(error.message.contains("src/a.ts"), "{}", error.message);
1671        let error = guard_cache_holds_no_planned_file(root, &root.join("test"), &plan)
1672            .expect_err("the cache holds a planned test file");
1673        assert!(
1674            error.message.contains("test/a.test.ts"),
1675            "{}",
1676            error.message
1677        );
1678        assert!(guard_cache_holds_no_planned_file(root, &root.join(".fallow"), &plan).is_ok());
1679    }
1680
1681    #[test]
1682    fn kill_matrix_targets_take_the_form_of_runner_test_ids() {
1683        let root = Path::new("/project");
1684        assert_eq!(normalize_target(root, "./test/a.test.ts"), "test/a.test.ts");
1685        assert_eq!(
1686            normalize_target(root, "test\\a.test.ts::adds > two"),
1687            "test/a.test.ts::adds > two"
1688        );
1689        if cfg!(unix) {
1690            assert_eq!(
1691                normalize_target(root, "/project/test/a.test.ts::a::b"),
1692                "test/a.test.ts::a::b"
1693            );
1694            assert_eq!(
1695                normalize_target(root, "/other/a.test.ts"),
1696                "/other/a.test.ts"
1697            );
1698        }
1699    }
1700
1701    #[test]
1702    fn a_target_that_normalizes_to_no_file_is_refused_and_order_does_not_matter() {
1703        let root = Path::new("/project");
1704        for raw in ["./", "././", "::name"] {
1705            let options = MutationRunOptions {
1706                kill_matrix_targets: vec![raw.to_owned()],
1707                ..MutationRunOptions::default()
1708            };
1709            let error = with_normalized_targets(&options, root).expect_err(raw);
1710            assert!(error.message.contains("names no test file"), "{raw}");
1711        }
1712        let options = MutationRunOptions {
1713            kill_matrix_targets: vec!["./b.test.ts".to_owned(), "b.test.ts".to_owned()],
1714            ..MutationRunOptions::default()
1715        };
1716        let normalized = with_normalized_targets(&options, root)
1717            .expect("valid")
1718            .expect("target mode");
1719        assert_eq!(normalized.kill_matrix_targets, ["b.test.ts"]);
1720        assert_eq!(
1721            sorted_targets(&["b".to_owned(), "a".to_owned()]),
1722            sorted_targets(&["a".to_owned(), "b".to_owned()])
1723        );
1724    }
1725
1726    #[test]
1727    fn the_full_and_the_target_kill_matrix_are_exclusive() {
1728        let both = MutationRunOptions {
1729            kill_matrix: true,
1730            kill_matrix_targets: vec!["test/a.test.ts".to_owned()],
1731            ..MutationRunOptions::default()
1732        };
1733        assert!(validate(&both).is_err());
1734        let blank = MutationRunOptions {
1735            kill_matrix_targets: vec![" ".to_owned()],
1736            ..MutationRunOptions::default()
1737        };
1738        assert!(validate(&blank).is_err());
1739    }
1740
1741    #[test]
1742    fn no_start_snapshot_needs_no_end_check() {
1743        let end = settle_worktree(None, |_| panic!("no end check without a start snapshot"));
1744        assert!(end.changed_paths.is_empty());
1745        assert!(end.check_error.is_none());
1746    }
1747
1748    #[test]
1749    fn the_glob_runners_get_the_static_test_files_and_vitest_does_not() {
1750        let dir = tempfile::tempdir().expect("dir");
1751        let files = vec![".github/tests/math.test.mjs".to_owned()];
1752        for runner in [Runner::NodeTest, Runner::BunTest] {
1753            let options = init_options(runner, dir.path(), &files);
1754            assert_eq!(options.extra_test_files, files, "{runner:?}");
1755            assert!(options.test_files.is_empty(), "{runner:?}");
1756        }
1757        let vitest = init_options(Runner::Vitest, dir.path(), &files);
1758        assert!(vitest.extra_test_files.is_empty());
1759    }
1760
1761    #[test]
1762    fn equal_scopes_and_operators_give_one_fingerprint() {
1763        let root = Path::new("/project");
1764        let paths = |paths: &[&str]| MutationRunOptions {
1765            scope: MutationRunScope::Paths(paths.iter().map(PathBuf::from).collect()),
1766            ..MutationRunOptions::default()
1767        };
1768        let label = scope_label(&paths(&["src/a", "lib"]), None, root);
1769        for same in [
1770            paths(&["./src/a", "lib"]),
1771            paths(&["lib/", "src/a"]),
1772            paths(&["/project/src/a", "lib", "./lib"]),
1773        ] {
1774            assert_eq!(scope_label(&same, None, root), label, "{:?}", same.scope);
1775        }
1776        assert_ne!(scope_label(&paths(&["src/b"]), None, root), label);
1777
1778        use fallow_engine::mutation::Operator;
1779        let names = operator_names(&[
1780            Operator::RelationalOperator,
1781            Operator::ArithmeticOperator,
1782            Operator::RelationalOperator,
1783        ]);
1784        assert_eq!(
1785            names,
1786            operator_names(&[Operator::ArithmeticOperator, Operator::RelationalOperator,])
1787        );
1788    }
1789}