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