# JSON report

**The JSON report gives scripts and agents the results of a run.** It includes
the score, problems found along the way and the mutants to act on, with their
changes and commands to re-check them.

## Save the report

Redirect the output of `--json` to a file:

```sh
npx mootant run src --json > mutation.json
```

Mootant writes one JSON object to stdout when the run finishes. Progress and
test output go to stderr, so they do not enter the file. The examples below are
formatted for reading; the command writes JSON on one line.

A run with errors or a score below its threshold still writes its report and
exits with code 1. A failure before the report, such as tests failing without
mutants, prints the error to stderr and writes no JSON. Check the exit code and
whether the file contains a report before parsing it. An interrupted run writes
no report either; see [exit codes](https://mootant.org/guide/cli.md#mutation-score-and-exit-code).

With `--html`, the same run also writes an [HTML report](https://mootant.org/reports/html.md). If that
file cannot be written, the command exits with code 1 even when the JSON
report's `summary.passed` is `true`.

## Choose the detail

| Command options              | Mutants included                                          | Detail                                                                                                                                     |
| ---------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `run --json`                 | `Survived`, `NoCoverage` and `Error`                      | Compact: changes, test suggestions and re-check commands                                                                                   |
| `run --json --all`           | Every mutant, including `Killed`, `Timeout` and `Ignored` | Compact; killed and timed-out mutants have only their identity, position, status, `killedIn` when known and a batch `path` when applicable |
| `run --json --verbose`       | `Survived`, `NoCoverage` and `Error`                      | Full: source ranges, covering tests, cache and timing details                                                                              |
| `run --json --verbose --all` | Every mutant                                              | Full                                                                                                                                       |

`--all` changes which mutants appear. `--verbose` changes their detail. Neither
changes the counts or score in `summary`, which describe every mutant selected
for the run. With `--since` or `--mutant`, that selection can be smaller than
the project.

To save the full report of every mutant:

```sh
npx mootant run src --json --verbose --all > mutation.json
```

The download button of the [HTML report](https://mootant.org/reports/html.md) saves this full format
with every mutant, plus a `skipped` array of changes Mootant left out.

## Example run

This command re-checks the boundary mutant from the
[getting started guide](https://mootant.org/guide/getting-started.md#fix-a-surviving-mutant), in the
sample shop:

```sh
npx mootant run src/discount.ts --mutant q31p --threshold 80 --json
```

The mutant survives, so the score is `0`, `passed` is `false` and the command
exits with code 1. The test runner checks related test files without mutants
first: `totalTests` counts those tests, while the mutant's `tests` counts only
the ones that reached it. Timings vary between runs.

**Complete compact report**

```json
{
  "summary": {
    "coveredScore": 0,
    "threshold": 80,
    "score": 0,
    "totalErrorMutants": 0,
    "duration": {
      "total": 1143
    },
    "totalNoCoverage": 0,
    "totalSurvived": 1,
    "totalWarnings": 0,
    "totalIgnored": 0,
    "totalTimeout": 0,
    "totalMutants": 1,
    "totalKilled": 0,
    "totalErrors": 0,
    "totalTests": 9,
    "totalFiles": 1,
    "passed": false
  },
  "schemaVersion": 4,
  "diagnostics": [],
  "command": "run",
  "listed": "actionable",
  "runner": "vitest",
  "preset": "recommended",
  "mode": "isolated",
  "mutants": [
    {
      "scope": "getDiscount",
      "mutator": "comparison-operator",
      "column": 7,
      "status": "Survived",
      "before": ["  if (total >= 100 || isMember) {"],
      "after": ["  if (total > 100 || isMember) {"],
      "file": "src/discount.ts",
      "line": 2,
      "id": "q31p780qv6yk",
      "testFiles": {
        "test/discount.test.ts": 3,
        "test/cart.test.ts": 3
      },
      "test": {
        "line": 6,
        "file": "test/discount.test.ts",
        "name": "getDiscount > gives members 10% off"
      },
      "tests": 6,
      "recheck": "mootant run src/discount.ts --mutant q31p780qv6yk"
    }
  ]
}
```

## Report fields

Both `run` and `list` use these fields, in either format:

| Field           | Meaning                                                                                               |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| `schemaVersion` | Version of the report format, currently `4`                                                           |
| `command`       | `"run"`, or `"list"` for [listing mutants](#list-without-running-tests)                               |
| `preset`        | The `--preset` id, or the ids in [`extends`](https://mootant.org/guide/configuration.md#presets), comma-separated           |
| `diagnostics`   | Problems found while listing or running mutants                                                       |
| `summary`       | Counts of files and mutants; a run adds scores and timings                                            |
| `mutants`       | Mutants to act on, or every mutant for `list` and `run --all`                                         |
| `since`         | With `--since`, `{ "ref": "origin/main", "base": "…" }`: the given revision and its merge-base commit |

A run also has:

| Field           | Meaning                                                                                                    |
| --------------- | ---------------------------------------------------------------------------------------------------------- |
| `listed`        | `"actionable"` by default, or `"all"` with `--all`                                                         |
| `runner`        | Name of the test runner adapter                                                                            |
| `mode`          | `"isolated"` or `"fast"`; see [fast mode](https://mootant.org/guide/configuration.md#fast)                                       |
| `parallelUnits` | `true` when Vitest or Node Test ran [parallel units](https://mootant.org/guide/configuration.md#parallelunits); absent otherwise |

The full run report adds `runnerVersion`, the `files` array and the `mutators`
array. A file has `file`, `parsed` and `mutants`. A mutator has `id`,
`description` and `mutants`. Their counts include ignored mutants.

### Missing values and versions

The compact report leaves out many fields when they have no value. For example,
`since` is absent without `--since`, and `test` is absent when no test covers a
mutant. The full report uses `null` for these values. Some fields, such as
`parallelUnits`, `focus` and `skipped`, are optional in both formats.
Diagnostics keep their `null` locations in both formats.

`schemaVersion` changes when a field is removed or its meaning changes. Adding a
field does not change it. Check `schemaVersion` and `command` in a reader,
accept extra fields and request `--verbose` if the reader needs the full format.
Both formats have the same schema version.

## Mutants

Each mutant has a full `id`, its `mutator`, `file`, `line`, `column` and
`status`. Paths use `/` separators and are relative to the
[project root](https://mootant.org/guide/configuration.md#project-root).

For mutants to act on, the compact report also gives:

| Field             | Meaning                                                                    |
| ----------------- | -------------------------------------------------------------------------- |
| `before`, `after` | Arrays of source lines before and after the change                         |
| `scope`           | Dotted names of the surrounding declarations, when there are any           |
| `focus`           | The part that changes, with its position and texts, when available         |
| `tests`           | Number of tests that reached the mutant                                    |
| `testFiles`       | Suggested test files to extend, mapped to their numbers of covering tests  |
| `test`            | One covering test to start from: `file`, full `name` and `line` when known |
| `recheck`         | Command to run this mutant again                                           |
| `message`         | First line of the reason of an `Error`, when available                     |

`testFiles` contains at most three suggestions, followed by the file of `test`
if it was not among them. A count of `0` is a suggestion, not evidence that a
test reached the mutant. Read `diagnostics` too: an uncovered file may have been
imported through a built copy rather than through the test runner's transform.

`recheck` keeps the source paths and the `--config`, `--preset`, `--fast`,
`--parallel-units` and `--incremental` options as given. It leaves out
`--since`, since the mutant's id already selects it, and the changed lines may
differ after a commit or rebase. Run the command from the same working directory
as the original run.

Long `before` and `after` lines are cut around the change. The compact report
marks the missing text with `…`. The full report gives `cutStart` and `cutEnd`,
the number of UTF-16 code units left out at each end, instead. These arrays are
for displaying a diff; use the full report's ranges and replacement text when
you need the exact edit.

### Statuses

| Status       | Meaning                                                       | Effect on the score     |
| ------------ | ------------------------------------------------------------- | ----------------------- |
| `Killed`     | A test, hook or other checked failure detected the mutant     | Detected                |
| `Timeout`    | The mutant exceeded a time or hit limit, confirmed by a retry | Detected                |
| `Survived`   | Tests reached the mutant and still passed                     | Undetected              |
| `NoCoverage` | No test reached the mutant                                    | Undetected              |
| `Ignored`    | An ignore comment excluded the mutant                         | Excluded                |
| `Error`      | Mootant could not decide the mutant                           | Excluded; fails the run |

With `--all`, an ignored mutant includes `ignoredBy`, the directive and its
position, and `reason` when the comment gives one. It has no re-check command.

### Full mutant fields

`--verbose` adds the following details to the common mutant fields:

| Fields                    | Meaning                                                                               |
| ------------------------- | ------------------------------------------------------------------------------------- |
| `original`, `replacement` | Exact source text and its replacement                                                 |
| `start`, `end`            | Zero-based UTF-16 offsets; `end` is just past the replaced text                       |
| `endLine`, `endColumn`    | Position just past the replaced text                                                  |
| `kind`                    | How to insert the replacement: `expression`, `block`, `element` or `property`         |
| `coveredBy`               | Covering tests, or `null` for a killed or timed-out mutant                            |
| `killedBy`, `killedIn`    | The test and test file that decided the verdict, when known                           |
| `message`, `cause`        | First line of the failure and how the mutant was detected, when known                 |
| `duration`, `cached`      | Time spent on the mutant in milliseconds, and whether its verdict came from the cache |
| `path`, `isolatedBecause` | How the verdict was reached, and why an isolated run was needed                       |

For the same mutant, these fields in the full report describe its exact edit
(other fields are omitted here):

```json
{
  "original": "total >= 100",
  "replacement": "total > 100",
  "kind": "expression",
  "start": 78,
  "end": 90,
  "line": 2,
  "column": 7,
  "endLine": 2,
  "endColumn": 19
}
```

Lines and columns are one-based. Columns and offsets count UTF-16 code units, as
JavaScript strings do. `focus` has its own text and position, but only marks the
part to display. Use the mutant's full range and replacement for the edit.

For `expression`, put the replacement in parentheses; for a quoted JSX
attribute, put those parentheses in braces too. For `block`, wrap it in braces.
For `element` and `property`, insert it as written: the replaced range includes
the removed item's comma.

`coveredBy`, `tests`, `test` and `testFiles` are `null` for killed and timed-out
mutants. Use `killedBy` or `killedIn` instead. A test object has `file`, `name`
and `line`; `line` is `null` when the runner does not provide it.

`cause` is one of `assertion`, `stray-error`, `load-error`, `hook-error`,
`crash`, `hit-limit`, `time-limit` or `hang`. A kill need not come from an
assertion: a failure while loading the mutated module can detect it too.

`path` is `"isolated"`, `"batch"` or `null` when no attempt decided it. A batch
kill or timeout in fast mode may be false because of state left by an earlier
attempt. The compact report keeps `path` only for a batch verdict.
`isolatedBecause` is usually `null` outside fast mode; `"static"` means the
mutant was reached while loading a test file.

## Summary and score

Use `summary` for totals, rather than counting `mutants`: the default array
leaves out killed, timed-out and ignored mutants.

| Field                               | Meaning                                                                   |
| ----------------------------------- | ------------------------------------------------------------------------- |
| `totalMutants`                      | Number of selected mutants                                                |
| `totalFiles`                        | Number of mutated files                                                   |
| `totalTests`                        | Number of tests from the run without mutants                              |
| `totalKilled`, `totalTimeout`       | Mutants killed or timed out, counted separately                           |
| `totalSurvived`, `totalNoCoverage`  | Surviving and uncovered mutants, counted separately                       |
| `totalIgnored`, `totalErrorMutants` | Ignored mutants and mutants with an `Error` verdict, counted separately   |
| `totalErrors`, `totalWarnings`      | Counts of diagnostics, separate from mutant statuses                      |
| `score`, `coveredScore`             | Mutation scores, in percent, rounded to two decimal places                |
| `threshold`                         | Passing score, when set                                                   |
| `passed`                            | No error diagnostics, no `Error` mutants and no score below the threshold |
| `duration.total`                    | Duration of the whole run in milliseconds                                 |
| `totalBatch`                        | Mutants killed or timed out in batch attempts; present in fast mode       |

The full score is:

```text
100 × (Killed + Timeout) / (Killed + Timeout + Survived + NoCoverage)
```

`coveredScore` leaves `NoCoverage` out of the denominator. `Ignored` and `Error`
never enter either score. A score with no denominator is absent in the compact
report and `null` in the full one. With no mutants to score, any threshold
passes, though errors still fail the run.

**Full summary details**

The full summary also includes:

- `duration`: adds `startup`, `dryRun`, `isolated` and `batch` timings; `batch`
  is `null` outside fast mode.
- `totalCached`: verdicts reused from the cache, or `null` when caching was off.
- `runs`: numbers of test runner runs by kind: `dry`, `isolated`, `batch`,
  `confirmation` and `recovery`. Kinds that did not run are absent.
- `totalIsolated`, `totalStatic` and `totalUnrepeatableTests`: counts used to
  explain how the run tested mutants. The last is `null` outside fast mode.
- `staticCost`: per-file isolated execution cost, with `file`, `duration`,
  `units` and the number of static `mutants`.

## Diagnostics

`diagnostics` lists problems found while processing files and running tests. No
test of the sample shop imports `src/stock.ts`, so
`npx mootant run src/stock.ts --json` lists this entry:

```json
{
  "severity": "warning",
  "column": null,
  "line": null,
  "message": "No test loaded src/stock.ts through the test runner's transform: no test imports it, or tests import a built copy, an external or a pre-bundled dependency.",
  "file": "src/stock.ts",
  "code": "never-served"
}
```

The message depends on the problem. Use `code` and `severity` in a reader rather
than matching message text. `file` is `null` for problems of the whole run.
`line` and `column` are `null` when the problem has no position.

`summary.totalErrors` counts diagnostics with `severity: "error"`.
`summary.totalErrorMutants` counts mutants with `status: "Error"`. A file that
could not be parsed can have an error diagnostic and no mutants, so check both.

## List without running tests

Use `list` to inspect the mutants before a run:

```sh
npx mootant list src --json > mutants.json
npx mootant list src --json --verbose --skipped > mutants-full.json
```

The report has `command: "list"`. It contains every listed mutant, with status
`"Pending"` or `"Ignored"` and the same `before`, `after`, `scope` and `focus`
as in a run, but no test results or scores. It has no `listed`, `runner` or
`mode`. `--all` is a `run` option; `list` already includes every mutant in the
selected paths and changed lines.

Its summary contains `totalFiles`, `totalMutants`, `totalPending`,
`totalIgnored`, `totalErrors` and `totalWarnings`. `--verbose` adds exact source
text, ranges and kinds to the mutants, and the `files` and `mutators` arrays to
the report.

### Skipped changes

`list --skipped` adds `skipped`, `summary.totalSkipped` and
`summary.skippedByCategory`. Skipped changes are candidates that Mootant did not
emit; they do not add entries to `mutants`.

Each entry includes its `file`, `line`, `column`, `mutator`, `original`,
`replacement`, `category`, `rule`, `reason` and `heuristic`. `heuristic: true`
means the decision rests on a guess, such as a type hint, rather than a proof.
See [skipped changes](https://mootant.org/mutators.md#skipped-changes) for the categories.

`by`, when available, names the mutant that justifies the skip by its `mutator`,
`line` and `column`. Its `id` is set only for the `duplicate` and `solitary`
rules, which drop a change in favor of a listed mutant. Other skips leave it
`null`, even when that mutant is in `mutants`. `focus` marks the changed part
when available. The full format also has `start` and `end` offsets on skipped
changes and their focus, and uses `by: null` when no single mutant justifies the
skip.

`run` has no `--skipped` option. To get skipped changes alongside verdicts,
download the JSON from the [HTML report](https://mootant.org/reports/html.md).
