mutant-cafe 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  Mutation testing for [Effect](https://effect.website) TypeScript. mutant.cafe reads your types, breaks your functions in ways that still type-check, runs the tests related to each break, and lists the breaks your tests miss.
6
6
 
7
+ mutant.cafe is part of [rat-stack](https://ratstack.sh).
8
+
7
9
  It is inspired by [cargo-mutants](https://mutants.rs) by Martin Pool ([source](https://github.com/sourcefrog/cargo-mutants), MIT). The core idea, replacing a function body with a plausible value of its return type and reporting what the tests don't notice, comes from cargo-mutants, and so does the operator experience: a baseline run first, a scratch copy of your tree, per-mutant timeouts, `--in-diff`, and a `mutants.out` directory of results. mutant.cafe ports those ideas to Effect; it shares no code with cargo-mutants.
8
10
 
9
11
  ## What it adds for Effect
@@ -30,7 +32,7 @@ npx mutant-cafe --jobs 4 # test them
30
32
 
31
33
  It mutates internal functions by default, including `Effect.fn` and `Effect.fnUntraced`, object-literal arrows, service methods inside Layers, and the inner function of a curried export. Layer values and static Layer properties are targets too. Names follow their path, such as `Greeter.layer.greet`, `policy.canEdit`, and `guardFor.<inner>`. With `--exported-only`, targets must be reachable through an exported binding path: exported top-level functions, methods and functions in exported values, returned curried functions, and exported Layers with their returned service methods. Local declarations and arrows inside other function bodies are internal, even if their owner is exported. This keeps local helpers out without dropping exported object or service APIs.
32
34
 
33
- Value synthesis includes branded strings and numbers, empty sets and maps, anonymous objects with cycled literal fields, and same-typed parameters as identity replacements. Naked type-parameter returns get no fabricated values, but a same-typed parameter can still supply an identity mutant. Context-only generic types that cannot be named in the body are skipped with a reason. Literal leaves keep their type without making mutable arrays readonly. Generator mutants use the body's type before `Effect.fn` pipeables such as `Effect.scoped` or `Effect.map`.
35
+ Value synthesis includes branded strings and numbers, empty sets and maps, anonymous objects with cycled literal fields, and every assignable parameter as an identity replacement, named by the parameter. Boolean and literal unions with up to eight members are exhaustive, excluding an obvious original constant. Swallow mutants enumerate recoveries only for genuinely finite success types with at most four members, including both booleans. Numbers, strings, structs, Json and larger finite sets use one representative per error tag. Larger or recursive shapes have at most six synthesized representatives per function and genre, plus `undefined` when present. For `Schema.Json`, these are `null`, `""`, `0`, `false`, `[]` and `{}`. Capped tagged unions keep the original body's discriminant first, with fields emptied, then other variants in declaration order. Synthesis stops beyond depth four or 2 KiB of printed value text and records the bound. Assignable-parameter identities are separate from the literal cap. Values differing only by `as const` or redundant parentheses generate one mutant. Naked type-parameter returns get no fabricated values, but a same-typed parameter can still supply an identity mutant. Context-only generic types that cannot be named in the body are skipped with a reason. Literal leaves keep their type without making mutable arrays readonly. Generator mutants use the body's type before `Effect.fn` pipeables such as `Effect.scoped` or `Effect.map`.
34
36
 
35
37
  Run it from the package whose tests you want to check. In a monorepo that resolves workspace packages through built output, build the package's dependencies first.
36
38
 
@@ -118,7 +120,7 @@ Mutant ids are stable within a version and may change between versions before 1.
118
120
 
119
121
  Results land in `mutants.out/`: `missed.txt`, `caught.txt`, `timeout.txt`, `unviable.txt`, `untested.txt`, `unreliable.txt`, `not-mutated.txt`, a context diff and a log per mutant, and `outcomes.json`. Every result line includes the mutant id used by `diff/<id>.diff` and `logs/<id>.log`. Lines show the declared return type when available, or an abbreviated inferred type; JSON keeps full types and uses report `schemaVersion: 2`. Add `mutants.out*` to `.gitignore`. Your source tree is never edited: each mutant runs in a scratch copy. Workspace dependency links back into the copied source tree, including package self-links, point at the scratch packages rather than the originals. Mutation imports are added when the file has no usable value import for an Effect API.
120
122
 
121
- `not-mutated.txt` lists considered functions with no mutants and their reasons: unsupported return values or required fields, generic returns, and explicit exclusions. The summary includes that count. With `--in-diff`, only skips from files touched by the diff are reported. The baseline command prints before execution. A failed baseline still writes `outcomes.json`, including its command and output tail; TypeScript load errors print the tsconfig path and diagnostics.
123
+ `not-mutated.txt` gives one located line per considered function or Layer value with omitted mutations: `file:line:column`, target path and reason. Layer values use their initializer location; unavailable locations print `?:?`. It reports unsupported return fields, generic returns, explicit exclusions, capped values with an omitted count, and error classes whose constructors are unavailable. A constructor failure does not suppress recoveries or defects. Callbacks in arguments and arrays have their own locations; schema and brand constants are not functions. When a return cannot be synthesized but inner functions are mutated, the reason says so. The summary includes the line count. A target that the compiler cannot analyse gets a located `analysis failed` reason without aborting the remaining targets. Faults discovered during viability checks join the same skip report rather than becoming unviable outcomes. Config and program-load failures still stop the run. With `--in-diff`, only skips from files touched by the diff are reported. An empty selection, including a zero budget or a diff outside function bodies, skips the baseline, prints the selection count and cause to stderr, and writes a report with zero run and no baseline command. An empty actionable summary says “No actionable mutants.” The baseline command prints before execution when there are selected mutants. A failed baseline still writes `outcomes.json`, including its command and output tail; TypeScript load errors print the tsconfig path and diagnostics.
122
124
 
123
125
  An include glob that matches no source file is a usage error, including a path outside the package root. Diff paths resolve from the Git toplevel, with support for `git diff --relative`; outside Git they resolve from the working directory.
124
126
 
@@ -127,7 +129,7 @@ An include glob that matches no source file is a usage error, including a path o
127
129
  | 0 | no missed, unreliable, untested or timed-out mutants |
128
130
  | 1 | usage, source or tsconfig error |
129
131
  | 2 | some mutants were missed, or untested with no unreliable results |
130
- | 3 | some timed out, with no missed, unreliable or untested results |
132
+ | 3 | baseline deadline exceeded, or some mutants timed out with no missed, unreliable or untested results |
131
133
  | 4 | baseline tests fail |
132
134
  | 5 | the `--in-diff` diff does not match the tree |
133
135
  | 6 | the diff cannot be parsed |
@@ -147,6 +149,8 @@ Precedence is **missed (2), unreliable (7), untested (2), then timeout (3)**. A
147
149
  | untested | related selection found no test files and the full-suite fallback did not fail |
148
150
  | unreliable | an unsupported runner, an omitted importing test, or a selected test reading a built self-entry instead of the affected source |
149
151
 
152
+ For built-in Node pools, mutant.cafe checks an empty related selection once per source file with a temporary module-load poison. The full suite must pass, its control hook must run, and no module-load signal may appear before any mutants in that file can be returned as untested without execution. A caught dynamic import still emits the signal, so it keeps per-mutant fallback. Probes and their durations appear in `reachabilityProbes` in the report. Unsupported pools and unreliable selections keep the existing fallback. This optimization applies to both cold and warm modes.
153
+
150
154
  Vitest first runs tests related to the mutated file. When that selects no test files, mutant.cafe reruns the package's full suite within the remaining budget. A failing fallback counts as caught, including dynamic-import consumers. A passing fallback is untested, not missed: unrelated passing tests do not prove they reached the mutant.
151
155
 
152
156
  Before the baseline, mutant.cafe checks `package.json`'s test script and asks the installed Vitest for its resolved test files. It warns when another runner owns the test script or a test importing a target is omitted. Test support imported by selected tests is not an omitted suite. Affected viable mutants are unreliable and are not scored as missed; their diagnostics name the script or omitted test. Common wrappers (`pnpm exec vitest`, `npx vitest`, `cross-env … vitest`, chained commands and `vitest --project`) count as Vitest scripts. Delegated scripts such as `turbo run test` or `pnpm -r test` are unverified, not declared non-Vitest.
@@ -159,7 +163,23 @@ This does not add `node:test` support. Literal relative imports are traced trans
159
163
 
160
164
  Selection and partial failures come from Vitest's reporter hooks, not its human-readable messages. A reported failure still counts as caught if another test file hangs.
161
165
 
162
- Ordinary mutants use the configured timeout. For `Effect.never`, mutant.cafe measures the unmutated related run once per file, including any full-suite fallback. Its budget is that duration × the timeout multiplier, with a 1 s floor. Slow tests that never call the function can finish normally; a process killed before test collection is not credited as caught. Each mutant run also sets Vitest's per-test timeout to half its budget, overriding a package's `testTimeout: 0`, and stops after the first reported failure.
166
+ ### Warm and cold runs
167
+
168
+ The baseline has a 30-minute overall hang guard, including selection and process startup. Set `--baseline-timeout 2400` (seconds), or `baselineTimeoutMs` in `mutants.config.json`, for a longer suite. Expiry reports `BaselineTimedOut`, names the limit and flag, and exits 3 rather than calling the original tests failed. Each paired calibration run uses that same baseline budget independently, across all scratch copies. Each cold execution also includes startup in its existing per-run budget. Cold runs launch the installed project's Vitest bin through Node, without an npm wrapper or shell lookup; the printed command names the actual generated launcher. Cleanup runs after deadline expiry before the next execution.
169
+
170
+ Set `MUTANT_CAFE_PROCESS_TRACE=/absolute/path/trace.jsonl` to opt into timestamped startup and cleanup stages: parent spawn, preload, birth inspection, child spawn, Vitest resolution/start, test-module start and cwd inspection. Traces append process IDs, times and stage details, not arguments, environment contents or test output. No trace file is written by default.
171
+
172
+ By default, mutant.cafe first verifies a clean cold baseline and stops if it fails. It then excludes unviable and probe-cached mutants from calibration. Small runs stay cold without more baselines. Other runs measure warm and cold after the successful primer, so both use warmed filesystem inputs. Warm must select the same files, pass, and be at least 10% faster. At decision time the samples and opened copies are already paid for. Projected savings must cover only startup for copies not yet opened; sample costs remain in the report but do not bias the choice. Reports include the decision, measured costs and testable-mutant count. Use a forcing flag to avoid calibration.
173
+
174
+ A warm scratch copy keeps one instance of the project's installed Vitest. Mutations and restores invalidate the changed module and its importers before the next run. Vitest's normal per-file isolation resets module-level state. Both modes use the project's configured worker count, or Vitest's default. `--jobs N` uses N scratch copies.
175
+
176
+ Use `--cold` to start a fresh Vitest process for each mutant that needs tests, or `--warm` to force a persistent instance. The flags are mutually exclusive. Warm execution supports isolated built-in `forks` and `threads` pools on Vitest major 5, verified against 5.1.0. Other majors, VM pools, browser mode, custom pools, `globalSetup`, `isolate: false`, `poolOptions.*.isolate: false` and `--no-isolate` use cold execution. Auto falls back silently; `--warm` warns once with the reason. `baseline.runnerModeReason` records the reason in either mode. Selection-only hosts can inspect refused configurations but cannot execute tests; quiet logging never relaxes execution checks. The adapter also checks the private fields and transform/invalidation interfaces it uses. Falling back for `globalSetup` ensures each mutant initializes from its own source, just as cold execution does.
177
+
178
+ After every warm execution, mutant.cafe closes the disposable worker pool and reaps test-created descendants before the next mutant. The Vitest/Vite host and its startup services remain alive. Test and hook timeouts, parallel bail and ordinary unhandled errors do not restart a healthy host. An unhandled error is a caught failure unless the project ignores it. Real worker death gets one pool retry; a second death switches the remaining run to cold mode. Only an unhealthy host is replaced. Reports and summaries include host restarts and unexpected pool resets from crashes, outer-deadline recovery or cancellation. Routine pool disposal is not counted. A host health check performs a trivial Vite transform as well as an IPC round trip. Worker-budget telemetry comes from Vitest's resolved config and is omitted when unavailable. Invalid telemetry never changes a verdict or triggers a pool retry: outcomes are written first, then the reporter warns with the bad field and value.
179
+
180
+ Each Vitest instance has an ownership ledger. Child spawns inherit a unique label. Cleanup checks recorded PID identities, parent chains and escaped process groups with POSIX `ps`, then stops, kills and verifies the owned tree. Cleanup runs before reuse and on exit. Inspection or ownership failures warn with tracked PIDs, keep the ledger and let the run continue; an unhealthy host is not reused. Each ownership sweep shares a 10-second deadline across discovery, signalling and retries. Inspector calls allow two seconds, discovery seven seconds and signalling three seconds, all clamped to that shared deadline. These are hang guards, not clean-run speed targets. PPID descendants in the snapshot are claimed before fallible label inspection, so degraded cleanup claims unlabelled children before signalling their known parents. Inspector subprocesses receive cancellation signals; a stalled inspection cannot turn interruption into minutes of serial retries. If inspection fails or the budget expires, cleanup still attempts SIGKILL for PIDs already birth-matched in that sweep, then warns about unconfirmed exits and unverified ledger PIDs. A stale ledger entry alone never authorizes a signal. Zombies do not count as live survivors, and unverifiable PIDs are never signalled. Explicit child environments are left unchanged. The preload is appended only for implicit children using the current Node executable. Inspector environment output is never logged or included in reports. A minimal-env grandchild that daemonizes after its parent exits can escape cleanup. After each run, a scratch-path scan warns with the PIDs of unowned survivors; it never kills a process on a path match alone. The warning scan recognizes birth-validated PIDs from every live mutant.cafe ledger, including selector hosts. It reuses the latest PID/birth/argv snapshot and checks cwd only for unknown processes born since the scratch session opened. Darwin restricts `lsof` to those candidate PIDs, drops exited or inaccessible PIDs and preserves partial output when another candidate exits during inspection. This warning-only filter never changes ownership or kill permissions. Each executed result records `backstopMs`, the total scratch-path scan time during that mutant. Summaries show its per-mutant p50/p90; baseline and selector-only scans are not samples. A source entry that vanishes during scratch copying is skipped with a debug note; permission errors, dangling source symlinks and missing destinations still fail the copy. Scratch removal allows 30 seconds for large workspaces and sends failures to stderr, never into GitHub Markdown output.
181
+
182
+ Ordinary mutants use the configured timeout. For `Effect.never`, the reporter measures each passing test in the clean baseline. The budget uses the slowest test among the related files, including any full-suite fallback. A related-file probe selects those files. Comparing each task's original and probe timeouts distinguishes explicit options from inherited defaults; the probe's imposed timeout is not an original limit. The test and hook timeout is that duration × the timeout multiplier, with a 2 s floor, rather than the duration of the whole suite. Explicit per-test timeout options remain in effect, including larger values. Vitest does not expose a configuration API to raise a smaller explicit per-test timeout; those tests still use their own value. Reports record the computed timeout on each mutant result. The report also records the baseline test duration used as the budget base and the separate outer deadline. An inherited config timeout does not raise the outer deadline. That deadline allows the original startup time and the selected baseline files' collection, environment, hook and test durations, not the duration of the whole package. Cold and warm modes use the same per-test budget policy, so switching modes alone does not shorten a hanging test's timeout. A process killed before test collection is not credited as caught. Other mutants keep the existing per-test timeout of half their run budget. Both modes stop after the first reported failure.
163
183
 
164
184
  ## Prior art
165
185
 
@@ -167,7 +187,7 @@ Ordinary mutants use the configured timeout. For `Effect.never`, mutant.cafe mea
167
187
 
168
188
  ## License
169
189
 
170
- MIT
190
+ MIT. Part of [rat-stack](https://ratstack.sh).
171
191
 
172
192
  ## Package build
173
193