# Configuration

Mootant works without a configuration: it applies the `recommended` preset and
finds your test runner itself. **Add a configuration file to change the
mutators, set the paths to mutate or tune `mootant run`.**

- [Configuration file](#configuration-file): Where Mootant looks for it and which formats it reads.
- [Presets](#presets): Ready sets of mutators and settings.
- [Mutators](#mutators): Turn mutators on and off and set their options.
- [Settings](#settings): Settings that all mutators share.
- [Plugins](https://mootant.org/advanced/plugins.md): Mutators and presets from other packages.
- [Run settings](#run-settings): Defaults of `mootant run`.

## Configuration file

Create `mootant.config.ts` in the root of your project:

```ts
import { defineConfig } from 'mootant'

export default defineConfig({
  mutators: {
    'string-literal': 'off',
  },
  run: {
    paths: ['src'],
    threshold: 80,
  },
})
```

`defineConfig` only adds types: it returns the object as it is.

Mootant looks for a configuration in the current directory, then in each
directory above it, and uses the first one it finds. In each directory, it
checks in this order:

1. The `mootant` key of `package.json`
2. `.mootantrc` and `.mootantrc.json`, written in JSON
3. `mootant.config.js`, `.mjs`, `.cjs`, `.ts`, `.mts` and `.cts`

To use another file, pass its path:

```sh
npx mootant run --config mootant.ci.config.ts
```

A JSON configuration takes the same options, except [plugins](https://mootant.org/advanced/plugins.md)
and test runner adapters, which have to be imported:

```json
{
  "extends": ["strict"],
  "run": {
    "paths": ["src"]
  }
}
```

TypeScript files need Node.js 22.18 or later, which strips types itself. On
older versions, install the [`jiti`](https://github.com/unjs/jiti) package. In a
package without `"type": "module"`, install jiti there too or name the file
`mootant.config.mts`.

### Project root

The directory of the configuration file is the root of the project. Reported
paths and mutant ids are relative to it, so they stay the same wherever in the
project you run Mootant. Paths in the configuration are relative to the root,
and paths on the command line to the current directory. Without a configuration
file, the current directory is the root. Files that tests read outside the root
count for the [cache](#cache) too.

## Presets

A preset is a ready set of mutators and settings. `extends` lists the presets to
apply, in order, and a later preset overrides an earlier one:

```ts
export default defineConfig({
  extends: ['strict'],
})
```

| Preset | Mutants of the [sample shop](https://mootant.org/reports/html/demo#/) | Command |
| --- | --- | --- |
| `recommended` | 100 | `mootant list src` |
| `strict` | 142 | `mootant list src --preset strict` |

|                                     | `recommended`, the default | `strict`                |
| ----------------------------------- | -------------------------- | ----------------------- |
| Built-in mutators                   | All 20                     | All 20                  |
| [Mutator options](#mutator-options) | Defaults                   | All but `jsxAttributes` |
| Mutants that may cause timeouts     | Left out                   | Added                   |
| Coarse mutants                      | Dropped                    | Kept                    |

`--preset` replaces `extends` for one run, while the `mutators` and `settings`
of the configuration still apply:

```sh
npx mootant run src --preset strict
```

## Mutators

`mutators` turns mutators on and off and sets their options, over the presets.
[Mutators](https://mootant.org/mutators.md) lists every mutator with the changes it makes. The id of a
mutator is the name that reports show next to each mutant:

```ts
export default defineConfig({
  mutators: {
    'string-literal': 'off',
    'method-call': ['on', { anyReceiver: true }],
  },
})
```

- `'off'`: the mutator does not run
- `'on'`: the mutator runs with its default options
- `['on', options]`: the mutator runs with these options over its defaults

A setting replaces the one that a preset gives, so its options are merged over
the defaults of the mutator, not over the options of the preset. With `strict`,
`'method-call': 'on'` turns `anyReceiver` back off.

### Mutator options

The options are `false` by default, and `strict` turns all of them on but
[`jsxAttributes`](https://mootant.org/mutators/string-literal.md#jsxattributes), which can change what
some code does with no mutant on. `nullishSwap` is `'distinguishing'` by
default, and `strict` sets it to `'always'`.

| Mutator                                                | Option                 | What it does                                                                                                                                                                                         |
| ------------------------------------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`assignment-operator`](https://mootant.org/mutators/assignment-operator.md) | `nullishSwap`          | With `'always'`, also swaps `??=` and `\|\|=` for a number with the default `0`, such as `count ??= 0`, and for a left side of unknown type, unless the default is an object, an array or a function |
| [`logical-operator`](https://mootant.org/mutators/logical-operator.md)       | `nullishSwap`          | The same for `??` and `\|\|`                                                                                                                                                                         |
| [`logical-operator`](https://mootant.org/mutators/logical-operator.md)       | `nullishNormalization` | Drops a `null`, `undefined` or `void 0` default of `??`, so `value ?? null` becomes `value`                                                                                                          |
| [`method-call`](https://mootant.org/mutators/method-call.md)                 | `anyReceiver`          | Mutates methods also on receivers of another known type, such as `filter()` on an instance of your own class                                                                                         |
| [`number-literal`](https://mootant.org/mutators/number-literal.md)           | `caseTests`            | Mutates numbers in `case` labels                                                                                                                                                                     |
| [`optional-chaining`](https://mootant.org/mutators/optional-chaining.md)     | `nonNullable`          | Replaces `?.` also where type hints say that the value cannot be nullish, since annotations can be wrong at runtime                                                                                  |
| [`regex-flag`](https://mootant.org/mutators/regex-flag.md)                   | `additions`            | Adds `i` to a pattern with cased letters and `g` to the pattern of a `.replace()` call                                                                                                               |
| [`regex-pattern`](https://mootant.org/mutators/regex-pattern.md)             | `classMembers`         | Removes an element of a character class and narrows a range by one character at each end                                                                                                             |
| [`regex-pattern`](https://mootant.org/mutators/regex-pattern.md)             | `largeAlternations`    | Removes an alternative also from a list of more than eight                                                                                                                                           |
| [`regex-pattern`](https://mootant.org/mutators/regex-pattern.md)             | `negations`            | Negates classes and escapes, such as `[a]` and `[^a]` or `\d` and `\D`, and turns `\.` into `.`                                                                                                      |
| [`regex-pattern`](https://mootant.org/mutators/regex-pattern.md)             | `quantifiers`          | Narrows a quantifier, such as `x+` to `x` or `x*` to `x?`, and moves its bounds by one                                                                                                               |
| [`statement-removal`](https://mootant.org/mutators/statement-removal.md)     | `jumps`                | Removes `continue`, `yield` and the `break` of a loop or a label                                                                                                                                     |
| [`string-literal`](https://mootant.org/mutators/string-literal.md)           | `caseTests`            | Mutates strings in `case` labels                                                                                                                                                                     |
| [`string-literal`](https://mootant.org/mutators/string-literal.md)           | `jsxAttributes`        | Mutates quoted JSX attribute values, except those of `className`, `class`, `style`, `data-testid` and those whose meaning braces would change, such as `disabled=""`                                 |

## Settings

`settings` holds the settings that all mutators share. Each one overrides the
same setting of the presets:

```ts
export default defineConfig({
  settings: {
    templates: false,
  },
})
```

| Setting                           | `recommended`                                      | `strict` |
| --------------------------------- | -------------------------------------------------- | -------- |
| [`loggers`](#loggers)             | `['console', 'log', 'logger', '*Logger', 'debug']` | The same |
| [`templates`](#templates)         | `true`                                             | The same |
| [`timeouts`](#timeouts)           | `false`                                            | `true`   |
| [`coarseMutants`](#coarsemutants) | `false`                                            | `true`   |

### `loggers`

Loggers whose message text is not mutated. For example, Mootant skips `'Saved'`
→ `''` in `logger.info('Saved')`.

`recommended` sets `['console', 'log', 'logger', '*Logger', 'debug']`. Your list
replaces it, so repeat these names to add one:

```ts
export default defineConfig({
  settings: {
    loggers: ['console', 'log', 'logger', '*Logger', 'debug', 'consola'],
  },
})
```

Names can match an object with log methods, such as `logger` in
`logger.info('Saved')`, or a function that takes the message as its first
argument, such as `debug('Saved')`.

A name matches in any letter case. After a leading `*`, the rest matches as
written: `*Logger` matches `requestLogger`, but not `blogger`.

**Which log changes are skipped**

Mootant skips changes to strings and templates with only variable names in
`${}`, alone or joined with `+`. It also skips removing a `console` call with
only such text, such as `console.log('Saved')`, and changing child logger
labels, such as `'db'` in `logger.child('db')`.

Mootant still makes these changes:

- Changes to the code that builds the message, such as `name.trim()` → `name` or
  `'Total: ' + total` → `'Total: '`.
- Changes to a text with `%` or `${}` before other arguments, such as
  `'Order %j'` in `logger.info('Order %j', order)`: `%j` converts `order` to
  JSON and may throw, and `${}` may insert a `%`.
- The removal of other calls, such as `logger.info('Saved')` or
  `console.log('Saved', order.id)`: `logger` may be `undefined`, and `order.id`
  throws when `order` is `null`.

### `templates`

Whether expressions in Svelte and Vue templates are mutated, when Svelte 5 or
`@vue/compiler-dom` 3.5 or later is installed. `true` by default.

### `timeouts`

Whether to add the mutants that may cause timeouts, such as a loop condition
forced to `true`. `false` by default, `strict` turns it on.

### `coarseMutants`

Whether to keep a coarse mutant, such as a removed statement, when a finer
mutant lies inside it. `recommended` drops such a mutant when a test that kills
the finer one is likely to observe this code too. That is not a proof, so
`strict` keeps it.

## Run settings

`run` holds the defaults of `mootant run`. An option on the command line wins
over the setting of the same name:

```ts
export default defineConfig({
  run: {
    paths: ['src'],
    threshold: 80,
    concurrency: 4,
  },
})
```

| Setting                           | Default                                                           | For one run                               |
| --------------------------------- | ----------------------------------------------------------------- | ----------------------------------------- |
| [`paths`](#paths)                 | None                                                              | The paths after `mootant run`             |
| [`threshold`](#threshold)         | None                                                              | `--threshold`                             |
| [`concurrency`](#concurrency)     | `maxWorkers` of Vitest or Jest, CPU cores minus one for Node Test | `--concurrency`                           |
| [`fast`](#fast)                   | `false`                                                           | `--fast`, `--no-fast`                     |
| [`parallelUnits`](#parallelunits) | `false`                                                           | `--parallel-units`, `--no-parallel-units` |
| [`cache`](#cache)                 | `true`                                                            | `--cache`, `--no-cache`                   |
| [`incremental`](#incremental)     | `false`                                                           | `--incremental`, `--no-incremental`       |
| [`html`](#html)                   | No report                                                         | `--html`, `--no-html`                     |
| [`runner`](#runner)               | Detected                                                          | None                                      |
| [`timeout`](#timeout)             | `{ factor: 3, constant: 250 }`                                    | None                                      |
| [`hitLimit`](#hitlimit)           | `{ factor: 100, floor: 100000 }`                                  | None                                      |

### `paths`

Files and directories to mutate when the command line gives none, relative to
the root of the project. With them, `mootant run` needs no arguments.
`mootant list` always takes its paths from the command line.

### `threshold`

The lowest mutation score, from 0 to 100, that passes. Below it, the exit code
is 1. No threshold by default. The `--threshold` option sets it for one run.

### `concurrency`

The most test files to run at once. By default, the `maxWorkers` of Vitest or
Jest, or the number of CPU cores minus one for Node Test. The `--concurrency`
option sets it for one run. On top of it, up to as many idle processes may start
early for the next test files, no more than the CPU cores the running ones leave
free, but at least one.

### `fast`

Fast mode tries many mutants in one test run and trusts their kills. It is
faster, but a kill may be false, and tests that run concurrently run one at a
time. It works with Vitest and changes nothing with Jest and Node Test. `false`
by default. `--fast` and `--no-fast` set it for one run.

### `parallelUnits`

Runs a test file for several mutants at once. This speeds up runs where a few
test files cover most mutants. It works with Vitest and Node Test and changes
nothing with Jest. `false` by default. `--parallel-units` and
`--no-parallel-units` set it for one run.

Turn it on only if a test file can safely run twice at once: its tests use no
fixed file, port, database or other shared resource. Otherwise runs can disturb
each other and give false verdicts: mostly kills, which raise the score,
sometimes survivors, which lower it.

**Memory, cache and reports**

- Runs of one test file load at the same time, so memory use grows. Lower
  [`concurrency`](#concurrency) if memory runs short: test processes that run
  out of memory twice give their mutant a false kill.
- Runs with and without this setting never reuse each other's verdicts. The
  first run after a switch runs every mutant again.
- Reports mark such runs: the `time` line in the terminal, the mode in the HTML
  report and `"parallelUnits": true` in JSON.

### `cache`

Reuses verdicts from earlier runs. `true` by default. `--no-cache` and `--cache`
set it for one run.

Verdicts are stored in `node_modules/.cache/mootant` in the project root. A
verdict is reused while the mutated file and the files, environment variables
and, with Vitest, `provide` and `define` values read by its tests stay
unchanged.

Mootant tracks files read by tests, including files outside the project root,
such as workspace fixtures, and files of installed packages. Directory listings
above the project root, what recursive listings find in `node_modules`, and
files that `fs.cp` with a `filter` copies from a `node_modules` directory inside
the copied directory are not tracked.

When nothing has changed since the last run and every verdict is cached, Mootant
does not start the test runner. It reuses the run without mutants that the last
run saved. A change of any file in the project, of a file its tests read, of an
environment variable, of the configuration file, the working directory or the
concurrency starts the test runner as usual. Runs with `--mutant` or `--since`,
and runs in [fast mode](#fast) with Vitest, never reuse it.

**When to clear the cache**

Delete the cache directory after changes to:

- Inputs that only child processes or workers read, or data from the network.
- Installed packages that only the test runner loads, such as Vite plugins,
  packages that global setup imports, a test environment or Jest's transformers,
  made by hand or by a script such as `patch-package`.
- Directory listings above the project root, or what recursive listings find in
  `node_modules`.
- Files that `fs.cp` with a `filter` copies from a `node_modules` directory
  inside the copied directory.
- Files read only by a Vite plugin, unless they are tracked as described below.

For Jest, also check its
[cache invalidation rules](https://mootant.org/guide/compatibility.md#cache-invalidation).

**`--no-cache` does not clear or update saved verdicts.** It reruns every
selected mutant without reading or updating the cache.

**Files read by Vite plugins**

A file read only by a Vite plugin is tracked when both conditions hold:

- The plugin calls `this.addWatchFile()` for the file while loading or
  transforming the module.
- The module ID does not end in `.json` or `.map` and does not contain `.json?`
  or `.map?`.

Otherwise, delete the cache directory after changing that file.

**Runs that reuse the last run**

- Every environment variable counts, except a few that differ from one shell to
  another, such as `PWD`. A run where other variables are set, such as in an
  editor's terminal, or in CI, where variables change from run to run, starts
  the test runner.
- Files that editors and other tools keep in the project, such as `.idea`, count
  as changes too.
- A mutant without a cached verdict, such as a `Timeout` of the time limit,
  starts the test runner too.
- No tests run, and neither do global setup and teardown: results that depend on
  what global setup does in each run, such as a server it starts, stay those of
  the saved run, and a global setup that would fail now goes unnoticed. Tests
  that depend on time, randomness or the network keep their saved results, and
  `--verbose` shows no test output.
- A change outside the project root that no test of the saved run read, such as
  a workspace package behind a link, goes unnoticed.
- A run is not saved for reuse when it has errors, when a test file fails and
  then passes when it runs again, when a file changes while it runs, when the
  test runner reports a problem as it stops, when Mootant cannot tell which
  files a test file read, or when it cannot list a directory of the project.
  When a file changed during the run, a note names it.

To start the test runner and keep the cached verdicts, delete the `dry-v*.json`
file in `node_modules/.cache/mootant`.

**Files modified during a run**

If a file's modification time is at or after the start of a run, verdicts that
depend on it are neither reused nor saved in that run. The file may have changed
after tests read it. A file system clock that runs ahead can also produce such
timestamps.

Mootant warns if this prevents caching for the entire run. Files that tests read
and then write themselves are compared by content instead.

### `incremental`

Reuses cached verdicts after changes elsewhere in the project. Requires
[caching](#cache). `false` by default. `--incremental` and `--no-incremental`
set it for one run.

A verdict is reused while these dependencies stay unchanged:

- The declaration containing the mutant.
- The code that declaration depends on in the same file.
- Files, environment variables and, with Vitest, `provide` and `define` values
  read by its tests, excluding mutated files.

This speeds up runs after an edit, but changes to a caller or another mutated
file may leave a cached verdict stale.

### `html`

Whether to write the [HTML report](https://mootant.org/reports/html.md) after the run: `true` writes
it to `.mootant/report.html` in the root of the project, a path writes it there,
relative to the root. No report by default. `--html` asks for it for one run,
and `--no-html` skips it. A run of single mutants with `--mutant` writes a
report only with `--html`, so a re-check keeps the report of the whole run.

### `runner`

The test runner: `'vitest'`, `'jest'`, `'node-test'` or an adapter object. By
default, Mootant detects it, and a runner that the test scripts of
`package.json` call wins over one that is only installed.

To run Vitest with another configuration file than the one it finds, import the
adapter from `mootant/vitest`. The path is relative to the root of the project:

```ts
import { vitestAdapter } from 'mootant/vitest'
import { defineConfig } from 'mootant'

export default defineConfig({
  run: {
    runner: vitestAdapter({ config: 'vitest.unit.config.ts' }),
  },
})
```

The adapter of Jest comes from `mootant/jest`:

```ts
import { jestAdapter } from 'mootant/jest'
import { defineConfig } from 'mootant'

export default defineConfig({
  run: {
    runner: jestAdapter({ command: 'jest --config jest.unit.js' }),
  },
})
```

**Options of `jestAdapter`**

- `command`: the test command as a script of `package.json` has it, such as
  `jest --config jest.unit.js`. Mootant reads its variables and flags and never
  runs it. Taken from the test scripts by default.
- `env`: environment variables added to the Jest processes
- `freshWorkers`: `true` gives every run of a test file a new worker, so nothing
  a test file leaves in a worker reaches the next one. It is slower, and what
  global setup started and the files on disk stay shared. `false` by default.

The adapter of Node Test comes from `mootant/node-test`:

```ts
import { nodeTestAdapter } from 'mootant/node-test'
import { defineConfig } from 'mootant'

export default defineConfig({
  run: {
    runner: nodeTestAdapter({
      files: ['test/**/*.test.js'],
      env: { TZ: 'UTC' },
    }),
  },
})
```

**Options of `nodeTestAdapter`**

- `command`: the test command as a script of `package.json` has it, such as
  `bnt` or `node --test --import tsx`. Mootant reads its flags and files and
  never runs it. Taken from the test scripts by default.
- `files`: test files or globs, relative to the root, in place of those of the
  command
- `execArgv`: Node.js flags added after those of the command
- `env`: environment variables added to the test processes
- `node`: the Node.js binary that runs the tests, by default the one that runs
  Mootant

### `timeout`

The time limit for running a test file with a mutant. Defaults to
`{ factor: 3, constant: 250 }`.

Mootant calculates `factor × duration + constant` milliseconds for loading the
file and for each test, then adds these limits together. Each duration is
measured during the run without mutants.

When a mutant exceeds the limit:

1. Mootant runs the test file again with twice the time limit.
2. If the retry also times out, the mutant receives a `Timeout` verdict and
   counts as detected in the score. Otherwise, the test results decide its
   verdict.

A mutant that only slows a test down, such as a longer retry delay, can still
exceed the doubled limit. It then counts as detected even if the tests would
pass with more time. Near this limit, the verdict may vary with machine load.

Increase `constant` for such mutants, or ignore them with a
[comment](https://mootant.org/mutators.md#ignore-mutants).

### `hitLimit`

The maximum number of evaluations of mutated code while a test file runs with a
mutant. Defaults to `{ factor: 100, floor: 100000 }`.

Mootant calculates `max(floor, factor × hits)` for loading the file and for each
test, then adds these limits together. Each hit count is measured during the run
without mutants.

When a mutant exceeds the limit, for example by creating an endless loop:

1. Mootant stops running the test file and retries it with twice the time limit
   and `factor × floor` additional evaluations.
2. If the retry exceeds either limit, the mutant receives a `Timeout` verdict
   and counts as detected in the score. Otherwise, the test results decide its
   verdict.

A `Timeout` of the raised hit limit is [cached](#cache) too, except in fast
mode, but only a run that mutates exactly the same files reuses it, as hit
counts cover only those files: a re-check with `--mutant` runs it again. A
`Timeout` of the time limit is never cached.

In [fast mode](#fast), each test has its own hit limit. Exceeding that limit
first sends the mutant to a run of the whole test file.

A mutant that increases the number of evaluations, such as disabling a cache,
can exceed even the raised limit. It then counts as detected even if the tests
would otherwise pass. Increase `hitLimit` for such mutants.
