diff --git a/.github/workflows/mutation-report.yml b/.github/workflows/mutation-report.yml
new file mode 100644
index 000000000..55afa880b
--- /dev/null
+++ b/.github/workflows/mutation-report.yml
@@ -0,0 +1,64 @@
+name: Mutation report
+
+# Weekly, report-only mutation trial (docs/TESTING_INTERNALS.md#mutation-report).
+# StrykerJS plants small wrong edits in the five lib files with the most commits
+# in the last 90 days and runs the tests that import each file; the step summary
+# and the artifact list every edit no test caught. It never blocks a merge: it
+# is not a required check and does not run on pull requests.
+#
+# Stryker and its Bun runner are installed at exact versions into the runner's
+# temp directory (scripts/mutation-report.ts STRYKER_PACKAGES), so package.json
+# and bun.lock do not change. Stryker edits files in place, so it runs only in
+# this job's own disposable checkout.
+
+on:
+ schedule:
+ - cron: '0 6 * * 6' # Saturday 06:00 UTC, away from Monday's periodic census
+ workflow_dispatch:
+ inputs:
+ files:
+ description: How many of the most-changed lib files to mutate
+ type: string
+ default: '5'
+
+concurrency:
+ group: mutation-report
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+
+jobs:
+ mutation-report:
+ name: Mutation report
+ runs-on: ubicloud-standard-16
+ timeout-minutes: 330
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ fetch-depth: 0
+ filter: blob:none
+ persist-credentials: false
+ - name: Prepare the same inputs as a free-suite shard
+ run: |
+ bash scripts/ubicloud/setup-free-suite.sh
+ echo "$HOME/.bun/bin" >> "$GITHUB_PATH"
+ - name: Install pinned Stryker outside the checkout
+ run: |
+ set -euo pipefail
+ read -ra packages <<< "$(bun --no-env-file --config=/dev/null -e 'import { STRYKER_PACKAGES } from "./scripts/mutation-report.ts"; console.log(STRYKER_PACKAGES.join(" "))')"
+ npm install --prefix "$RUNNER_TEMP/stryker" --no-save --no-audit --no-fund --ignore-scripts "${packages[@]}"
+ - name: Run the mutation report
+ env:
+ FILES: ${{ inputs.files || '5' }}
+ run: |
+ set -euo pipefail
+ GSTACK_HOME="$RUNNER_TEMP/gstack-home" xvfb-run -a bun --no-env-file --config=/dev/null scripts/mutation-report.ts \
+ --throwaway-checkout --files "$FILES" --concurrency 14 --file-budget-min 55 \
+ --stryker-dir "$RUNNER_TEMP/stryker" --out-dir "$RUNNER_TEMP/mutation" --summary-file "$GITHUB_STEP_SUMMARY"
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ if: always()
+ with:
+ name: mutation-report
+ path: ${{ runner.temp }}/mutation/
+ if-no-files-found: ignore
diff --git a/changelog.d/mutation-report.md b/changelog.d/mutation-report.md
new file mode 100644
index 000000000..e8ed2b51e
--- /dev/null
+++ b/changelog.d/mutation-report.md
@@ -0,0 +1 @@
+**A weekly report shows which small wrong edits gstack's tests fail to catch.** Every Saturday a new workflow, Mutation report, uses StrykerJS to plant small wrong edits in the five `lib/` files with the most landings in the last 30 days, runs the tests that import each file, and lists every edit no test failed on. Before it mutates a file, a positive control makes the file throw on load and checks that those tests fail. If they still pass, the tests never load the file directly and the file is reported without mutation scores. The report never blocks a merge. It is a trial, and its results decide whether mutation testing earns a permanent place.
diff --git a/docs/TESTING_INTERNALS.md b/docs/TESTING_INTERNALS.md
index c9098ae28..6d1c81584 100644
--- a/docs/TESTING_INTERNALS.md
+++ b/docs/TESTING_INTERNALS.md
@@ -1139,6 +1139,29 @@ machine swap, in this order:
plus ten minutes has passed, so set `UBI_TTL_HOURS` above the expected
duration and name that duration in the thread before launching.
+## Mutation report
+
+A weekly, report-only trial of mutation testing. It checks whether gstack's tests reject plausible wrong code in the files agents change most. `.github/workflows/mutation-report.yml` runs every Saturday at 06:00 UTC, or on demand through workflow_dispatch, on `ubicloud-standard-16`. It is not a required check, never runs on pull requests, and never blocks a merge.
+
+`scripts/mutation-report.ts` does the work:
+
+1. It picks the five `lib/**/*.ts` files (not tests) with the most landings on main in the last 30 days (`git log --first-parent`), from the job's full-history checkout. A file that no test imports is listed as `no tests`, and a file Stryker finds nothing to mutate in (a data-only file) as `no mutants`; in both cases the next file takes its place.
+2. For each file it selects the test files that import it directly. If none do, it falls back to the transitive importers from `lib/pregate/import-graph.ts`. At most 20 run, and the report shows "20 of N" when it caps them.
+3. **Positive control.** The selected tests must first pass on the unedited file; if they don't, the file is reported as `failed`. Then the script prepends `throw new Error('mutation-report positive control')` to the file and runs the same tests, which must fail with that message. If they don't, the tests reach the file only through a spawned process, and every mutant would be a false survivor. The file is then reported as `control survived` and not mutated.
+4. It runs StrykerJS with the community Bun runner, using per-test coverage and `ignoreStatic`, within a 55-minute budget per file that also covers the two test runs before it (at most 10 minutes each). Stryker runs under `timeout`, which kills its whole process group at the budget, and the script then restores the tree with `git checkout -- .`. A file that runs out of budget is reported as `unfinished`. The report is rewritten after every file, so a job that hits its own limit still leaves the finished files.
+5. It writes a table (killed, survived, no coverage, timeout, mutation score) and up to 15 survivors per file, each with its line, mutator and replacement. The table goes to the step summary, and the Markdown, JSON and per-file Stryker reports go to the `mutation-report` artifact.
+
+Stryker (`@stryker-mutator/core`) and `@hughescr/stryker-bun-runner` are both Apache-2.0. They are installed at the exact versions in `STRYKER_PACKAGES` into the runner's temp directory with `--ignore-scripts`, so `package.json` and `bun.lock` don't change. Their own dependencies aren't locked.
+
+Stryker has to edit files in place, because its sandbox copy fails on this repo's symlinked directories (`EISDIR` on `connect-chrome`). The script therefore refuses a dirty tree, requires `--throwaway-checkout`, and must never run in a checkout you work in. If a run is killed, it can leave a mutated file behind: run `git checkout -- .` and remove `.stryker-tmp`. To run it locally, use a scratch worktree:
+
+```bash
+git worktree add /tmp/mut origin/main && cd /tmp/mut && bun install
+npm install --prefix /tmp/stryker --no-save --ignore-scripts @stryker-mutator/core@10.1.1 @hughescr/stryker-bun-runner@1.6.0
+bun --no-env-file --config=/dev/null scripts/mutation-report.ts --throwaway-checkout --files 1 \
+ --stryker-dir /tmp/stryker --out-dir /tmp/mutation-out
+```
+
## Cloud sandboxes (Vercel / Conductor cloud workspaces)
Syscall-supervised sandboxes need environment setup before `bun run test` can
diff --git a/scripts/harness-pins/scripts/test-pr-profile.ts.json b/scripts/harness-pins/scripts/test-pr-profile.ts.json
index 24141a1a9..ee85d1df3 100644
--- a/scripts/harness-pins/scripts/test-pr-profile.ts.json
+++ b/scripts/harness-pins/scripts/test-pr-profile.ts.json
@@ -1 +1 @@
-{"blob":"16093cf648950c2a863689e261ea2d06279a8740","since":7,"nonBehavioral":"GST-3440 adds scripts/free-test-durations-windows.json to FREE_ONLY_PR_FILES in scripts/test-pr-profile.ts: the Windows duration seed is read only by the free Windows shard plan, so it only stops a seed refresh from selecting paid cases; no paid case's selection, prompt, threshold, samples or verdict can change"}
+{"blob":"9384e521785e31e99eae4c0f126f67bb2d174260","since":7,"nonBehavioral":"GST-3386 adds .github/workflows/mutation-report.yml to FREE_ONLY_PR_FILES in scripts/test-pr-profile.ts: the new workflow is a weekly report-only job on main, so it only classifies that file as free-lane in the workflow inventory; no paid case's selection, prompt, threshold, samples or verdict can change"}
diff --git a/scripts/mutation-report.ts b/scripts/mutation-report.ts
new file mode 100755
index 000000000..55b445805
--- /dev/null
+++ b/scripts/mutation-report.ts
@@ -0,0 +1,217 @@
+#!/usr/bin/env -S bun --no-env-file --config=/dev/null
+/**
+ * mutation-report — the weekly, report-only mutation trial (docs/TESTING_INTERNALS.md#mutation-report).
+ * StrykerJS plants small wrong edits (mutants) in the lib files with the most landings on main in the last
+ * 30 days (a file no test imports, or with nothing to mutate, is listed and the next one takes its place) and runs the tests
+ * that import each file; a mutant no test fails on "survived" and is listed in the report. Nothing here
+ * gates a merge: the script exits 0 whatever it finds, and 1 only when it cannot run.
+ *
+ * bun scripts/mutation-report.ts --throwaway-checkout --stryker-dir
--out-dir
+ * [--files N | --only lib/.ts] [--since-days N] [--file-budget-min N] [--concurrency N] [--summary-file ]
+ *
+ * Stryker mutates files IN PLACE (its sandbox copy cannot follow this repo's symlinked directories),
+ * so the script refuses a dirty tree and needs --throwaway-checkout; it restores the tree with git after
+ * every file. --stryker-dir holds the exact-pinned install below (npm install --prefix, never package.json).
+ *
+ * Before Stryker runs on a file, the selected tests must pass unedited; then a positive control plants a
+ * throw at the top of the file and the same tests must fail with that throw's message. If they don't, the
+ * tests never load the file in-process (for example they only spawn it), every mutant would show as a
+ * false survivor, and the file is reported as "control survived" without a mutation run. Stryker runs
+ * under `timeout`, which kills its whole process group at the file budget, and the report is rewritten
+ * after every file so a job that hits its own limit still leaves the finished files.
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { spawnSync } from '../lib/spawn-sync';
+import { buildGraph, isTestFile, testsFor } from '../lib/pregate/import-graph';
+
+export const STRYKER_PACKAGES = ['@stryker-mutator/core@10.1.1', '@hughescr/stryker-bun-runner@1.6.0'];
+export const CONTROL_MESSAGE = 'mutation-report positive control';
+export const CONTROL_LINE = `throw new Error('${CONTROL_MESSAGE}');\n`;
+const CONTROL_MS = 10 * 60_000;
+const FREE_TEST_TIMEOUT_MS = 30_000;
+const MAX_TESTS = 20;
+const SURVIVORS_SHOWN = 15;
+
+export interface Churn { file: string; commits: number }
+export interface Mutant { id?: string; mutatorName: string; replacement?: string; status: string; location: { start: { line: number; column: number } } }
+export interface FileResult {
+ file: string; commits: number; tests: string[]; testsFound: number; testSource: 'direct' | 'transitive' | 'none';
+ outcome: 'scored' | 'no tests' | 'no mutants' | 'control survived' | 'unfinished' | 'failed';
+ detail?: string; counts?: Record; score?: number; survivors?: Mutant[]; minutes?: number;
+}
+
+/** Rank existing, non-test lib TypeScript files by landings in `git log --first-parent --format= --name-only` output. */
+export function rankChurn(nameLog: string, exists: (file: string) => boolean, n: number): Churn[] {
+ const counts = new Map();
+ for (const line of nameLog.split('\n')) {
+ const f = line.trim();
+ if (!/^lib\/.+\.ts$/.test(f) || f.endsWith('.d.ts') || isTestFile(f)) continue;
+ counts.set(f, (counts.get(f) ?? 0) + 1);
+ }
+ return [...counts].filter(([f]) => exists(f)).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .slice(0, n).map(([file, commits]) => ({ file, commits }));
+}
+
+export function plantControl(source: string): string { return CONTROL_LINE + source; }
+
+/** Stryker's mutation score: detected (killed, timeout) over detected plus undetected (survived, no coverage). */
+export function summarize(mutants: Mutant[]): { counts: Record; score: number | undefined; survivors: Mutant[] } {
+ const counts: Record = {};
+ for (const m of mutants) counts[m.status] = (counts[m.status] ?? 0) + 1;
+ const detected = (counts.Killed ?? 0) + (counts.Timeout ?? 0);
+ const undetected = (counts.Survived ?? 0) + (counts.NoCoverage ?? 0);
+ const survivors = mutants.filter(m => m.status === 'Survived')
+ .sort((a, b) => a.location.start.line - b.location.start.line || a.location.start.column - b.location.start.column);
+ return { counts, score: detected + undetected ? detected / (detected + undetected) : undefined, survivors };
+}
+
+const cell = (s: string) => '`' + s.replace(/\s+/g, ' ').slice(0, 80).replace(/[^\x20-\x7e]/g, '?').replace(/[`|]/g, '?') + '`';
+
+export function renderMarkdown(results: FileResult[], meta: { sinceDays: number; head: string; packages: string[] }): string {
+ const lines = [
+ '## Mutation report (report-only)', '',
+ `The lib files with the most landings in the last ${meta.sinceDays} days at ${meta.head.slice(0, 12)}; ${meta.packages.join(', ')}. A file no test imports ("no tests") or with nothing to mutate ("no mutants") is listed and the next file takes its place; at most ${MAX_TESTS} test files run per file.`,
+ 'A survivor is a small wrong edit that every selected test still passed. Nothing here blocks a merge.', '',
+ '| file | landings | tests | outcome | killed | survived | no coverage | timeout | score | minutes |',
+ '|---|---|---|---|---|---|---|---|---|---|',
+ ];
+ for (const r of results) {
+ const c = r.counts ?? {};
+ const n = (k: string) => (r.counts ? String(c[k] ?? 0) : '-');
+ lines.push(`| ${cell(r.file)} | ${r.commits} | ${r.tests.length}${r.testsFound > r.tests.length ? ` of ${r.testsFound}` : ''} (${r.testSource}) | ${r.outcome}${r.detail ? ': ' + r.detail.replace(/[|\n]/g, ' ').slice(0, 120) : ''} | ${n('Killed')} | ${n('Survived')} | ${n('NoCoverage')} | ${n('Timeout')} | ${r.score === undefined ? '-' : (r.score * 100).toFixed(1) + '%'} | ${r.minutes ?? '-'} |`);
+ }
+ for (const r of results) {
+ if (!r.survivors?.length) continue;
+ lines.push('', `### Survivors in ${cell(r.file)} (${r.survivors.length}${r.survivors.length > SURVIVORS_SHOWN ? `, first ${SURVIVORS_SHOWN} by line` : ''})`, '');
+ for (const m of r.survivors.slice(0, SURVIVORS_SHOWN))
+ lines.push(`- line ${m.location.start.line}: ${m.mutatorName}${m.replacement === undefined ? '' : ' → ' + cell(m.replacement)}`);
+ }
+ return lines.join('\n') + '\n';
+}
+
+function fail(msg: string): never {
+ process.stderr.write(`mutation-report: ${msg}\n`);
+ process.exit(1);
+}
+
+function git(args: string[]): string {
+ const r = spawnSync('git', args, { encoding: 'utf-8', timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
+ if (r.error || r.status !== 0) fail(`git ${args[0]} failed: ${r.error?.message ?? (r.stderr ?? '').trim().slice(0, 300)}`);
+ return r.stdout;
+}
+
+function restoreTree(): void {
+ git(['checkout', '--', '.']);
+ fs.rmSync('.stryker-tmp', { recursive: true, force: true });
+ if (git(['status', '--porcelain', '--untracked-files=no']).trim()) fail('the tree is still dirty after restoring it; stopping');
+}
+
+function selectTests(graph: ReturnType, file: string): Pick {
+ const direct = [...new Set((graph.reverse.get(file) ?? []).map(e => e.from).filter(f => graph.tests.has(f) && f.startsWith('test/')))].sort();
+ const found = direct.length ? direct : testsFor(graph, file).tests.filter(f => f.startsWith('test/')).sort();
+ return { tests: found.slice(0, MAX_TESTS), testsFound: found.length, testSource: direct.length ? 'direct' : found.length ? 'transitive' : 'none' };
+}
+
+function runTests(tests: string[], deadline: number) {
+ return spawnSync(process.execPath, ['test', ...tests.map(t => './' + t), `--timeout=${FREE_TEST_TIMEOUT_MS}`],
+ { encoding: 'utf-8', timeout: Math.max(1_000, Math.min(CONTROL_MS, deadline - Date.now())), maxBuffer: 256 * 1024 * 1024 });
+}
+
+function mutateFile(c: Churn, sel: Pick, o: { strykerDir: string; outDir: string; budgetMs: number; concurrency: number }): FileResult {
+ const started = Date.now();
+ const deadline = started + o.budgetMs;
+ const base: FileResult = { ...c, ...sel, outcome: 'failed' };
+ const baseline = runTests(sel.tests, deadline);
+ if (baseline.error) return { ...base, outcome: 'unfinished', detail: `the selected tests did not finish unedited: ${baseline.error.message}` };
+ if (baseline.status !== 0) return { ...base, detail: `the selected tests fail before any edit (exit ${baseline.status})` };
+ fs.writeFileSync(c.file, plantControl(fs.readFileSync(c.file, 'utf-8')));
+ const control = runTests(sel.tests, deadline);
+ restoreTree();
+ if (control.error) return { ...base, detail: `positive control did not finish: ${control.error.message}` };
+ if (control.status === 0 || !`${control.stdout}${control.stderr}`.includes(CONTROL_MESSAGE))
+ return { ...base, outcome: 'control survived', detail: 'the selected tests did not fail on the planted throw' };
+
+ const slug = c.file.replace(/[^a-zA-Z0-9]+/g, '-');
+ const reportFile = path.join(o.outDir, `${slug}.json`);
+ const configFile = path.join(o.outDir, `${slug}.stryker.json`);
+ fs.writeFileSync(configFile, JSON.stringify({
+ appendPlugins: [path.join(o.strykerDir, 'node_modules/@hughescr/stryker-bun-runner/dist/index.js')],
+ testRunner: 'bun', mutate: [c.file], inPlace: true, ignoreStatic: true,
+ bun: { testFiles: sel.tests, timeout: 60_000 },
+ reporters: ['progress-append-only', 'json'], jsonReporter: { fileName: reportFile },
+ concurrency: o.concurrency, timeoutMS: 30_000, tempDirName: '.stryker-tmp',
+ }, null, 2));
+ const budgetS = Math.round((deadline - Date.now()) / 1000);
+ if (budgetS < 60) return { ...base, outcome: 'unfinished', detail: `the controls used the ${Math.round(o.budgetMs / 60_000)}-minute file budget` };
+ const run = spawnSync('timeout', ['--kill-after=60', String(budgetS), 'node', path.join(o.strykerDir, 'node_modules/@stryker-mutator/core/bin/stryker.js'), 'run', configFile],
+ { encoding: 'utf-8', timeout: (budgetS + 120) * 1000, maxBuffer: 512 * 1024 * 1024 });
+ fs.writeFileSync(path.join(o.outDir, `${slug}.log`), (run.stdout ?? '') + (run.stderr ?? ''));
+ restoreTree();
+ const minutes = Math.round((Date.now() - started) / 60_000);
+ if (run.status === 124 || run.status === 137) return { ...base, outcome: 'unfinished', detail: `stopped at the ${Math.round(o.budgetMs / 60_000)}-minute file budget`, minutes };
+ if (run.error || run.status !== 0 || !fs.existsSync(reportFile))
+ return { ...base, detail: `stryker ${run.error ? run.error.message : `exit ${run.status}`}: ${(run.stderr || run.stdout || '').trim().split('\n').pop()}`, minutes };
+ let mutants: Mutant[];
+ try {
+ mutants = Object.values((JSON.parse(fs.readFileSync(reportFile, 'utf-8')) as { files: Record }).files).flatMap(f => f.mutants);
+ } catch (error) {
+ return { ...base, detail: `unreadable Stryker report: ${String(error).slice(0, 120)}`, minutes };
+ }
+ if (!mutants.length) return { ...base, outcome: 'no mutants', detail: 'Stryker found nothing to mutate (a data-only file)', minutes };
+ return { ...base, outcome: 'scored', ...summarize(mutants), minutes };
+}
+
+function arg(argv: string[], name: string): string | undefined {
+ const i = argv.indexOf(name);
+ if (i === -1) return undefined;
+ const v = argv[i + 1];
+ if (!v || v.startsWith('--')) fail(`${name} needs a value`);
+ return v;
+}
+
+function intArg(argv: string[], name: string, fallback: number): number {
+ const v = arg(argv, name);
+ if (v === undefined) return fallback;
+ if (!/^[1-9]\d*$/.test(v)) fail(`${name} must be a positive integer`);
+ return Number(v);
+}
+
+if (import.meta.main) {
+ const argv = process.argv.slice(2);
+ if (!argv.includes('--throwaway-checkout')) fail('Stryker edits files in place; pass --throwaway-checkout and run only in a disposable checkout');
+ const strykerDir = arg(argv, '--stryker-dir'), outDir = arg(argv, '--out-dir'), summaryFile = arg(argv, '--summary-file'), only = arg(argv, '--only');
+ if (!strykerDir || !outDir) fail('--stryker-dir and --out-dir are required');
+ const files = intArg(argv, '--files', 5), sinceDays = intArg(argv, '--since-days', 30);
+ const budgetMs = intArg(argv, '--file-budget-min', 55) * 60_000, concurrency = intArg(argv, '--concurrency', 4);
+ process.chdir(git(['rev-parse', '--show-toplevel']).trim());
+ if (git(['status', '--porcelain', '--untracked-files=no']).trim()) fail('the checkout has uncommitted changes; use a clean disposable checkout');
+ const resolvedOut = path.resolve(outDir);
+ const rel = path.relative(process.cwd(), resolvedOut);
+ if (!path.isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + path.sep)) fail('--out-dir must be outside the checkout');
+ fs.mkdirSync(resolvedOut, { recursive: true });
+ const head = git(['rev-parse', 'HEAD']).trim();
+ const ranked = rankChurn(git(['log', '--first-parent', `--since=${sinceDays} days ago`, '--format=', '--name-only', 'HEAD', '--', 'lib']), f => fs.existsSync(f), Number.MAX_SAFE_INTEGER);
+ const churn = only ? ranked.filter(c => c.file === only) : ranked;
+ if (only && !churn.length) fail(`--only ${only} is not a lib file landed in the last ${sinceDays} days`);
+ if (!churn.length) fail(`no lib files landed in the last ${sinceDays} days (is this a shallow clone?)`);
+ const graph = buildGraph(process.cwd());
+ const results: FileResult[] = [];
+ const write = () => {
+ const md = renderMarkdown(results, { sinceDays, head, packages: STRYKER_PACKAGES });
+ fs.writeFileSync(path.join(resolvedOut, 'mutation-report.md'), md);
+ fs.writeFileSync(path.join(resolvedOut, 'mutation-report.json'), JSON.stringify({ head, sinceDays, packages: STRYKER_PACKAGES, results }, null, 2));
+ return md;
+ };
+ for (const c of churn) {
+ if (results.filter(r => r.outcome !== 'no tests' && r.outcome !== 'no mutants').length >= files) break;
+ const sel = selectTests(graph, c.file);
+ const r = sel.tests.length ? mutateFile(c, sel, { strykerDir: path.resolve(strykerDir), outDir: resolvedOut, budgetMs, concurrency }) : { ...c, ...sel, outcome: 'no tests' as const };
+ results.push(r);
+ write();
+ process.stdout.write(`MUTATION_FILE: file=${r.file} outcome=${r.outcome.replace(/ /g, '_')} tests=${r.tests.length} survived=${r.counts?.Survived ?? '-'} score=${r.score === undefined ? '-' : r.score.toFixed(3)}\n`);
+ }
+ const md = write();
+ if (summaryFile) fs.appendFileSync(summaryFile, md);
+ process.stdout.write(md);
+}
diff --git a/scripts/test-pr-profile.ts b/scripts/test-pr-profile.ts
index 16093cf64..9384e5217 100644
--- a/scripts/test-pr-profile.ts
+++ b/scripts/test-pr-profile.ts
@@ -280,6 +280,7 @@ export const FREE_ONLY_PR_FILES = [
'.github/workflows/make-pdf-gate.yml',
'.github/workflows/model-policy-freshness.yml',
'.github/workflows/measure-journal-read.yml',
+ '.github/workflows/mutation-report.yml', // The weekly report-only mutation trial on main; no paid case reads it, and it never gates a PR.
'.github/workflows/native-qualification.yml',
'.github/workflows/osv-scanner.yml',
'.github/workflows/platform-qualification.yml',
diff --git a/test/mutation-report.test.ts b/test/mutation-report.test.ts
new file mode 100644
index 000000000..ef309777f
--- /dev/null
+++ b/test/mutation-report.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { CONTROL_LINE, CONTROL_MESSAGE, STRYKER_PACKAGES, plantControl, rankChurn, renderMarkdown, summarize, type Mutant } from '../scripts/mutation-report';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const mutant = (status: string, line: number, replacement = 'false'): Mutant => ({ mutatorName: 'BooleanLiteral', replacement, status, location: { start: { line, column: 1 } } });
+
+describe('mutation-report', () => {
+ test('ranks existing non-test lib files by landings', () => {
+ const log = ['lib/a.ts', 'lib/b.ts', '', 'lib/a.ts', 'lib/gone.ts', 'lib/gone.ts', 'lib/gone.ts', 'test/a.test.ts', 'lib/x.test.ts', 'lib/types.d.ts', 'bin/tool', 'lib/b.ts', 'lib/c.ts'].join('\n');
+ expect(rankChurn(log, f => f !== 'lib/gone.ts', 2)).toEqual([{ file: 'lib/a.ts', commits: 2 }, { file: 'lib/b.ts', commits: 2 }]);
+ });
+
+ test('the positive control throws before the file body runs', () => {
+ expect(plantControl('export const x = 1;\n')).toBe(CONTROL_LINE + 'export const x = 1;\n');
+ expect(CONTROL_LINE).toBe(`throw new Error('${CONTROL_MESSAGE}');\n`);
+ });
+
+ test('scores killed and timed-out mutants against survivors and uncovered ones', () => {
+ const s = summarize([mutant('Killed', 3), mutant('Timeout', 4), mutant('Survived', 9), mutant('Survived', 2), mutant('NoCoverage', 5), mutant('Ignored', 6)]);
+ expect(s.counts).toEqual({ Killed: 1, Timeout: 1, Survived: 2, NoCoverage: 1, Ignored: 1 });
+ expect(s.score).toBeCloseTo(2 / 5);
+ expect(s.survivors.map(m => m.location.start.line)).toEqual([2, 9]);
+ expect(summarize([mutant('Ignored', 1)]).score).toBeUndefined();
+ });
+
+ test('renders a table row per file and escapes mutant text', () => {
+ const md = renderMarkdown([
+ { file: 'lib/a.ts', commits: 7, tests: ['test/a.test.ts'], testsFound: 1, testSource: 'direct', outcome: 'scored', ...summarize([mutant('Killed', 1), mutant('Survived', 2, 'a | `b`')]), minutes: 3 },
+ { file: 'lib/b.ts', commits: 5, tests: ['test/b.test.ts'], testsFound: 1, testSource: 'direct', outcome: 'control survived', detail: 'the selected tests did not fail on the planted throw' },
+ { file: 'lib/c.ts', commits: 4, tests: Array.from({ length: 20 }, (_, i) => `test/c${i}.test.ts`), testsFound: 31, testSource: 'transitive', outcome: 'unfinished', detail: 'stopped at the 45-minute file budget', minutes: 46 },
+ ], { sinceDays: 90, head: 'abcdef0123456789', packages: STRYKER_PACKAGES });
+ expect(md).toContain('| `lib/a.ts` | 7 | 1 (direct) | scored | 1 | 1 | 0 | 0 | 50.0% | 3 |');
+ expect(md).toContain('| `lib/b.ts` | 5 | 1 (direct) | control survived: the selected tests did not fail on the planted throw | - | - | - | - | - | - |');
+ expect(md).toContain('| `lib/c.ts` | 4 | 20 of 31 (transitive) | unfinished: stopped at the 45-minute file budget | - | - | - | - | - | 46 |');
+ expect(md).toContain('- line 2: BooleanLiteral → `a ? ?b?`');
+ });
+
+ test('pins Stryker and its runner to exact versions', () => {
+ for (const p of STRYKER_PACKAGES) expect(p).toMatch(/^@[a-z-]+\/[a-z-]+@\d+\.\d+\.\d+$/);
+ });
+
+ test('refuses to run without --throwaway-checkout', () => {
+ const r = spawnSync(process.execPath, ['--no-env-file', '--config=/dev/null', path.join(ROOT, 'scripts/mutation-report.ts'), '--stryker-dir', '/nonexistent', '--out-dir', '/nonexistent'], { encoding: 'utf-8', timeout: 30_000 });
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('--throwaway-checkout');
+ });
+
+ test('the workflow is scheduled, read-only and never runs on pull requests', () => {
+ const wf = fs.readFileSync(path.join(ROOT, '.github/workflows/mutation-report.yml'), 'utf-8');
+ expect(wf).toMatch(/^on:\n schedule:\n/m);
+ expect(wf).toContain('workflow_dispatch:');
+ expect(wf).not.toMatch(/pull_request|push:/);
+ expect(wf).toMatch(/^permissions:\n contents: read\n/m);
+ expect(wf).toMatch(/persist-credentials[:] false/);
+ expect(wf).toContain('--throwaway-checkout');
+ expect(wf).not.toContain('secrets.');
+ });
+});