@fairfox/polly 0.90.0 → 0.92.0

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.
Files changed (107) hide show
  1. package/dist/cli/polly.js +3 -3
  2. package/dist/cli/polly.js.map +3 -3
  3. package/dist/gallery/gallery.css +2 -2
  4. package/dist/gallery/gallery.js +248 -241
  5. package/dist/src/background/index.js +27 -11
  6. package/dist/src/background/index.js.map +2 -2
  7. package/dist/src/background/message-router.js +27 -11
  8. package/dist/src/background/message-router.js.map +2 -2
  9. package/dist/src/client/index.js +56 -56
  10. package/dist/src/client/index.js.map +4 -4
  11. package/dist/src/elysia/index.js +6 -6
  12. package/dist/src/elysia/index.js.map +3 -3
  13. package/dist/src/index.js +51 -23
  14. package/dist/src/index.js.map +3 -3
  15. package/dist/src/mesh.js +2 -2
  16. package/dist/src/mesh.js.map +3 -3
  17. package/dist/src/peer.js +6 -6
  18. package/dist/src/peer.js.map +3 -3
  19. package/dist/src/polly-ui/index.css +2 -2
  20. package/dist/src/polly-ui/markdown.js +1844 -1010
  21. package/dist/src/polly-ui/markdown.js.map +5 -5
  22. package/dist/src/polly-ui/styles.css +2 -2
  23. package/dist/src/shared/adapters/index.js +27 -11
  24. package/dist/src/shared/adapters/index.js.map +2 -2
  25. package/dist/src/shared/lib/context-helpers.js +27 -11
  26. package/dist/src/shared/lib/context-helpers.js.map +2 -2
  27. package/dist/src/shared/lib/message-bus.js +27 -11
  28. package/dist/src/shared/lib/message-bus.js.map +2 -2
  29. package/dist/src/shared/lib/resource.js +41 -13
  30. package/dist/src/shared/lib/resource.js.map +3 -3
  31. package/dist/src/shared/lib/state.js +41 -13
  32. package/dist/src/shared/lib/state.js.map +3 -3
  33. package/dist/src/shared/state/app-state.js +41 -13
  34. package/dist/src/shared/state/app-state.js.map +3 -3
  35. package/dist/tools/bdd/src/cli.js +20 -2
  36. package/dist/tools/bdd/src/cli.js.map +4 -4
  37. package/dist/tools/bdd/src/index.js +20 -2
  38. package/dist/tools/bdd/src/index.js.map +3 -3
  39. package/dist/tools/init/templates/pwa/package.json.template +2 -3
  40. package/dist/tools/mutate/src/args.d.ts +25 -3
  41. package/dist/tools/mutate/src/cli.js +3234 -312
  42. package/dist/tools/mutate/src/cli.js.map +32 -12
  43. package/dist/tools/mutate/src/config.d.ts +13 -2
  44. package/dist/tools/mutate/src/define.d.ts +76 -0
  45. package/dist/tools/mutate/src/engine/ast.d.ts +13 -0
  46. package/dist/tools/mutate/src/engine/baseline.d.ts +20 -0
  47. package/dist/tools/mutate/src/engine/cache.d.ts +32 -0
  48. package/dist/tools/mutate/src/engine/coverage.d.ts +60 -0
  49. package/dist/tools/mutate/src/engine/generate.d.ts +23 -0
  50. package/dist/tools/mutate/src/engine/graph.d.ts +11 -0
  51. package/dist/tools/mutate/src/engine/index.d.ts +16 -0
  52. package/dist/tools/mutate/src/engine/junit.d.ts +38 -0
  53. package/dist/tools/mutate/src/engine/operators.d.ts +14 -0
  54. package/dist/tools/mutate/src/engine/preload.d.ts +10 -0
  55. package/dist/tools/mutate/src/engine/preload.js +180 -0
  56. package/dist/tools/mutate/src/engine/preload.js.map +10 -0
  57. package/dist/tools/mutate/src/engine/probes.d.ts +12 -0
  58. package/dist/tools/mutate/src/engine/report-writer.d.ts +44 -0
  59. package/dist/tools/mutate/src/engine/runner.d.ts +31 -0
  60. package/dist/tools/mutate/src/engine/stray-writes.d.ts +25 -0
  61. package/dist/tools/mutate/src/engine/typecheck.d.ts +37 -0
  62. package/dist/tools/mutate/src/engine/types.d.ts +191 -0
  63. package/dist/tools/mutate/src/engine/verify-callsites.d.ts +9 -0
  64. package/dist/tools/mutate/src/engine/workdir.d.ts +16 -0
  65. package/dist/tools/mutate/src/engine-config.d.ts +7 -0
  66. package/dist/tools/mutate/src/index.d.ts +7 -3
  67. package/dist/tools/mutate/src/index.js +2701 -77
  68. package/dist/tools/mutate/src/index.js.map +26 -7
  69. package/dist/tools/mutate/src/ingest.d.ts +30 -1
  70. package/dist/tools/mutate/src/init.d.ts +2 -1
  71. package/dist/tools/mutate/src/migrate.d.ts +32 -0
  72. package/dist/tools/mutate/src/report.d.ts +3 -0
  73. package/dist/tools/mutate/src/run.d.ts +17 -8
  74. package/dist/tools/mutate/src/verify-matrix.d.ts +12 -15
  75. package/dist/tools/quality/src/cli.js +9 -9
  76. package/dist/tools/quality/src/cli.js.map +4 -4
  77. package/dist/tools/quality/src/index.js +9 -9
  78. package/dist/tools/quality/src/index.js.map +4 -4
  79. package/dist/tools/quality/src/no-tautology-ensures.d.ts +2 -2
  80. package/dist/tools/quality/src/plugins/import-checks.d.ts +1 -1
  81. package/dist/tools/test/src/adapters/index.js +3 -2
  82. package/dist/tools/test/src/adapters/index.js.map +3 -3
  83. package/dist/tools/test/src/coverage-policy/cli.d.ts +2 -2
  84. package/dist/tools/test/src/coverage-policy/cli.js +217 -17
  85. package/dist/tools/test/src/coverage-policy/cli.js.map +7 -5
  86. package/dist/tools/test/src/coverage-policy/index.d.ts +1 -1
  87. package/dist/tools/test/src/coverage-policy/index.js +213 -12
  88. package/dist/tools/test/src/coverage-policy/index.js.map +7 -5
  89. package/dist/tools/test/src/coverage-policy/mutate-targets.d.ts +29 -12
  90. package/dist/tools/test/src/e2e-mesh/index.js +6 -6
  91. package/dist/tools/test/src/e2e-mesh/index.js.map +4 -4
  92. package/dist/tools/test/src/e2e-relay/index.js +230 -226
  93. package/dist/tools/test/src/e2e-relay/index.js.map +7 -7
  94. package/dist/tools/test/src/index.js +3 -2
  95. package/dist/tools/test/src/index.js.map +3 -3
  96. package/dist/tools/test/src/visual/index.js +684 -511
  97. package/dist/tools/test/src/visual/index.js.map +11 -11
  98. package/dist/tools/verify/src/cli.js +294 -21
  99. package/dist/tools/verify/src/cli.js.map +9 -9
  100. package/dist/tools/verify/src/config.d.ts +57 -1
  101. package/dist/tools/verify/src/config.js +68 -3
  102. package/dist/tools/verify/src/config.js.map +4 -4
  103. package/dist/tools/verify/src/primitives/index.d.ts +34 -0
  104. package/package.json +30 -39
  105. package/dist/tools/verify/src/stryker/index.d.ts +0 -32
  106. package/dist/tools/verify/src/stryker/index.js +0 -86
  107. package/dist/tools/verify/src/stryker/index.js.map +0 -10
@@ -1,8 +1,272 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
+ // tools/mutate/src/cli.ts
4
+ import { resolve as resolve5 } from "node:path";
5
+
6
+ // tools/test/src/coverage-policy/mutate-targets.ts
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { Glob } from "bun";
10
+
11
+ // src/shared/lib/guards.ts
12
+ function isRecord(input) {
13
+ return typeof input === "object" && input !== null && !Array.isArray(input);
14
+ }
15
+
16
+ // tools/mutate/src/define.ts
17
+ var MUTATION_CONFIG_FILE = "polly.mutate.ts";
18
+ function defineMutation(config) {
19
+ return config;
20
+ }
21
+ var MUTATOR_NAMES = new Set([
22
+ "ArithmeticOperator",
23
+ "ArrayDeclaration",
24
+ "ArrowFunction",
25
+ "AssignmentOperator",
26
+ "BlockStatement",
27
+ "BooleanLiteral",
28
+ "ConditionalExpression",
29
+ "EqualityOperator",
30
+ "LogicalOperator",
31
+ "MethodExpression",
32
+ "ObjectLiteral",
33
+ "OptionalChaining",
34
+ "Regex",
35
+ "StringLiteral",
36
+ "UnaryOperator",
37
+ "UpdateOperator"
38
+ ]);
39
+ function isMutatorName(value) {
40
+ return typeof value === "string" && MUTATOR_NAMES.has(value);
41
+ }
42
+ function strings(value, where) {
43
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
44
+ throw new Error(`${where} must be an array of strings`);
45
+ }
46
+ return value;
47
+ }
48
+ function optionalNumber(value, where) {
49
+ if (value === undefined)
50
+ return;
51
+ if (typeof value !== "number" || !Number.isFinite(value))
52
+ throw new Error(`${where} must be a number`);
53
+ return value;
54
+ }
55
+ function optionalString(value, where) {
56
+ if (value === undefined)
57
+ return;
58
+ if (typeof value !== "string")
59
+ throw new Error(`${where} must be a string`);
60
+ return value;
61
+ }
62
+ function isEngineMode(v) {
63
+ return v === "fast" || v === "matrix";
64
+ }
65
+ function isCoverageMode(v) {
66
+ return v === "dynamic" || v === "static";
67
+ }
68
+ function parseRun(raw, where) {
69
+ const mode = raw["mode"];
70
+ if (mode !== undefined && !isEngineMode(mode)) {
71
+ throw new Error(`${where}: mode must be "fast" or "matrix"`);
72
+ }
73
+ const concurrency = optionalNumber(raw["concurrency"], `${where}: concurrency`);
74
+ if (concurrency !== undefined && !(Number.isInteger(concurrency) && concurrency > 0)) {
75
+ throw new Error(`${where}: concurrency must be a positive integer`);
76
+ }
77
+ const coverage = raw["coverage"];
78
+ if (coverage !== undefined && !isCoverageMode(coverage)) {
79
+ throw new Error(`${where}: coverage must be "dynamic" or "static"`);
80
+ }
81
+ const common = { targets: strings(raw["targets"], `${where}: targets`) };
82
+ if (isEngineMode(mode))
83
+ common.mode = mode;
84
+ if (isCoverageMode(coverage))
85
+ common.coverage = coverage;
86
+ if (concurrency !== undefined)
87
+ common.concurrency = concurrency;
88
+ const timeout = raw["timeout"];
89
+ if (timeout !== undefined) {
90
+ if (!isRecord(timeout))
91
+ throw new Error(`${where}: timeout must be { factor, extraMs }`);
92
+ const factor = optionalNumber(timeout["factor"], `${where}: timeout.factor`) ?? 2;
93
+ const extraMs = optionalNumber(timeout["extraMs"], `${where}: timeout.extraMs`) ?? 3000;
94
+ common.timeout = { factor, extraMs };
95
+ }
96
+ return common;
97
+ }
98
+ function parseMutants(raw, where) {
99
+ const out = {};
100
+ const mutators = raw["mutators"];
101
+ if (mutators !== undefined) {
102
+ if (!isRecord(mutators))
103
+ throw new Error(`${where}: mutators must be { exclude }`);
104
+ const exclude = mutators["exclude"] === undefined ? [] : mutators["exclude"];
105
+ if (!Array.isArray(exclude) || !exclude.every(isMutatorName)) {
106
+ throw new Error(`${where}: mutators.exclude holds an unknown mutator name`);
107
+ }
108
+ out.mutators = { exclude };
109
+ }
110
+ const ignore = raw["ignoreVerifyCallsites"];
111
+ if (ignore !== undefined) {
112
+ if (typeof ignore !== "boolean")
113
+ throw new Error(`${where}: ignoreVerifyCallsites must be boolean`);
114
+ out.ignoreVerifyCallsites = ignore;
115
+ }
116
+ const typecheck = raw["typecheck"];
117
+ if (typecheck !== undefined) {
118
+ if (typeof typecheck !== "boolean")
119
+ throw new Error(`${where}: typecheck must be boolean`);
120
+ out.typecheck = typecheck;
121
+ }
122
+ return { ...out, ...parseContracts(raw, where) };
123
+ }
124
+ function isContractsMode(v) {
125
+ return v === "off" || v === "ensures" || v === "all";
126
+ }
127
+ function parseContracts(raw, where) {
128
+ const contracts = raw["contracts"];
129
+ if (contracts === undefined)
130
+ return {};
131
+ if (!isContractsMode(contracts)) {
132
+ throw new Error(`${where}: contracts must be "off", "ensures" or "all"`);
133
+ }
134
+ return { contracts };
135
+ }
136
+ function parseOutputs(raw, where) {
137
+ const out = {};
138
+ const thresholds = raw["thresholds"];
139
+ if (thresholds !== undefined) {
140
+ if (!isRecord(thresholds))
141
+ throw new Error(`${where}: thresholds must be { break }`);
142
+ const brk = optionalNumber(thresholds["break"], `${where}: thresholds.break`);
143
+ out.thresholds = brk === undefined ? {} : { break: brk };
144
+ }
145
+ const report = optionalString(raw["report"], `${where}: report`);
146
+ if (report !== undefined)
147
+ out.report = report;
148
+ const decisions = optionalString(raw["decisions"], `${where}: decisions`);
149
+ if (decisions !== undefined)
150
+ out.decisions = decisions;
151
+ return out;
152
+ }
153
+ function parseCommon(raw, where) {
154
+ return { ...parseRun(raw, where), ...parseMutants(raw, where), ...parseOutputs(raw, where) };
155
+ }
156
+ function parseMutationConfig(raw, where) {
157
+ if (!isRecord(raw))
158
+ throw new Error(`${where}: the default export must be a config object`);
159
+ const { targets, ...common } = parseCommon(raw, where);
160
+ const runner = raw["runner"];
161
+ if (isRecord(runner) && runner["kind"] === "command") {
162
+ const argv = strings(runner["argv"], `${where}: runner.argv`);
163
+ if (argv.length === 0)
164
+ throw new Error(`${where}: runner.argv is empty`);
165
+ return { targets, runner: { kind: "command", argv }, ...common };
166
+ }
167
+ if (runner !== undefined && !(isRecord(runner) && runner["kind"] === "bun-test")) {
168
+ throw new Error(`${where}: runner.kind must be "bun-test" or "command"`);
169
+ }
170
+ const tests = raw["tests"];
171
+ if (!isRecord(tests))
172
+ throw new Error(`${where}: tests.include is required`);
173
+ const include = strings(tests["include"], `${where}: tests.include`);
174
+ if (include.length === 0)
175
+ throw new Error(`${where}: tests.include is empty`);
176
+ const preload = tests["preload"] === undefined ? undefined : strings(tests["preload"], `${where}: tests.preload`);
177
+ return { targets, tests: preload ? { include, preload } : { include }, ...common };
178
+ }
179
+ async function loadMutationConfig(path) {
180
+ const mod = await import(path);
181
+ const raw = isRecord(mod) ? mod["default"] : undefined;
182
+ return parseMutationConfig(raw, path);
183
+ }
184
+
185
+ // tools/test/src/coverage-policy/mutate-targets.ts
186
+ async function findStrykerConfigs(root) {
187
+ const found = [];
188
+ const single = join(root, "stryker.conf.json");
189
+ if (existsSync(single))
190
+ found.push(single);
191
+ const glob = new Glob("stryker/*.{json,conf.json}");
192
+ for await (const rel of glob.scan({ cwd: root, onlyFiles: true })) {
193
+ found.push(join(root, rel));
194
+ }
195
+ return found.sort();
196
+ }
197
+ async function findMutateConfigs(root) {
198
+ const out = [];
199
+ const polly = join(root, MUTATION_CONFIG_FILE);
200
+ if (existsSync(polly)) {
201
+ const config = await loadMutationConfig(polly);
202
+ out.push({
203
+ path: polly,
204
+ format: "polly",
205
+ targets: { field: "targets", patterns: config.targets },
206
+ tests: { field: "tests.include", patterns: config.tests?.include ?? [] }
207
+ });
208
+ }
209
+ for (const path of await findStrykerConfigs(root)) {
210
+ const config = JSON.parse(readFileSync(path, "utf8"));
211
+ out.push({
212
+ path,
213
+ format: "stryker",
214
+ targets: { field: "mutate", patterns: config.mutate ?? [] },
215
+ tests: { field: "testFiles", patterns: config.testFiles ?? config.bun?.testFiles ?? [] }
216
+ });
217
+ }
218
+ return out;
219
+ }
220
+ function isGlob(pattern) {
221
+ return pattern.includes("*") || pattern.includes("?") || pattern.includes("[");
222
+ }
223
+ var LINE_RANGE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
224
+ async function resolvesToFile(entry, cwd) {
225
+ if (entry.startsWith("!"))
226
+ return true;
227
+ const pattern = entry.replace(LINE_RANGE, "");
228
+ if (!isGlob(pattern))
229
+ return existsSync(resolve(cwd, pattern));
230
+ const glob = new Glob(pattern);
231
+ for await (const _ of glob.scan({ cwd, onlyFiles: true }))
232
+ return true;
233
+ return false;
234
+ }
235
+ async function checkField(configPath, field, patterns, cwd) {
236
+ const issues = [];
237
+ for (const pattern of patterns) {
238
+ if (!await resolvesToFile(pattern, cwd)) {
239
+ issues.push({ config: configPath, field, pattern });
240
+ }
241
+ }
242
+ return issues;
243
+ }
244
+ async function validateMutateTargets(root) {
245
+ const configs = await findMutateConfigs(root);
246
+ const issues = [];
247
+ for (const c of configs) {
248
+ const cwd = c.format === "polly" ? dirname(c.path) : root;
249
+ issues.push(...await checkField(c.path, c.targets.field, c.targets.patterns, cwd));
250
+ issues.push(...await checkField(c.path, c.tests.field, c.tests.patterns, cwd));
251
+ }
252
+ return { configs: configs.map((c) => c.path), issues };
253
+ }
254
+
3
255
  // tools/mutate/src/args.ts
4
- var KNOWN_VERBS = new Set(["run", "report", "decisions", "verify", "init", "help"]);
5
- var VALUE_FLAGS = new Set(["--config", "--report", "--decisions", "--db"]);
256
+ var KNOWN_VERBS = new Set(["run", "report", "decisions", "verify", "init", "migrate", "help"]);
257
+ var VALUE_FLAGS = new Set([
258
+ "--config",
259
+ "--report",
260
+ "--decisions",
261
+ "--db",
262
+ "--engine",
263
+ "--mode",
264
+ "--coverage",
265
+ "--concurrency",
266
+ "--files",
267
+ "--since",
268
+ "--contracts"
269
+ ]);
6
270
  function parseMutateArgs(argv) {
7
271
  const positionals = [];
8
272
  const flags = new Map;
@@ -36,79 +300,194 @@ function parseMutateArgs(argv) {
36
300
  noReport: bools.has("--no-report"),
37
301
  run: bools.has("--run"),
38
302
  force: bools.has("--force"),
39
- help
303
+ write: bools.has("--write"),
304
+ inTree: bools.has("--in-tree"),
305
+ noCache: bools.has("--no-cache"),
306
+ noTypecheck: bools.has("--no-typecheck"),
307
+ help,
308
+ engine: flags.get("--engine"),
309
+ mode: flags.get("--mode"),
310
+ coverage: flags.get("--coverage"),
311
+ concurrency: flags.get("--concurrency"),
312
+ files: flags.get("--files"),
313
+ since: flags.get("--since"),
314
+ contracts: flags.get("--contracts")
40
315
  };
41
316
  }
42
317
 
43
318
  // tools/mutate/src/config.ts
44
- import { resolve as resolve2 } from "node:path";
319
+ import { existsSync as existsSync3 } from "node:fs";
320
+ import { dirname as dirname3, resolve as resolve2 } from "node:path";
45
321
 
46
- // tools/test/src/coverage-policy/mutate-targets.ts
47
- import { existsSync, readFileSync } from "node:fs";
48
- import { join, resolve } from "node:path";
49
- import { Glob } from "bun";
50
- async function findStrykerConfigs(root) {
51
- const found = [];
52
- const single = join(root, "stryker.conf.json");
53
- if (existsSync(single))
54
- found.push(single);
55
- const glob = new Glob("stryker/*.{json,conf.json}");
56
- for await (const rel of glob.scan({ cwd: root, onlyFiles: true })) {
57
- found.push(join(root, rel));
58
- }
59
- return found.sort();
322
+ // tools/mutate/src/migrate.ts
323
+ import { existsSync as existsSync2 } from "node:fs";
324
+ import { dirname as dirname2, join as join2, relative } from "node:path";
325
+ var MAPPED = new Set([
326
+ "mutate",
327
+ "testRunner",
328
+ "bun",
329
+ "commandRunner",
330
+ "concurrency",
331
+ "timeoutFactor",
332
+ "timeoutMS",
333
+ "disableBail",
334
+ "mutator",
335
+ "thresholds",
336
+ "ignorers"
337
+ ]);
338
+ var SILENT = new Set(["$schema", "_comment"]);
339
+ var SHELL_SYNTAX = /[|&;<>()$`"'\\*?{}[\]~]/;
340
+ function preloadArgs(nodeArgs) {
341
+ const out = [];
342
+ nodeArgs.forEach((arg, i) => {
343
+ const value = arg === "--preload" ? nodeArgs[i + 1] : arg.startsWith("--preload=") ? arg.slice(10) : undefined;
344
+ if (value)
345
+ out.push(value);
346
+ });
347
+ return out;
60
348
  }
61
- function isGlob(pattern) {
62
- return pattern.includes("*") || pattern.includes("?") || pattern.includes("[");
349
+ function commandArgv(command) {
350
+ const trimmed = command.trim();
351
+ return SHELL_SYNTAX.test(trimmed) ? ["sh", "-c", trimmed] : trimmed.split(/\s+/);
63
352
  }
64
- async function resolvesToFile(pattern, cwd) {
65
- if (pattern.startsWith("!"))
66
- return true;
67
- if (!isGlob(pattern))
68
- return existsSync(resolve(cwd, pattern));
69
- const glob = new Glob(pattern);
70
- for await (const _ of glob.scan({ cwd, onlyFiles: true }))
71
- return true;
72
- return false;
353
+ function stringList(value) {
354
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
73
355
  }
74
- async function checkField(configPath, field, patterns, cwd) {
75
- const issues = [];
76
- for (const pattern of patterns ?? []) {
77
- if (!await resolvesToFile(pattern, cwd)) {
78
- issues.push({ config: configPath, field, pattern });
79
- }
356
+ function timeoutOf(raw) {
357
+ const factor = raw["timeoutFactor"];
358
+ const ms = raw["timeoutMS"];
359
+ if (typeof factor !== "number" && typeof ms !== "number")
360
+ return;
361
+ return {
362
+ factor: typeof factor === "number" ? factor : 1.5,
363
+ extraMs: typeof ms === "number" ? ms : 5000
364
+ };
365
+ }
366
+ function testsOf(raw, where) {
367
+ const bun = isRecord(raw["bun"]) ? raw["bun"] : {};
368
+ const include = stringList(bun["testFiles"]);
369
+ if (include.length === 0)
370
+ throw new Error(`${where} has no bun.testFiles`);
371
+ const preload = preloadArgs(stringList(bun["nodeArgs"]));
372
+ return preload.length > 0 ? { include, preload } : { include };
373
+ }
374
+ function runnerOf(raw, where) {
375
+ const runnerName = raw["testRunner"];
376
+ if (runnerName === "command") {
377
+ const cmd = isRecord(raw["commandRunner"]) ? raw["commandRunner"]["command"] : undefined;
378
+ const argv = commandArgv(typeof cmd === "string" ? cmd : "npm test");
379
+ return { runner: { kind: "command", argv } };
80
380
  }
81
- return issues;
381
+ if (runnerName === undefined || runnerName === "bun") {
382
+ return {
383
+ tests: testsOf(raw, where),
384
+ ...raw["disableBail"] === true ? { mode: "matrix" } : {}
385
+ };
386
+ }
387
+ throw new Error(`${where}: testRunner "${String(runnerName)}" has no polly counterpart (bun or command)`);
82
388
  }
83
- async function validateMutateTargets(root) {
84
- const configs = await findStrykerConfigs(root);
85
- const issues = [];
86
- for (const configPath of configs) {
87
- const config = JSON.parse(readFileSync(configPath, "utf8"));
88
- const testFiles = config.testFiles ?? config.bun?.testFiles;
89
- issues.push(...await checkField(configPath, "mutate", config.mutate, root));
90
- issues.push(...await checkField(configPath, "testFiles", testFiles, root));
389
+ function tuningOf(raw) {
390
+ const out = {};
391
+ if (typeof raw["concurrency"] === "number")
392
+ out["concurrency"] = raw["concurrency"];
393
+ const timeout = timeoutOf(raw);
394
+ if (timeout)
395
+ out["timeout"] = timeout;
396
+ const excluded = isRecord(raw["mutator"]) ? stringList(raw["mutator"]["excludedMutations"]) : [];
397
+ if (excluded.length > 0)
398
+ out["mutators"] = { exclude: excluded };
399
+ const brk = isRecord(raw["thresholds"]) ? raw["thresholds"]["break"] : undefined;
400
+ if (typeof brk === "number")
401
+ out["thresholds"] = { break: brk };
402
+ return out;
403
+ }
404
+ function strykerToMutation(raw, where) {
405
+ if (!isRecord(raw))
406
+ throw new Error(`${where} is not a JSON object`);
407
+ const draft = { targets: stringList(raw["mutate"]), ...runnerOf(raw, where), ...tuningOf(raw) };
408
+ const notes = [];
409
+ if (!stringList(raw["ignorers"]).includes("polly-verify")) {
410
+ notes.push("ignoreVerifyCallsites defaults to true: requires/ensures mutants are reported Ignored (polly#143)");
91
411
  }
92
- return { configs, issues };
412
+ const dropped = Object.keys(raw).filter((k) => !MAPPED.has(k) && !SILENT.has(k));
413
+ if (dropped.length > 0)
414
+ notes.push(`dropped Stryker-only keys: ${dropped.join(", ")}`);
415
+ return { config: parseMutationConfig(draft, where), notes };
416
+ }
417
+ async function readStrykerConfig(path) {
418
+ return strykerToMutation(await Bun.file(path).json(), path);
419
+ }
420
+ function defineImportSpecifier(dir) {
421
+ try {
422
+ Bun.resolveSync("@fairfox/polly/mutate", dir);
423
+ return "@fairfox/polly/mutate";
424
+ } catch {
425
+ const local = join2(import.meta.dir, "define.ts");
426
+ if (!existsSync2(local))
427
+ return "@fairfox/polly/mutate";
428
+ const rel = relative(dir, local);
429
+ return rel.startsWith(".") ? rel : `./${rel}`;
430
+ }
431
+ }
432
+ function literal(value) {
433
+ return JSON.stringify(value, null, 2).replace(/^(\s*)"([A-Za-z_$][\w$]*)":/gm, "$1$2:").replace(/([^\s[{,])(?=\n\s*[}\]])/g, "$1,");
434
+ }
435
+ function renderMutationConfig(config, specifier) {
436
+ return [
437
+ `import { defineMutation } from "${specifier}";`,
438
+ "",
439
+ `export default defineMutation(${literal(config)});`,
440
+ ""
441
+ ].join(`
442
+ `);
443
+ }
444
+ async function migrateConfig(strykerPath, opts = {}) {
445
+ const { config, notes } = await readStrykerConfig(strykerPath);
446
+ const dir = dirname2(strykerPath);
447
+ const path = join2(dir, MUTATION_CONFIG_FILE);
448
+ const source = renderMutationConfig(config, defineImportSpecifier(dir));
449
+ const existed = existsSync2(path);
450
+ const written = Boolean(opts.write) && (!existed || Boolean(opts.force));
451
+ if (written)
452
+ await Bun.write(path, source);
453
+ return { path, source, notes, written, existed };
93
454
  }
94
455
 
95
456
  // tools/mutate/src/config.ts
96
457
  var DEFAULT_REPORT = "reports/mutation/mutation.json";
97
458
  var DEFAULT_DECISIONS = ".polly/test-debt/decisions.jsonl";
459
+ async function loadAt(path) {
460
+ if (path.endsWith(".json")) {
461
+ const { config, notes } = await readStrykerConfig(path);
462
+ return { path, format: "stryker", config, notes };
463
+ }
464
+ return { path, format: "polly", config: await loadMutationConfig(path), notes: [] };
465
+ }
98
466
  async function resolveMutateConfig(cwd, args) {
99
- let strykerConfigPath = null;
100
- if (args.config) {
101
- strykerConfigPath = resolve2(cwd, args.config);
102
- } else {
103
- const found = await findStrykerConfigs(cwd);
104
- strykerConfigPath = found[0] ?? null;
467
+ const explicit = args.config ? resolve2(cwd, args.config) : null;
468
+ const discoveredStryker = (await findStrykerConfigs(cwd))[0] ?? null;
469
+ const local = resolve2(cwd, MUTATION_CONFIG_FILE);
470
+ const mutationPath = explicit ?? (existsSync3(local) ? local : discoveredStryker);
471
+ let mutation = null;
472
+ let mutationError = null;
473
+ if (mutationPath?.endsWith(".json")) {
474
+ try {
475
+ mutation = await loadAt(mutationPath);
476
+ } catch (err) {
477
+ mutationError = err instanceof Error ? err.message : String(err);
478
+ }
479
+ } else if (mutationPath) {
480
+ mutation = await loadAt(mutationPath);
105
481
  }
482
+ const base = mutation ? dirname3(mutation.path) : cwd;
483
+ const fromConfig = (flag, key, fallback) => flag ? resolve2(cwd, flag) : resolve2(base, key ?? fallback);
106
484
  return {
107
485
  cwd,
108
- strykerConfigPath,
109
- reportPath: resolve2(cwd, args.report ?? DEFAULT_REPORT),
486
+ mutation,
487
+ mutationError,
488
+ reportPath: fromConfig(args.report, mutation?.config.report, DEFAULT_REPORT),
110
489
  dbPath: args.db ? resolve2(cwd, args.db) : ":memory:",
111
- decisionsPath: resolve2(cwd, args.decisions ?? DEFAULT_DECISIONS)
490
+ decisionsPath: fromConfig(args.decisions, mutation?.config.decisions, DEFAULT_DECISIONS)
112
491
  };
113
492
  }
114
493
 
@@ -123,6 +502,10 @@ function buildDb(report, dbPath = ":memory:") {
123
502
  db.exec(`
124
503
  DROP TABLE IF EXISTS kills;
125
504
  DROP TABLE IF EXISTS covers;
505
+ DROP TABLE IF EXISTS contract_kills;
506
+ DROP TABLE IF EXISTS contract_sites;
507
+ DROP TABLE IF EXISTS contract_violations;
508
+ DROP TABLE IF EXISTS report_meta;
126
509
  DROP TABLE IF EXISTS mutants;
127
510
  DROP TABLE IF EXISTS tests;
128
511
  CREATE TABLE tests (
@@ -136,8 +519,30 @@ function buildDb(report, dbPath = ":memory:") {
136
519
  mutator TEXT NOT NULL,
137
520
  file TEXT NOT NULL,
138
521
  line INTEGER,
139
- status TEXT NOT NULL
522
+ status TEXT NOT NULL,
523
+ contract_only INTEGER NOT NULL DEFAULT 0
524
+ );
525
+ -- requires/ensures sites and the mutants each one killed (bun engine, contracts on)
526
+ CREATE TABLE contract_sites (
527
+ id TEXT PRIMARY KEY,
528
+ file TEXT NOT NULL,
529
+ line INTEGER NOT NULL,
530
+ primitive TEXT NOT NULL,
531
+ message TEXT,
532
+ handler_from INTEGER,
533
+ handler_to INTEGER
140
534
  );
535
+ CREATE TABLE contract_kills (
536
+ mutant_id TEXT NOT NULL REFERENCES mutants(id),
537
+ contract_id TEXT NOT NULL,
538
+ PRIMARY KEY (mutant_id, contract_id)
539
+ );
540
+ CREATE TABLE contract_violations (
541
+ target TEXT NOT NULL,
542
+ test TEXT NOT NULL,
543
+ contract_id TEXT
544
+ );
545
+ CREATE TABLE report_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
141
546
  -- the kill matrix: (mutant, test) where test detects mutant
142
547
  CREATE TABLE kills (
143
548
  mutant_id TEXT NOT NULL REFERENCES mutants(id),
@@ -154,9 +559,13 @@ function buildDb(report, dbPath = ":memory:") {
154
559
  CREATE INDEX idx_kills_mutant ON kills(mutant_id);
155
560
  `);
156
561
  const insTest = db.prepare("INSERT OR IGNORE INTO tests (id, file, name, line) VALUES (?, ?, ?, ?)");
157
- const insMut = db.prepare("INSERT INTO mutants (id, mutator, file, line, status) VALUES (?, ?, ?, ?, ?)");
562
+ const insMut = db.prepare("INSERT INTO mutants (id, mutator, file, line, status, contract_only) VALUES (?, ?, ?, ?, ?, ?)");
158
563
  const insKill = db.prepare("INSERT OR IGNORE INTO kills (mutant_id, test_id) VALUES (?, ?)");
159
564
  const insCover = db.prepare("INSERT OR IGNORE INTO covers (mutant_id, test_id) VALUES (?, ?)");
565
+ const insContractKill = db.prepare("INSERT OR IGNORE INTO contract_kills (mutant_id, contract_id) VALUES (?, ?)");
566
+ const insSite = db.prepare("INSERT OR IGNORE INTO contract_sites (id, file, line, primitive, message, handler_from, handler_to) VALUES (?, ?, ?, ?, ?, ?, ?)");
567
+ const insViolation = db.prepare("INSERT INTO contract_violations (target, test, contract_id) VALUES (?, ?, ?)");
568
+ const insMeta = db.prepare("INSERT INTO report_meta (key, value) VALUES (?, ?)");
160
569
  const ingest = db.transaction(() => {
161
570
  for (const [file, tf] of Object.entries(report.testFiles ?? {})) {
162
571
  for (const t of tf.tests) {
@@ -165,215 +574,2607 @@ function buildDb(report, dbPath = ":memory:") {
165
574
  }
166
575
  for (const [file, f] of Object.entries(report.files)) {
167
576
  for (const m of f.mutants) {
168
- insMut.run(m.id, m.mutatorName, file, m.location.start.line, m.status);
577
+ insMut.run(m.id, m.mutatorName, file, m.location.start.line, m.status, m.contractOnly ? 1 : 0);
169
578
  for (const tid of m.killedBy ?? [])
170
579
  insKill.run(m.id, tid);
171
580
  for (const tid of m.coveredBy ?? [])
172
581
  insCover.run(m.id, tid);
582
+ for (const cid of m.killedByContract ?? [])
583
+ insContractKill.run(m.id, cid);
584
+ }
585
+ }
586
+ const contracts = report.contracts;
587
+ if (contracts) {
588
+ insMeta.run("contracts_mode", contracts.mode);
589
+ insMeta.run("runner", contracts.runner);
590
+ for (const s of contracts.sites) {
591
+ insSite.run(s.id, s.file, s.line, s.primitive, s.message ?? null, s.handler?.from ?? null, s.handler?.to ?? null);
592
+ }
593
+ for (const v of contracts.violations) {
594
+ if (v.contracts.length === 0)
595
+ insViolation.run(v.target, v.test, null);
596
+ for (const cid of v.contracts)
597
+ insViolation.run(v.target, v.test, cid);
173
598
  }
174
599
  }
175
600
  });
176
- ingest();
177
- return db;
601
+ ingest();
602
+ return db;
603
+ }
604
+ function queryAll(db, sql) {
605
+ return db.query(sql).all();
606
+ }
607
+ function queryGet(db, sql) {
608
+ return db.query(sql).get();
609
+ }
610
+ async function loadMutationReport(path) {
611
+ return await Bun.file(path).json();
612
+ }
613
+ if (false) {}
614
+
615
+ // tools/mutate/src/decisions.ts
616
+ var DEFAULT_LOG = ".polly/test-debt/decisions.jsonl";
617
+ var VERDICTS = ["keep", "prune", "rewrite", "investigate"];
618
+ function normalizeSource(src) {
619
+ return src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1").replace(/\s+/g, " ").trim();
620
+ }
621
+ async function fileHash(file) {
622
+ const f = Bun.file(file);
623
+ if (!await f.exists())
624
+ return null;
625
+ return createHash("sha256").update(normalizeSource(await f.text())).digest("hex").slice(0, 16);
626
+ }
627
+ function fileSignals(db) {
628
+ const rows = queryAll(db, `
629
+ WITH file_kill AS (SELECT DISTINCT t.file file, k.mutant_id mid FROM kills k JOIN tests t ON t.id=k.test_id),
630
+ owner AS (SELECT mid, count(DISTINCT file) nf FROM file_kill GROUP BY mid)
631
+ SELECT fk.file file, count(DISTINCT fk.mid) kills,
632
+ sum(CASE WHEN o.nf=1 THEN 1 ELSE 0 END) unique_kills
633
+ FROM file_kill fk JOIN owner o ON o.mid=fk.mid GROUP BY fk.file`);
634
+ const m = new Map;
635
+ for (const r of rows)
636
+ m.set(r.file, {
637
+ kills: r.kills,
638
+ uniqueKills: r.unique_kills,
639
+ subsumed: r.kills > 0 && r.unique_kills === 0
640
+ });
641
+ return m;
642
+ }
643
+ async function loadDecisions(logPath) {
644
+ const m = new Map;
645
+ const f = Bun.file(logPath);
646
+ if (!await f.exists())
647
+ return m;
648
+ for (const line of (await f.text()).split(`
649
+ `)) {
650
+ const t = line.trim();
651
+ if (!t)
652
+ continue;
653
+ const d = JSON.parse(t);
654
+ m.set(d.file, d);
655
+ }
656
+ return m;
657
+ }
658
+ function staleReason(d, currentHash, current) {
659
+ if (!current)
660
+ return "file no longer kills any mutant (renamed/deleted/refactored?)";
661
+ if (d.hash !== currentHash)
662
+ return "test file changed since the decision";
663
+ if (d.signal.subsumed !== current.subsumed)
664
+ return `subsumption flipped (${d.signal.subsumed} → ${current.subsumed})`;
665
+ if (d.signal.uniqueKills > 0 !== current.uniqueKills > 0)
666
+ return `unique-kill status changed (${d.signal.uniqueKills} → ${current.uniqueKills})`;
667
+ return null;
668
+ }
669
+ async function status(db, logPath = DEFAULT_LOG) {
670
+ const signals = fileSignals(db);
671
+ const decisions = await loadDecisions(logPath);
672
+ const needsReview = [];
673
+ const stale = [];
674
+ const settled = [];
675
+ for (const [file, sig] of [...signals].sort((a, b) => b[1].kills - a[1].kills)) {
676
+ const d = decisions.get(file);
677
+ if (!d) {
678
+ if (sig.subsumed)
679
+ needsReview.push(` ${file} (${sig.kills} kills, 0 unique)`);
680
+ continue;
681
+ }
682
+ const reason = staleReason(d, await fileHash(file), sig);
683
+ if (reason)
684
+ stale.push(` ${file} [${d.verdict}] — ${reason}`);
685
+ else
686
+ settled.push(` ${file} [${d.verdict}] ${d.rationale ? `— ${d.rationale}` : ""}`);
687
+ }
688
+ for (const [file, d] of decisions) {
689
+ if (!signals.has(file))
690
+ stale.push(` ${file} [${d.verdict}] — file no longer in matrix`);
691
+ }
692
+ const out = [];
693
+ out.push(`NEEDS REVIEW (subsumed files with no decision — ${needsReview.length})`);
694
+ out.push(needsReview.length ? needsReview.join(`
695
+ `) : " none");
696
+ out.push(`
697
+ STALE (decision's basis drifted — re-review — ${stale.length})`);
698
+ out.push(stale.length ? stale.join(`
699
+ `) : " none");
700
+ out.push(`
701
+ SETTLED (fresh decisions, suppressed from action list — ${settled.length})`);
702
+ out.push(settled.length ? settled.join(`
703
+ `) : " none");
704
+ return out.join(`
705
+ `);
706
+ }
707
+ async function decide(file, verdict, rationale, db, logPath = DEFAULT_LOG) {
708
+ if (!VERDICTS.includes(verdict)) {
709
+ console.log(`✗ verdict must be one of: ${VERDICTS.join(", ")}`);
710
+ process.exit(1);
711
+ }
712
+ const sig = fileSignals(db).get(file);
713
+ if (!sig) {
714
+ console.log(`✗ ${file} is not a test file that kills any mutant in the current matrix`);
715
+ process.exit(1);
716
+ }
717
+ const decided = new Date().toISOString().slice(0, 10);
718
+ const record = {
719
+ file,
720
+ verdict,
721
+ rationale,
722
+ signal: sig,
723
+ hash: await fileHash(file),
724
+ decided
725
+ };
726
+ await Bun.write(logPath, (await Bun.file(logPath).exists() ? await Bun.file(logPath).text() : "") + JSON.stringify(record) + `
727
+ `);
728
+ console.log(`✓ recorded: ${file} [${verdict}]${rationale ? ` — ${rationale}` : ""}`);
729
+ }
730
+ if (false) {}
731
+
732
+ // tools/mutate/src/init.ts
733
+ import { existsSync as existsSync4 } from "node:fs";
734
+ import { join as join3 } from "node:path";
735
+ function detectMutate(projectDir) {
736
+ if (existsSync4(join3(projectDir, "src"))) {
737
+ return ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.d.ts"];
738
+ }
739
+ return ["**/*.ts", "!**/*.test.ts", "!**/*.d.ts", "!dist/**", `!${MUTATION_CONFIG_FILE}`];
740
+ }
741
+ function detectTestGlob(projectDir) {
742
+ for (const d of ["tests", "test"]) {
743
+ if (existsSync4(join3(projectDir, d)))
744
+ return `${d}/**/*.test.ts`;
745
+ }
746
+ return "**/*.test.ts";
747
+ }
748
+ async function initConfig(projectDir, opts = {}) {
749
+ const configPath = join3(projectDir, MUTATION_CONFIG_FILE);
750
+ const warnings = [];
751
+ const specifier = defineImportSpecifier(projectDir);
752
+ if (specifier === "@fairfox/polly/mutate") {
753
+ try {
754
+ Bun.resolveSync(specifier, projectDir);
755
+ } catch {
756
+ warnings.push("@fairfox/polly does not resolve here — install it, or the config cannot load");
757
+ }
758
+ }
759
+ const mutate = detectMutate(projectDir);
760
+ const testGlob = detectTestGlob(projectDir);
761
+ if (!existsSync4(join3(projectDir, "src"))) {
762
+ warnings.push("no src/ directory — adjust `targets` to point at your source");
763
+ }
764
+ if (!existsSync4(join3(projectDir, "tests")) && !existsSync4(join3(projectDir, "test"))) {
765
+ warnings.push(`no tests/ directory — using "${testGlob}"; adjust tests.include if needed`);
766
+ }
767
+ if (existsSync4(configPath) && !opts.force) {
768
+ return { configPath, created: false, specifier, mutate, testGlob, warnings };
769
+ }
770
+ const config = { targets: mutate, tests: { include: [testGlob] } };
771
+ await Bun.write(configPath, renderMutationConfig(config, specifier));
772
+ return { configPath, created: true, specifier, mutate, testGlob, warnings };
773
+ }
774
+
775
+ // tools/mutate/src/run.ts
776
+ import { relative as relative7 } from "node:path";
777
+
778
+ // tools/mutate/src/engine/index.ts
779
+ import { realpathSync as realpathSync4 } from "node:fs";
780
+ import { join as join9, relative as relative6 } from "node:path";
781
+
782
+ // tools/mutate/src/engine/baseline.ts
783
+ import { relative as relative3 } from "node:path";
784
+
785
+ // tools/mutate/src/engine/junit.ts
786
+ import { realpathSync } from "node:fs";
787
+ import { relative as relative2, resolve as resolve3 } from "node:path";
788
+ var ENTITIES = {
789
+ "&quot;": '"',
790
+ "&apos;": "'",
791
+ "&lt;": "<",
792
+ "&gt;": ">",
793
+ "&amp;": "&"
794
+ };
795
+ function decode(s) {
796
+ return s.replace(/&(?:quot|apos|lt|gt|amp|#(\d+)|#x([0-9a-f]+));/gi, (m, dec, hex) => {
797
+ if (dec)
798
+ return String.fromCodePoint(Number(dec));
799
+ if (hex)
800
+ return String.fromCodePoint(Number.parseInt(hex, 16));
801
+ return ENTITIES[m] ?? m;
802
+ });
803
+ }
804
+ function attr(attrs, key) {
805
+ const m = new RegExp(`\\b${key}="([^"]*)"`).exec(attrs);
806
+ return m?.[1] === undefined ? "" : decode(m[1]);
807
+ }
808
+ function caseStatus(body) {
809
+ if (/<(?:failure|error)\b/.test(body))
810
+ return "failed";
811
+ return /<skipped\b/.test(body) ? "skipped" : "passed";
812
+ }
813
+ var FAILURE = /<(?:failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:failure|error)>)/;
814
+ function failureMessage(body) {
815
+ const m = FAILURE.exec(body);
816
+ if (!m)
817
+ return;
818
+ const parts = [attr(m[1] ?? "", "message"), decode(m[2] ?? "")].filter((s) => s.length > 0);
819
+ return parts.join(`
820
+ `);
821
+ }
822
+ var TAG = /<testsuite\b([^>]*?)(\/?)>|<\/testsuite>|<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
823
+ function parseJunit(xml, cwd) {
824
+ const cases = [];
825
+ const suites = [];
826
+ for (const [whole, suiteAttrs, selfClosing, caseAttrs, body] of xml.matchAll(TAG)) {
827
+ if (whole.startsWith("</testsuite"))
828
+ suites.pop();
829
+ else if (suiteAttrs !== undefined && selfClosing !== "/")
830
+ suites.push(attr(suiteAttrs, "name"));
831
+ else if (caseAttrs !== undefined)
832
+ cases.push(caseFrom(suites, caseAttrs, body ?? "", cwd));
833
+ }
834
+ return cases;
835
+ }
836
+ function caseFrom(suites, caseAttrs, body, cwd) {
837
+ const path = [...suites.slice(1), attr(caseAttrs, "name")];
838
+ const status = caseStatus(body);
839
+ const message = status === "failed" ? failureMessage(body) : undefined;
840
+ return {
841
+ file: resolve3(cwd, attr(caseAttrs, "file")),
842
+ name: path.join(" > "),
843
+ filterName: path.join(" "),
844
+ line: Number(attr(caseAttrs, "line")) || 0,
845
+ status,
846
+ ...message === undefined ? {} : { failureMessage: message }
847
+ };
848
+ }
849
+ function testId(projectCwd, file, name, line) {
850
+ return `${relative2(projectCwd, file)}#${name}@${line}`;
851
+ }
852
+ var CONTRACT_MARKER = /\[polly-contract (requires|ensures) (.+?):(\d+)\]/g;
853
+ function realOr(path) {
854
+ try {
855
+ return realpathSync(path);
856
+ } catch {
857
+ return path;
858
+ }
859
+ }
860
+ function contractsIn(text, projectCwd) {
861
+ const ids = new Set;
862
+ for (const m of text.matchAll(CONTRACT_MARKER)) {
863
+ if (m[2] && m[3])
864
+ ids.add(`${relative2(projectCwd, realOr(m[2]))}:${m[3]}`);
865
+ }
866
+ return [...ids].sort();
867
+ }
868
+ function contractKills(cases, projectCwd) {
869
+ const out = [];
870
+ for (const c of cases) {
871
+ if (c.status !== "failed" || c.failureMessage === undefined)
872
+ continue;
873
+ const contracts = contractsIn(c.failureMessage, projectCwd);
874
+ if (contracts.length > 0) {
875
+ out.push({ test: testId(projectCwd, c.file, c.name, c.line), contracts });
876
+ }
877
+ }
878
+ return out;
879
+ }
880
+ var LOAD_FAILURE_NAME = "(file produced no results)";
881
+ function loadFailureId(projectCwd, file) {
882
+ return testId(projectCwd, file, LOAD_FAILURE_NAME, 0);
883
+ }
884
+ function killers(cases, baselineFiles, projectCwd) {
885
+ const ids = cases.filter((c) => c.status === "failed").map((c) => testId(projectCwd, c.file, c.name, c.line));
886
+ const reported = new Set(cases.map((c) => c.file));
887
+ for (const f of [...baselineFiles].sort()) {
888
+ if (!reported.has(f))
889
+ ids.push(loadFailureId(projectCwd, f));
890
+ }
891
+ return ids;
892
+ }
893
+
894
+ // tools/mutate/src/engine/runner.ts
895
+ import { randomUUID } from "node:crypto";
896
+ import { existsSync as existsSync5, rmSync } from "node:fs";
897
+ import { tmpdir } from "node:os";
898
+ import { join as join4 } from "node:path";
899
+ function preloadPath() {
900
+ const candidates = [
901
+ `${import.meta.dir}/preload.js`,
902
+ `${import.meta.dir}/engine/preload.js`,
903
+ `${import.meta.dir}/preload.ts`
904
+ ];
905
+ const found = candidates.find((c) => existsSync5(c));
906
+ if (!found)
907
+ throw new Error(`polly mutate: cannot find the engine preload (looked in ${import.meta.dir})`);
908
+ return found;
909
+ }
910
+ function cleanEnv(extra) {
911
+ const env = {};
912
+ for (const [k, v] of Object.entries(process.env)) {
913
+ if (v !== undefined && !k.startsWith("POLLY_MUTATE_") && k !== "POLLY_CONTRACTS")
914
+ env[k] = v;
915
+ }
916
+ return { ...env, ...extra };
917
+ }
918
+ async function readJunit(path) {
919
+ if (!path)
920
+ return;
921
+ const file = Bun.file(path);
922
+ if (!await file.exists())
923
+ return;
924
+ const xml = await file.text();
925
+ rmSync(path, { force: true });
926
+ return xml;
927
+ }
928
+ function processArgv(runner, run, junitPath) {
929
+ const env = { ...run.env, POLLY_CONTRACTS: run.contracts ?? "off" };
930
+ if (runner.kind === "command") {
931
+ const inherited = process.env["BUN_OPTIONS"];
932
+ const preloads = run.preloads.map((p) => `--preload=${p}`).join(" ");
933
+ return {
934
+ argv: runner.argv,
935
+ env: { ...env, BUN_OPTIONS: inherited ? `${inherited} ${preloads}` : preloads }
936
+ };
937
+ }
938
+ return {
939
+ argv: [
940
+ "bun",
941
+ "test",
942
+ ...run.preloads.flatMap((p) => ["--preload", p]),
943
+ ...run.bail ? ["--bail"] : [],
944
+ ...run.namePattern ? ["-t", run.namePattern] : [],
945
+ ...junitPath ? ["--reporter=junit", `--reporter-outfile=${junitPath}`] : [],
946
+ ...run.files
947
+ ],
948
+ env
949
+ };
950
+ }
951
+ async function runBunTest(run, runner = { kind: "bun-test" }) {
952
+ const started = performance.now();
953
+ const junitPath = run.junit && runner.kind === "bun-test" ? join4(tmpdir(), `polly-mutate-junit-${randomUUID()}.xml`) : undefined;
954
+ const { argv, env } = processArgv(runner, run, junitPath);
955
+ const group = runner.kind === "command";
956
+ const proc = Bun.spawn(argv, {
957
+ cwd: run.cwd,
958
+ detached: group,
959
+ env: cleanEnv(env),
960
+ stdin: "ignore",
961
+ stdout: "ignore",
962
+ stderr: run.captureStderr ? "pipe" : "ignore"
963
+ });
964
+ let timedOut = false;
965
+ const timer = setTimeout(() => {
966
+ timedOut = true;
967
+ if (group)
968
+ process.kill(-proc.pid, 9);
969
+ else
970
+ proc.kill(9);
971
+ }, run.timeoutMs);
972
+ const stderrText = run.captureStderr && proc.stderr ? new Response(proc.stderr).text() : undefined;
973
+ const exitCode = await proc.exited;
974
+ clearTimeout(timer);
975
+ const ms = performance.now() - started;
976
+ const junitXml = await readJunit(junitPath);
977
+ const outcome = { exitCode, timedOut, ms, ...junitXml ? { junitXml } : {} };
978
+ if (stderrText === undefined)
979
+ return outcome;
980
+ return { ...outcome, stderrTail: (await stderrText).slice(-2000) };
981
+ }
982
+ async function pool(items, concurrency, fn) {
983
+ const results = new Array(items.length);
984
+ let next = 0;
985
+ const worker = async () => {
986
+ while (next < items.length) {
987
+ const i = next++;
988
+ const item = items[i];
989
+ if (item !== undefined)
990
+ results[i] = await fn(item, i);
991
+ }
992
+ };
993
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, worker));
994
+ return results;
995
+ }
996
+
997
+ // tools/mutate/src/engine/workdir.ts
998
+ import { existsSync as existsSync6, mkdirSync, mkdtempSync, readFileSync as readFileSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
999
+ import { tmpdir as tmpdir2 } from "node:os";
1000
+ import { join as join5 } from "node:path";
1001
+ function isRecord2(v) {
1002
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1003
+ }
1004
+ function absolutePreload(spec, projectCwd) {
1005
+ if (typeof spec !== "string")
1006
+ return spec;
1007
+ try {
1008
+ return Bun.resolveSync(spec, projectCwd);
1009
+ } catch {
1010
+ return spec;
1011
+ }
1012
+ }
1013
+ function absolutiseBunfig(config, projectCwd) {
1014
+ const fix = (v) => Array.isArray(v) ? v.map((s) => absolutePreload(s, projectCwd)) : absolutePreload(v, projectCwd);
1015
+ const out = { ...config };
1016
+ if ("preload" in out)
1017
+ out["preload"] = fix(out["preload"]);
1018
+ const test = out["test"];
1019
+ if (isRecord2(test) && "preload" in test)
1020
+ out["test"] = { ...test, preload: fix(test["preload"]) };
1021
+ return out;
1022
+ }
1023
+ var tomlKey = (k) => /^[A-Za-z0-9_-]+$/.test(k) ? k : JSON.stringify(k);
1024
+ function tomlValue(v) {
1025
+ if (Array.isArray(v))
1026
+ return `[${v.map(tomlValue).join(", ")}]`;
1027
+ if (isRecord2(v)) {
1028
+ return `{ ${Object.entries(v).map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`).join(", ")} }`;
1029
+ }
1030
+ if (typeof v === "string")
1031
+ return JSON.stringify(v);
1032
+ return String(v);
1033
+ }
1034
+ function renderToml(config, prefix = []) {
1035
+ const lines = [];
1036
+ const tables = [];
1037
+ for (const [k, v] of Object.entries(config)) {
1038
+ if (isRecord2(v))
1039
+ tables.push([k, v]);
1040
+ else
1041
+ lines.push(`${tomlKey(k)} = ${tomlValue(v)}`);
1042
+ }
1043
+ const sections = tables.map(([k, v]) => {
1044
+ const path = [...prefix, k];
1045
+ return `[${path.map(tomlKey).join(".")}]
1046
+ ${renderToml(v, path)}`;
1047
+ });
1048
+ return [lines.join(`
1049
+ `), ...sections].filter(Boolean).join(`
1050
+
1051
+ `);
1052
+ }
1053
+ function createWorkdirs(projectCwd) {
1054
+ const root = mkdtempSync(join5(tmpdir2(), "polly-mutate-"));
1055
+ const files = {};
1056
+ const tsconfig = join5(projectCwd, "tsconfig.json");
1057
+ if (existsSync6(tsconfig))
1058
+ files["tsconfig.json"] = JSON.stringify({ extends: tsconfig });
1059
+ const bunfig = join5(projectCwd, "bunfig.toml");
1060
+ if (existsSync6(bunfig)) {
1061
+ const parsed = Bun.TOML.parse(readFileSync2(bunfig, "utf8"));
1062
+ if (isRecord2(parsed))
1063
+ files["bunfig.toml"] = renderToml(absolutiseBunfig(parsed, projectCwd));
1064
+ }
1065
+ return {
1066
+ root,
1067
+ create() {
1068
+ mkdirSync(root, { recursive: true });
1069
+ const dir = mkdtempSync(join5(root, "run-"));
1070
+ for (const [name, text] of Object.entries(files))
1071
+ writeFileSync(join5(dir, name), text);
1072
+ return dir;
1073
+ },
1074
+ release: (dir) => rmSync2(dir, { recursive: true, force: true }),
1075
+ remove: () => rmSync2(root, { recursive: true, force: true })
1076
+ };
1077
+ }
1078
+ async function inCwd(workdirs, projectCwd, fn) {
1079
+ if (!workdirs)
1080
+ return fn(projectCwd);
1081
+ const dir = workdirs.create();
1082
+ try {
1083
+ return await fn(dir);
1084
+ } finally {
1085
+ workdirs.release(dir);
1086
+ }
1087
+ }
1088
+
1089
+ // tools/mutate/src/engine/baseline.ts
1090
+ var BASELINE_ATTEMPTS = 3;
1091
+ var BASELINE_TIMEOUT_MS = 300000;
1092
+ function failed(reason, contractViolations) {
1093
+ return {
1094
+ ok: false,
1095
+ ms: 0,
1096
+ reason,
1097
+ tests: [],
1098
+ reportedFiles: new Set,
1099
+ ...contractViolations ? { contractViolations } : {}
1100
+ };
1101
+ }
1102
+ var COMMAND = "(command)";
1103
+ async function commandViolatesContract(cfg, cwd, preloads, files) {
1104
+ const off = await runBunTest({
1105
+ cwd,
1106
+ files,
1107
+ preloads,
1108
+ contracts: "off",
1109
+ bail: false,
1110
+ timeoutMs: BASELINE_TIMEOUT_MS,
1111
+ captureStderr: true
1112
+ }, cfg.runner);
1113
+ return off.exitCode === 0 && !off.timedOut;
1114
+ }
1115
+ function green(cfg, cwd, outcome) {
1116
+ if (cfg.mode === "fast")
1117
+ return { ok: true, ms: outcome.ms, tests: [], reportedFiles: new Set };
1118
+ const cases = parseJunit(outcome.junitXml ?? "", cwd);
1119
+ if (cases.length === 0) {
1120
+ return failed("baseline passed but its junit report holds no test case (reporter broke?)");
1121
+ }
1122
+ return {
1123
+ ok: true,
1124
+ ms: outcome.ms,
1125
+ tests: cases.map((c) => ({
1126
+ id: testId(cfg.cwd, c.file, c.name, c.line),
1127
+ file: c.file,
1128
+ name: c.name,
1129
+ line: c.line
1130
+ })),
1131
+ reportedFiles: new Set(cases.map((c) => c.file))
1132
+ };
1133
+ }
1134
+ async function measureIn(cfg, cwd, preloads, files) {
1135
+ let last = "";
1136
+ for (let attempt = 1;attempt <= BASELINE_ATTEMPTS; attempt++) {
1137
+ const outcome = await runBunTest({
1138
+ cwd,
1139
+ files,
1140
+ preloads,
1141
+ contracts: cfg.contracts,
1142
+ bail: false,
1143
+ timeoutMs: BASELINE_TIMEOUT_MS,
1144
+ captureStderr: true,
1145
+ junit: cfg.mode === "matrix" || cfg.contracts !== "off" && cfg.runner.kind === "bun-test"
1146
+ }, cfg.runner);
1147
+ if (outcome.exitCode === 0 && !outcome.timedOut)
1148
+ return green(cfg, cwd, outcome);
1149
+ last = outcome.timedOut ? `timed out after ${BASELINE_TIMEOUT_MS} ms` : `exit ${outcome.exitCode}`;
1150
+ const failLine = outcome.stderrTail?.match(/\(fail\)[^\n]*/)?.[0];
1151
+ if (failLine)
1152
+ last += `: ${failLine}`;
1153
+ if (cfg.contracts === "off" || outcome.timedOut)
1154
+ continue;
1155
+ const contract = await contractFailure(cfg, cwd, preloads, files, outcome.junitXml, last);
1156
+ if (contract)
1157
+ return contract;
1158
+ }
1159
+ return failed(`baseline red ${BASELINE_ATTEMPTS}× on the selected tests (${last})`);
1160
+ }
1161
+ async function contractFailure(cfg, cwd, preloads, files, junitXml, last) {
1162
+ if (cfg.runner.kind === "command") {
1163
+ if (!await commandViolatesContract(cfg, cwd, preloads, files))
1164
+ return null;
1165
+ return failed(`the command fails only with contracts on (POLLY_CONTRACTS=${cfg.contracts}): a scenario violates a contract`, [{ test: COMMAND, contracts: [] }]);
1166
+ }
1167
+ const cases = parseJunit(junitXml ?? "", cwd);
1168
+ const violations = contractKills(cases, cfg.cwd);
1169
+ if (violations.length === 0)
1170
+ return null;
1171
+ const red = cases.filter((c) => c.status === "failed").length;
1172
+ return failed(violations.length === red ? `${violations.length} test(s) violate contracts` : `baseline red (${last}) and ${violations.length} of ${red} failing test(s) violate contracts`, violations);
1173
+ }
1174
+ async function measureBaseline(cfg, workdirs, preloads, target, log) {
1175
+ const scratch = await inCwd(workdirs, cfg.cwd, (cwd) => measureIn(cfg, cwd, preloads, target.covering));
1176
+ if (scratch.ok || !workdirs || scratch.contractViolations) {
1177
+ return { ...scratch, inTree: !workdirs };
1178
+ }
1179
+ const inTree = await measureIn(cfg, cfg.cwd, preloads, target.covering);
1180
+ if (inTree.ok) {
1181
+ log(`${relative3(cfg.cwd, target.file)}: tests fail outside ${cfg.cwd} (${scratch.reason}); its mutants run in-tree`);
1182
+ }
1183
+ return { ...inTree, inTree: true };
1184
+ }
1185
+
1186
+ // tools/mutate/src/engine/cache.ts
1187
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
1188
+ import { join as join6 } from "node:path";
1189
+ var CACHE_VERSION = 2;
1190
+ function mutantSig(m) {
1191
+ return `${m.mutatorName}:${m.start}:${m.end}:${m.replacement}`;
1192
+ }
1193
+ async function textOrEmpty(path) {
1194
+ const file = Bun.file(path);
1195
+ return await file.exists() ? file.text() : "";
1196
+ }
1197
+ async function cacheKey(input) {
1198
+ const hash = new Bun.CryptoHasher("sha256");
1199
+ hash.update(JSON.stringify({ v: CACHE_VERSION, bun: Bun.version, settings: input.settings }));
1200
+ for (const m of input.mutants)
1201
+ hash.update(`${mutantSig(m)}|${m.ignoredReason ?? ""}
1202
+ `);
1203
+ for (const f of [...input.closure, ...input.projectFiles]) {
1204
+ hash.update(`\x00${f}\x00`);
1205
+ hash.update(await textOrEmpty(f));
1206
+ }
1207
+ return hash.digest("hex");
1208
+ }
1209
+ async function readCache(dir, key) {
1210
+ const file = Bun.file(join6(dir, `${key}.json`));
1211
+ if (!await file.exists())
1212
+ return null;
1213
+ try {
1214
+ const entry = await file.json();
1215
+ return Array.isArray(entry.results) ? entry : null;
1216
+ } catch {
1217
+ return null;
1218
+ }
1219
+ }
1220
+ function writeEntry(dir, name, value) {
1221
+ mkdirSync2(dir, { recursive: true });
1222
+ const ignore = join6(dir, ".gitignore");
1223
+ if (!existsSync7(ignore))
1224
+ writeFileSync2(ignore, `*
1225
+ `);
1226
+ writeFileSync2(join6(dir, name), `${JSON.stringify(value)}
1227
+ `);
1228
+ }
1229
+ function writeCache(dir, key, entry) {
1230
+ writeEntry(dir, `${key}.json`, entry);
1231
+ }
1232
+ function writeCoverageCache(dir, key, coverage) {
1233
+ writeEntry(dir, `coverage-${key}.json`, coverage);
1234
+ }
1235
+ async function readCoverageCache(dir, key) {
1236
+ const file = Bun.file(join6(dir, `coverage-${key}.json`));
1237
+ if (!await file.exists())
1238
+ return null;
1239
+ try {
1240
+ const coverage = await file.json();
1241
+ return Array.isArray(coverage.targets) ? coverage : null;
1242
+ } catch {
1243
+ return null;
1244
+ }
1245
+ }
1246
+ function cachedResult(r) {
1247
+ return {
1248
+ sig: mutantSig(r.mutant),
1249
+ status: r.status,
1250
+ ...r.statusReason ? { statusReason: r.statusReason } : {},
1251
+ ...r.durationMs === undefined ? {} : { durationMs: r.durationMs },
1252
+ ...r.killedBy ? { killedBy: r.killedBy } : {},
1253
+ ...r.coveredBy ? { coveredBy: r.coveredBy } : {},
1254
+ ...r.killedByContract ? { killedByContract: r.killedByContract } : {},
1255
+ ...r.contractOnly ? { contractOnly: true } : {}
1256
+ };
1257
+ }
1258
+
1259
+ // tools/mutate/src/engine/coverage.ts
1260
+ import { mkdtempSync as mkdtempSync2, realpathSync as realpathSync2, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
1261
+ import { tmpdir as tmpdir3 } from "node:os";
1262
+ import { join as join7 } from "node:path";
1263
+
1264
+ // tools/mutate/src/engine/probes.ts
1265
+ import { parseSync } from "oxc-parser";
1266
+
1267
+ // tools/mutate/src/engine/ast.ts
1268
+ function isAstNode(value) {
1269
+ return isRecord(value) && typeof value["type"] === "string" && typeof value["start"] === "number" && typeof value["end"] === "number";
1270
+ }
1271
+ function child(node, key) {
1272
+ const value = node[key];
1273
+ return isAstNode(value) ? value : undefined;
1274
+ }
1275
+ function children(node, key) {
1276
+ const value = node[key];
1277
+ return Array.isArray(value) ? value.filter(isAstNode) : [];
1278
+ }
1279
+ function stringField(node, key) {
1280
+ const value = node[key];
1281
+ return typeof value === "string" ? value : undefined;
1282
+ }
1283
+ function calleeName(call) {
1284
+ const callee = child(call, "callee");
1285
+ if (!callee)
1286
+ return;
1287
+ if (callee.type === "Identifier")
1288
+ return stringField(callee, "name");
1289
+ if (callee.type === "MemberExpression" && callee["computed"] !== true) {
1290
+ const property = child(callee, "property");
1291
+ if (property?.type === "Identifier")
1292
+ return stringField(property, "name");
1293
+ }
1294
+ return;
1295
+ }
1296
+
1297
+ // tools/mutate/src/engine/probes.ts
1298
+ var HIT = "globalThis.__pollyMutateHit?.";
1299
+ var PARSE_OPTIONS = { preserveParens: false };
1300
+ var LIST_PARENTS = new Set(["Program", "BlockStatement", "StaticBlock", "TSModuleBlock"]);
1301
+ var LONE_PARENTS = {
1302
+ IfStatement: ["consequent", "alternate"],
1303
+ ForStatement: ["body"],
1304
+ ForInStatement: ["body"],
1305
+ ForOfStatement: ["body"],
1306
+ WhileStatement: ["body"],
1307
+ DoWhileStatement: ["body"],
1308
+ WithStatement: ["body"]
1309
+ };
1310
+ var ANONYMOUS = new Set(["FunctionExpression", "ArrowFunctionExpression", "ClassExpression"]);
1311
+ function isDirective(node) {
1312
+ return node?.type === "ExpressionStatement" && typeof node["directive"] === "string";
1313
+ }
1314
+ function afterDirectives(statements, from) {
1315
+ let at = from;
1316
+ for (const s of statements) {
1317
+ if (!isDirective(s))
1318
+ break;
1319
+ at = s.end;
1320
+ }
1321
+ return at;
1322
+ }
1323
+ function inList(parent, key) {
1324
+ return LIST_PARENTS.has(parent.type) && key === "body" || parent.type === "SwitchCase" && key === "consequent";
1325
+ }
1326
+ function isLone(node, parent, key) {
1327
+ return (LONE_PARENTS[parent.type]?.includes(key) ?? false) && node.type !== "BlockStatement" && !node.type.endsWith("Declaration");
1328
+ }
1329
+ function isWrappedValue(node, parent, key) {
1330
+ const value = parent.type === "ArrowFunctionExpression" && key === "body" && parent["expression"] === true || (parent.type === "PropertyDefinition" || parent.type === "AccessorProperty") && key === "value" || parent.type === "AssignmentPattern" && key === "right";
1331
+ const named = parent.type !== "ArrowFunctionExpression" && ANONYMOUS.has(node.type);
1332
+ return value && !named;
1333
+ }
1334
+ function sitesOf(node, parent, key) {
1335
+ const sites = [];
1336
+ const span = { start: node.start, end: node.end };
1337
+ if (node.type === "BlockStatement" || node.type === "StaticBlock") {
1338
+ sites.push({
1339
+ kind: "block",
1340
+ ...span,
1341
+ at: afterDirectives(children(node, "body"), node.start + 1)
1342
+ });
1343
+ }
1344
+ if (!parent)
1345
+ return sites;
1346
+ if (inList(parent, key)) {
1347
+ sites.push({ kind: "statement", ...span, at: isDirective(node) ? node.end : node.start });
1348
+ } else if (isLone(node, parent, key)) {
1349
+ sites.push({ kind: "lone", ...span, at: node.start });
1350
+ } else if (isWrappedValue(node, parent, key)) {
1351
+ sites.push({ kind: "expression", ...span, at: node.start });
1352
+ }
1353
+ return sites;
1354
+ }
1355
+ function collectSites(program) {
1356
+ const sites = [];
1357
+ const visit = (node, parent, key) => {
1358
+ sites.push(...sitesOf(node, parent, key));
1359
+ for (const [k, value] of Object.entries(node)) {
1360
+ const list = Array.isArray(value) ? value : [value];
1361
+ for (const c of list)
1362
+ if (isAstNode(c))
1363
+ visit(c, node, k);
1364
+ }
1365
+ };
1366
+ for (const s of children(program, "body"))
1367
+ visit(s, program, "body");
1368
+ return sites;
1369
+ }
1370
+ function innermost(sites, start, end) {
1371
+ let best = null;
1372
+ for (const s of sites) {
1373
+ if (s.start > start || s.end < end)
1374
+ continue;
1375
+ if (!best || s.end - s.start < best.end - best.start)
1376
+ best = s;
1377
+ else if (s.end - s.start === best.end - best.start && s.kind === "block")
1378
+ best = s;
1379
+ }
1380
+ return best;
1381
+ }
1382
+ function edits(site, probe) {
1383
+ const hit = `${HIT}(${probe})`;
1384
+ const open = (text) => ({ at: site.at, text, order: [1, -site.end] });
1385
+ const close = (text) => ({ at: site.end, text, order: [0, -site.start] });
1386
+ switch (site.kind) {
1387
+ case "statement":
1388
+ case "block":
1389
+ return [open(`;${hit};`)];
1390
+ case "lone":
1391
+ return [open(`{;${hit};`), close("}")];
1392
+ case "expression":
1393
+ return [open(`(${hit},`), close(")")];
1394
+ }
1395
+ }
1396
+ function applyEdits(src, all) {
1397
+ all.sort((a, b) => a.at - b.at || a.order[0] - b.order[0] || a.order[1] - b.order[1]);
1398
+ let out = "";
1399
+ let from = 0;
1400
+ for (const e of all) {
1401
+ out += src.slice(from, e.at) + e.text;
1402
+ from = e.at;
1403
+ }
1404
+ return out + src.slice(from);
1405
+ }
1406
+ function instrument(file, src, mutants, firstProbe) {
1407
+ const parsed = parseSync(file, src, PARSE_OPTIONS);
1408
+ if (parsed.errors.length > 0 || !isAstNode(parsed.program))
1409
+ return null;
1410
+ const sites = collectSites(parsed.program);
1411
+ const bySite = new Map;
1412
+ for (const m of mutants) {
1413
+ const site = innermost(sites, m.start, m.end);
1414
+ if (!site)
1415
+ return null;
1416
+ bySite.set(site, [...bySite.get(site) ?? [], m.id]);
1417
+ }
1418
+ const probes = [];
1419
+ const all = [];
1420
+ for (const [site, ids] of bySite) {
1421
+ all.push(...edits(site, firstProbe + probes.length));
1422
+ probes.push(ids);
1423
+ }
1424
+ const code = applyEdits(src, all);
1425
+ if (parseSync(file, code, PARSE_OPTIONS).errors.length > 0)
1426
+ return null;
1427
+ return { code, probes };
1428
+ }
1429
+
1430
+ // tools/mutate/src/engine/coverage.ts
1431
+ var COVERAGE_VERSION = 1;
1432
+ var COVERAGE_TIMEOUT_MS = 600000;
1433
+ var MAX_PATTERN = 8000;
1434
+ var numbers = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "number") : [];
1435
+ function parseHits(raw) {
1436
+ if (!isRecord(raw) || !Array.isArray(raw["files"]))
1437
+ return null;
1438
+ return {
1439
+ served: numbers(raw["served"]),
1440
+ outside: numbers(raw["outside"]),
1441
+ files: raw["files"].filter(isRecord).map((f) => ({
1442
+ load: numbers(f["load"]),
1443
+ between: numbers(f["between"]),
1444
+ tests: Array.isArray(f["tests"]) ? f["tests"].map(numbers) : [],
1445
+ overlapped: f["overlapped"] === true
1446
+ }))
1447
+ };
1448
+ }
1449
+ function real(path) {
1450
+ try {
1451
+ return realpathSync2(path);
1452
+ } catch {
1453
+ return path;
1454
+ }
1455
+ }
1456
+ function chunk(items, n) {
1457
+ const count = Math.max(1, Math.min(n, items.length));
1458
+ const size = Math.ceil(items.length / count);
1459
+ const out = [];
1460
+ for (let i = 0;i < items.length; i += size)
1461
+ out.push(items.slice(i, i + size));
1462
+ return out;
1463
+ }
1464
+ function newProbeHits() {
1465
+ return { tests: new Set, files: new Set, loads: new Set, static: false };
1466
+ }
1467
+
1468
+ class Attribution {
1469
+ cwd;
1470
+ probes = new Map;
1471
+ served = new Set;
1472
+ tests = {};
1473
+ byFile = {};
1474
+ constructor(cwd) {
1475
+ this.cwd = cwd;
1476
+ }
1477
+ at(probe) {
1478
+ let hits = this.probes.get(probe);
1479
+ if (!hits) {
1480
+ hits = newProbeHits();
1481
+ this.probes.set(probe, hits);
1482
+ }
1483
+ return hits;
1484
+ }
1485
+ record(c) {
1486
+ const id = testId(this.cwd, c.file, c.name, c.line);
1487
+ if (!this.tests[id]) {
1488
+ this.tests[id] = { id, file: c.file, name: c.name, line: c.line, filterName: c.filterName };
1489
+ const file = real(c.file);
1490
+ this.byFile[file] = [...this.byFile[file] ?? [], id];
1491
+ }
1492
+ return id;
1493
+ }
1494
+ add(testFiles, hits, cases) {
1495
+ for (const t of hits.served)
1496
+ this.served.add(t);
1497
+ for (const p of hits.outside)
1498
+ this.at(p).static = true;
1499
+ const ran = new Map;
1500
+ for (const c of cases) {
1501
+ if (c.status === "skipped")
1502
+ continue;
1503
+ const file = real(c.file);
1504
+ ran.set(file, [...ran.get(file) ?? [], c]);
1505
+ }
1506
+ hits.files.forEach((f, i) => {
1507
+ const file = testFiles[i];
1508
+ if (!file)
1509
+ return;
1510
+ const fileCases = ran.get(file) ?? [];
1511
+ const ids = fileCases.map((c) => this.record(c));
1512
+ for (const p of f.load) {
1513
+ const h = this.at(p);
1514
+ h.static = true;
1515
+ h.loads.add(file);
1516
+ }
1517
+ for (const p of f.between)
1518
+ this.at(p).files.add(file);
1519
+ const ordered = !f.overlapped && f.tests.length === ids.length;
1520
+ f.tests.forEach((probes, k) => {
1521
+ const id = ids[k];
1522
+ for (const p of probes) {
1523
+ if (ordered && id)
1524
+ this.at(p).tests.add(id);
1525
+ else
1526
+ this.at(p).files.add(file);
1527
+ }
1528
+ });
1529
+ });
1530
+ }
1531
+ }
1532
+ async function planTargets(run) {
1533
+ const plan = [];
1534
+ const probes = [];
1535
+ const failed = new Map;
1536
+ for (const [target, t] of run.targets.entries()) {
1537
+ const probed = instrument(t.file, await Bun.file(t.file).text(), t.mutants, probes.length);
1538
+ if (!probed) {
1539
+ failed.set(target, "its probed source does not parse");
1540
+ continue;
1541
+ }
1542
+ plan.push({ file: t.file, code: probed.code });
1543
+ for (const ids of probed.probes)
1544
+ probes.push({ target, ids });
1545
+ }
1546
+ return { plan, probes, failed };
1547
+ }
1548
+ function sorted(set) {
1549
+ return [...new Set(set)].sort();
1550
+ }
1551
+ function usersOf(t, attribution, mine) {
1552
+ const users = new Set(t.covering);
1553
+ for (const { probe } of mine) {
1554
+ const h = attribution.probes.get(probe);
1555
+ if (!h)
1556
+ continue;
1557
+ const testFiles = [...h.tests].flatMap((id) => {
1558
+ const file = attribution.tests[id]?.file;
1559
+ return file ? [real(file)] : [];
1560
+ });
1561
+ for (const f of [...testFiles, ...h.files, ...h.loads])
1562
+ users.add(f);
1563
+ }
1564
+ return users;
1565
+ }
1566
+ function targetCoverage(run, target, attribution, probes) {
1567
+ const t = run.targets[target];
1568
+ if (!t)
1569
+ return { kind: "static", reason: "missing target" };
1570
+ const mine = probes.flatMap((p, probe) => p.target === target ? [{ probe, ids: p.ids }] : []);
1571
+ if (!attribution.served.has(target) && t.covering.length > 0) {
1572
+ return {
1573
+ kind: "static",
1574
+ reason: "a test imports it but the coverage pass never loaded it (a project preload may)"
1575
+ };
1576
+ }
1577
+ const users = usersOf(t, attribution, mine);
1578
+ const mutants = {};
1579
+ for (const { probe, ids } of mine) {
1580
+ const h = attribution.probes.get(probe) ?? newProbeHits();
1581
+ const files = h.static ? [...users, ...h.files] : [...h.files];
1582
+ const cov = { tests: sorted(h.tests), files: sorted(files) };
1583
+ for (const id of ids)
1584
+ mutants[id] = cov;
1585
+ }
1586
+ return { kind: "dynamic", mutants };
1587
+ }
1588
+ async function collectCoverage(run) {
1589
+ const { plan, probes, failed } = await planTargets(run);
1590
+ const dir = mkdtempSync2(join7(tmpdir3(), "polly-mutate-coverage-"));
1591
+ try {
1592
+ const planPath = join7(dir, "plan.json");
1593
+ writeFileSync3(planPath, JSON.stringify({ targets: plan, tests: run.testFiles }));
1594
+ const attribution = new Attribution(run.cwd);
1595
+ const chunks = chunk(run.testFiles, run.concurrency);
1596
+ const outcomes = await pool(chunks, run.concurrency, async (files, i) => {
1597
+ const out = join7(dir, `hits-${i}.json`);
1598
+ const attempt = (workdirs) => inCwd(workdirs, run.cwd, async (cwd) => {
1599
+ rmSync3(out, { force: true });
1600
+ const outcome = await runBunTest({
1601
+ cwd,
1602
+ files,
1603
+ preloads: run.preloads,
1604
+ env: { POLLY_MUTATE_COVERAGE: planPath, POLLY_MUTATE_COVERAGE_OUT: out },
1605
+ contracts: run.contracts,
1606
+ bail: false,
1607
+ junit: true,
1608
+ timeoutMs: COVERAGE_TIMEOUT_MS,
1609
+ captureStderr: true
1610
+ });
1611
+ const file = Bun.file(out);
1612
+ const hits = await file.exists() ? parseHits(await file.json()) : null;
1613
+ return { outcome, hits, cwd };
1614
+ });
1615
+ const scratch = await attempt(run.workdirs);
1616
+ if (scratch.outcome.exitCode === 0 || !run.workdirs)
1617
+ return scratch;
1618
+ run.log(`coverage pass: process ${i + 1}/${chunks.length} is red in a scratch cwd; rerun in-tree`);
1619
+ return attempt(null);
1620
+ });
1621
+ for (const [i, { outcome, hits, cwd }] of outcomes.entries()) {
1622
+ if (!hits) {
1623
+ run.log(`coverage pass: process ${i + 1}/${chunks.length} wrote no data (${outcome.timedOut ? "timed out" : `exit ${outcome.exitCode}`}); every target keeps static selection`);
1624
+ return null;
1625
+ }
1626
+ if (outcome.exitCode !== 0) {
1627
+ const failLine = outcome.stderrTail?.match(/\(fail\)[^\n]*/)?.[0] ?? "";
1628
+ run.log(`coverage pass: tests failed in process ${i + 1}/${chunks.length} (exit ${outcome.exitCode}) ${failLine}`.trim());
1629
+ }
1630
+ attribution.add(run.testFiles, hits, parseJunit(outcome.junitXml ?? "", cwd));
1631
+ }
1632
+ const targets = run.targets.map((_, i) => {
1633
+ const reason = failed.get(i);
1634
+ if (reason)
1635
+ return { kind: "static", reason };
1636
+ return targetCoverage(run, i, attribution, probes);
1637
+ });
1638
+ return { targets, tests: attribution.tests, byFile: attribution.byFile };
1639
+ } finally {
1640
+ rmSync3(dir, { recursive: true, force: true });
1641
+ }
1642
+ }
1643
+ var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1644
+ function selectionFor(cov, coverage) {
1645
+ const named = cov.tests.flatMap((id) => {
1646
+ const t = coverage.tests[id];
1647
+ return t ? [t] : [];
1648
+ });
1649
+ const files = sorted([...cov.files, ...named.map((t) => real(t.file))]);
1650
+ const coveredBy = sorted([...cov.tests, ...cov.files.flatMap((f) => coverage.byFile[f] ?? [])]);
1651
+ if (cov.files.length > 0 || named.length === 0)
1652
+ return { files, coveredBy };
1653
+ const pattern = `^(?:${sorted(named.map((t) => escapeRegex(t.filterName))).join("|")})$`;
1654
+ return pattern.length > MAX_PATTERN ? { files, coveredBy } : { files, namePattern: pattern, coveredBy };
1655
+ }
1656
+
1657
+ // tools/mutate/src/engine/generate.ts
1658
+ import { parseSync as parseSync2 } from "oxc-parser";
1659
+
1660
+ // tools/mutate/src/engine/operators.ts
1661
+ import { mutate as mutateRegex } from "weapon-regex";
1662
+ var EQUALITY = {
1663
+ "<": ["<=", ">="],
1664
+ "<=": ["<", ">"],
1665
+ ">": [">=", "<="],
1666
+ ">=": [">", "<"],
1667
+ "==": ["!="],
1668
+ "!=": ["=="],
1669
+ "===": ["!=="],
1670
+ "!==": ["==="]
1671
+ };
1672
+ var ARITHMETIC = { "+": "-", "-": "+", "*": "/", "/": "*", "%": "*" };
1673
+ var LOGICAL = { "&&": "||", "||": "&&", "??": "&&" };
1674
+ var ASSIGNMENT = {
1675
+ "+=": "-=",
1676
+ "-=": "+=",
1677
+ "*=": "/=",
1678
+ "/=": "*=",
1679
+ "%=": "*=",
1680
+ "<<=": ">>=",
1681
+ ">>=": "<<=",
1682
+ "&=": "|=",
1683
+ "|=": "&=",
1684
+ "&&=": "||=",
1685
+ "||=": "&&=",
1686
+ "??=": "&&="
1687
+ };
1688
+ var STRING_SAFE_ASSIGNMENTS = new Set(["&&=", "||=", "??="]);
1689
+ var BOOLEAN_OPERATORS = new Set(["!=", "!==", "&&", "<", "<=", "==", "===", ">", ">=", "||"]);
1690
+ var LOOPS = new Set(["ForStatement", "WhileStatement", "DoWhileStatement"]);
1691
+ var EMPTY_STRING_REPLACEMENT = '"Stryker was here!"';
1692
+ var METHODS = (() => {
1693
+ const forward = [
1694
+ ["charAt", null],
1695
+ ["endsWith", "startsWith"],
1696
+ ["every", "some"],
1697
+ ["filter", null],
1698
+ ["reverse", null],
1699
+ ["slice", null],
1700
+ ["sort", null],
1701
+ ["substr", null],
1702
+ ["substring", null],
1703
+ ["toLocaleLowerCase", "toLocaleUpperCase"],
1704
+ ["toLowerCase", "toUpperCase"],
1705
+ ["trim", null],
1706
+ ["trimEnd", "trimStart"],
1707
+ ["min", "max"],
1708
+ ["setDate", "setTime"],
1709
+ ["setFullYear", "setMonth"],
1710
+ ["setHours", "setMinutes"],
1711
+ ["setSeconds", "setMilliseconds"],
1712
+ ["setUTCDate", "setTime"],
1713
+ ["setUTCFullYear", "setUTCMonth"],
1714
+ ["setUTCHours", "setUTCMinutes"],
1715
+ ["setUTCSeconds", "setUTCMilliseconds"]
1716
+ ];
1717
+ const map = new Map(forward);
1718
+ for (const [name, swap] of forward) {
1719
+ if (swap && name !== "setUTCDate" && name !== "getUTCDate")
1720
+ map.set(swap, name);
1721
+ }
1722
+ return map;
1723
+ })();
1724
+ function operatorOffset(src, op, left, right) {
1725
+ const gap = src.slice(left.end, right.start);
1726
+ const at = gap.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (c) => " ".repeat(c.length)).indexOf(op);
1727
+ return at === -1 ? -1 : left.end + at;
1728
+ }
1729
+ function isStringNode(node) {
1730
+ if (!node)
1731
+ return false;
1732
+ return node.type === "Literal" && typeof node["value"] === "string" || node.type === "TemplateLiteral";
1733
+ }
1734
+ var text = (src, node) => src.slice(node.start, node.end);
1735
+ function binaryParts(node, src) {
1736
+ const op = stringField(node, "operator");
1737
+ const left = child(node, "left");
1738
+ const right = child(node, "right");
1739
+ if (!op || !left || !right)
1740
+ return;
1741
+ const at = operatorOffset(src, op, left, right);
1742
+ return at === -1 ? undefined : { op, left, right, at };
1743
+ }
1744
+ var binary = (node, ctx) => {
1745
+ if (node.type !== "BinaryExpression")
1746
+ return;
1747
+ const parts = binaryParts(node, ctx.src);
1748
+ if (!parts)
1749
+ return;
1750
+ const { op, left, right, at } = parts;
1751
+ const span = (rep, mutator) => ctx.emit(at, at + op.length, rep, mutator);
1752
+ for (const rep of EQUALITY[op] ?? [])
1753
+ span(rep, "EqualityOperator");
1754
+ const arith = ARITHMETIC[op];
1755
+ const leftProbe = left.type === "BinaryExpression" ? child(left, "right") : left;
1756
+ if (arith && !isStringNode(right) && !isStringNode(leftProbe))
1757
+ span(arith, "ArithmeticOperator");
1758
+ };
1759
+ var logical = (node, ctx) => {
1760
+ if (node.type !== "LogicalExpression")
1761
+ return;
1762
+ const parts = binaryParts(node, ctx.src);
1763
+ const rep = parts && LOGICAL[parts.op];
1764
+ if (!parts || !rep)
1765
+ return;
1766
+ const { op, left, right, at } = parts;
1767
+ if (op !== "??") {
1768
+ ctx.emit(at, at + op.length, rep, "LogicalOperator");
1769
+ return;
1770
+ }
1771
+ const operand = (n) => n.type === "LogicalExpression" ? `(${text(ctx.src, n)})` : text(ctx.src, n);
1772
+ const slice = (from, to) => ctx.src.slice(from, to);
1773
+ ctx.emit(node.start, node.end, `(${slice(node.start, left.start)}${operand(left)}${slice(left.end, at)}${rep}${slice(at + op.length, right.start)}${operand(right)}${slice(right.end, node.end)})`, "LogicalOperator");
1774
+ };
1775
+ var assignment = (node, ctx) => {
1776
+ if (node.type !== "AssignmentExpression")
1777
+ return;
1778
+ const parts = binaryParts(node, ctx.src);
1779
+ const rep = parts && ASSIGNMENT[parts.op];
1780
+ if (!parts || !rep)
1781
+ return;
1782
+ if (isStringNode(parts.right) && !STRING_SAFE_ASSIGNMENTS.has(parts.op))
1783
+ return;
1784
+ ctx.emit(parts.at, parts.at + parts.op.length, rep, "AssignmentOperator");
1785
+ };
1786
+ var booleanLiteral = (node, ctx) => {
1787
+ if (node.type === "Literal" && typeof node["value"] === "boolean") {
1788
+ ctx.emit(node.start, node.end, String(!node["value"]), "BooleanLiteral");
1789
+ }
1790
+ if (node.type === "UnaryExpression" && node["operator"] === "!") {
1791
+ ctx.emit(node.start, node.start + 1, "", "BooleanLiteral");
1792
+ }
1793
+ };
1794
+ var UNARY = { "+": "-", "-": "+", "~": "" };
1795
+ var unary = (node, ctx) => {
1796
+ if (node.type !== "UnaryExpression")
1797
+ return;
1798
+ const op = stringField(node, "operator");
1799
+ const rep = op === undefined ? undefined : UNARY[op];
1800
+ if (rep !== undefined)
1801
+ ctx.emit(node.start, node.start + 1, rep, "UnaryOperator");
1802
+ };
1803
+ var update = (node, ctx) => {
1804
+ if (node.type !== "UpdateExpression")
1805
+ return;
1806
+ const op = stringField(node, "operator");
1807
+ const arg = child(node, "argument");
1808
+ if (!op || !arg)
1809
+ return;
1810
+ const at = node["prefix"] === true ? node.start : arg.end;
1811
+ const opAt = ctx.src.indexOf(op, at);
1812
+ if (opAt === -1 || opAt >= node.end)
1813
+ return;
1814
+ ctx.emit(opAt, opAt + 2, op === "++" ? "--" : "++", "UpdateOperator");
1815
+ };
1816
+ function isStructuralString(node, ctx) {
1817
+ const p = ctx.parent;
1818
+ if (!p)
1819
+ return false;
1820
+ if (p.type.startsWith("Export") || p.type === "ImportExpression")
1821
+ return true;
1822
+ if (p.type === "JSXAttribute" || p.type === "ExpressionStatement")
1823
+ return true;
1824
+ if ((p.type === "Property" || p.type === "PropertyDefinition") && child(p, "key") === node) {
1825
+ return true;
1826
+ }
1827
+ if (p.type !== "CallExpression")
1828
+ return false;
1829
+ const callee = child(p, "callee");
1830
+ return callee?.type === "Identifier" && (callee["name"] === "require" || callee["name"] === "Symbol");
1831
+ }
1832
+ var stringLiteral = (node, ctx) => {
1833
+ if (node.type === "TemplateLiteral") {
1834
+ const quasis = children(node, "quasis");
1835
+ const value = quasis[0]?.["value"];
1836
+ const empty = quasis.length === 1 && isRecord(value) && value["raw"] === "";
1837
+ ctx.emit(node.start, node.end, empty ? "`Stryker was here!`" : "``", "StringLiteral");
1838
+ return;
1839
+ }
1840
+ if (node.type !== "Literal" || typeof node["value"] !== "string")
1841
+ return;
1842
+ if (isStructuralString(node, ctx))
1843
+ return;
1844
+ ctx.emit(node.start, node.end, node["value"] === "" ? EMPTY_STRING_REPLACEMENT : '""', "StringLiteral");
1845
+ };
1846
+ function isBooleanExpression(node) {
1847
+ if (node.type !== "BinaryExpression" && node.type !== "LogicalExpression")
1848
+ return false;
1849
+ const op = stringField(node, "operator");
1850
+ return op !== undefined && BOOLEAN_OPERATORS.has(op);
1851
+ }
1852
+ function conditionalTest(node, ctx) {
1853
+ const p = ctx.parent;
1854
+ const emit = (rep) => ctx.emit(node.start, node.end, rep, "ConditionalExpression");
1855
+ if (p && ctx.key === "test" && LOOPS.has(p.type)) {
1856
+ emit("false");
1857
+ return true;
1858
+ }
1859
+ if (p?.type === "IfStatement" && ctx.key === "test") {
1860
+ emit("true");
1861
+ emit("false");
1862
+ return true;
1863
+ }
1864
+ if (!isBooleanExpression(node))
1865
+ return false;
1866
+ const parentOp = p?.type === "LogicalExpression" ? stringField(p, "operator") : undefined;
1867
+ if (parentOp !== "||")
1868
+ emit("true");
1869
+ if (parentOp !== "&&")
1870
+ emit("false");
1871
+ return true;
1872
+ }
1873
+ function forWithoutTest(node, ctx) {
1874
+ const init = child(node, "init");
1875
+ const open = ctx.src.indexOf("(", node.start);
1876
+ const semi = open === -1 ? -1 : ctx.src.indexOf(";", init ? init.end : open);
1877
+ if (semi !== -1)
1878
+ ctx.emit(semi + 1, semi + 1, "false", "ConditionalExpression");
1879
+ }
1880
+ function emptySwitchCase(node, ctx) {
1881
+ const body = children(node, "consequent");
1882
+ const first = body[0];
1883
+ const last = body[body.length - 1];
1884
+ if (first && last)
1885
+ ctx.emit(first.start, last.end, "", "ConditionalExpression");
1886
+ }
1887
+ var conditional = (node, ctx) => {
1888
+ if (conditionalTest(node, ctx))
1889
+ return;
1890
+ if (node.type === "ForStatement" && !child(node, "test"))
1891
+ forWithoutTest(node, ctx);
1892
+ if (node.type === "SwitchCase")
1893
+ emptySwitchCase(node, ctx);
1894
+ };
1895
+ function containsSuperCall(node) {
1896
+ if (node.type === "CallExpression" && child(node, "callee")?.type === "Super")
1897
+ return true;
1898
+ for (const value of Object.values(node)) {
1899
+ const list = Array.isArray(value) ? value : [value];
1900
+ for (const c of list)
1901
+ if (isAstNode(c) && containsSuperCall(c))
1902
+ return true;
1903
+ }
1904
+ return false;
1905
+ }
1906
+ function isInvalidConstructorBody(ctx, block) {
1907
+ const n = ctx.ancestors.length;
1908
+ const fn = ctx.ancestors[n - 1];
1909
+ const method = ctx.ancestors[n - 2];
1910
+ const classBody = ctx.ancestors[n - 3];
1911
+ if (!fn || method?.type !== "MethodDefinition" || method["kind"] !== "constructor")
1912
+ return false;
1913
+ const paramProps = children(fn, "params").some((param) => param.type === "TSParameterProperty");
1914
+ const initialisedFields = classBody?.type === "ClassBody" && children(classBody, "body").some((m) => m.type === "PropertyDefinition" && child(m, "value") !== undefined && child(m, "key")?.type !== "PrivateIdentifier");
1915
+ return (paramProps || initialisedFields) && containsSuperCall(block);
1916
+ }
1917
+ var block = (node, ctx) => {
1918
+ if (node.type !== "BlockStatement" || children(node, "body").length === 0)
1919
+ return;
1920
+ if (isInvalidConstructorBody(ctx, node))
1921
+ return;
1922
+ ctx.emit(node.start, node.end, "{}", "BlockStatement");
1923
+ };
1924
+ var arrayDeclaration = (node, ctx) => {
1925
+ if (node.type === "ArrayExpression") {
1926
+ const empty = children(node, "elements").length === 0;
1927
+ ctx.emit(node.start, node.end, empty ? '["Stryker was here"]' : "[]", "ArrayDeclaration");
1928
+ return;
1929
+ }
1930
+ if (node.type !== "CallExpression" && node.type !== "NewExpression")
1931
+ return;
1932
+ const callee = child(node, "callee");
1933
+ if (callee?.type !== "Identifier" || callee["name"] !== "Array")
1934
+ return;
1935
+ const args = children(node, "arguments").length === 0 ? "[]" : "";
1936
+ const prefix = node.type === "NewExpression" ? "new " : "";
1937
+ ctx.emit(node.start, node.end, `${prefix}Array(${args})`, "ArrayDeclaration");
1938
+ };
1939
+ var objectLiteral = (node, ctx) => {
1940
+ if (node.type === "ObjectExpression" && children(node, "properties").length > 0) {
1941
+ ctx.emit(node.start, node.end, "{}", "ObjectLiteral");
1942
+ }
1943
+ };
1944
+ var arrowFunction = (node, ctx) => {
1945
+ if (node.type !== "ArrowFunctionExpression")
1946
+ return;
1947
+ const body = child(node, "body");
1948
+ if (!body || body.type === "BlockStatement" || node["expression"] === false)
1949
+ return;
1950
+ if (body.type === "Identifier" && body["name"] === "undefined")
1951
+ return;
1952
+ ctx.emit(node.start, node.end, "() => undefined", "ArrowFunction");
1953
+ };
1954
+ var optionalChaining = (node, ctx) => {
1955
+ if (node["optional"] !== true)
1956
+ return;
1957
+ if (node.type === "MemberExpression") {
1958
+ const object = child(node, "object");
1959
+ if (!object)
1960
+ return;
1961
+ const q = ctx.src.indexOf("?.", object.end);
1962
+ if (q === -1 || q >= node.end)
1963
+ return;
1964
+ ctx.emit(q, q + 2, node["computed"] === true ? "" : ".", "OptionalChaining");
1965
+ }
1966
+ if (node.type === "CallExpression") {
1967
+ const callee = child(node, "callee");
1968
+ if (!callee)
1969
+ return;
1970
+ const q = ctx.src.indexOf("?.", callee.end);
1971
+ if (q === -1 || q >= node.end)
1972
+ return;
1973
+ ctx.emit(q, q + 2, "", "OptionalChaining");
1974
+ }
1975
+ };
1976
+ var methodExpression = (node, ctx) => {
1977
+ if (node.type !== "CallExpression")
1978
+ return;
1979
+ const callee = child(node, "callee");
1980
+ if (callee?.type !== "MemberExpression" || callee["computed"] === true)
1981
+ return;
1982
+ const property = child(callee, "property");
1983
+ const object = child(callee, "object");
1984
+ if (property?.type !== "Identifier" || !object)
1985
+ return;
1986
+ const name = stringField(property, "name");
1987
+ const swap = name === undefined ? undefined : METHODS.get(name);
1988
+ if (swap === undefined)
1989
+ return;
1990
+ if (swap === null)
1991
+ ctx.emit(node.start, node.end, text(ctx.src, object), "MethodExpression");
1992
+ else
1993
+ ctx.emit(property.start, property.end, swap, "MethodExpression");
1994
+ };
1995
+ function regexPatterns(pattern, flags) {
1996
+ if (pattern.length === 0)
1997
+ return [];
1998
+ try {
1999
+ return mutateRegex(pattern, flags, { mutationLevels: [1] }).map((m) => m.pattern);
2000
+ } catch {
2001
+ return [];
2002
+ }
2003
+ }
2004
+ var regex = (node, ctx) => {
2005
+ if (node.type !== "Literal")
2006
+ return;
2007
+ const literal = node["regex"];
2008
+ if (isRecord(literal)) {
2009
+ const pattern = literal["pattern"];
2010
+ const flags = typeof literal["flags"] === "string" ? literal["flags"] : "";
2011
+ if (typeof pattern !== "string")
2012
+ return;
2013
+ for (const p of regexPatterns(pattern, flags)) {
2014
+ ctx.emit(node.start, node.end, `/${p}/${flags}`, "Regex");
2015
+ }
2016
+ return;
2017
+ }
2018
+ const p = ctx.parent;
2019
+ if (typeof node["value"] !== "string" || p?.type !== "NewExpression")
2020
+ return;
2021
+ if (calleeName(p) !== "RegExp" || child(p, "callee")?.type !== "Identifier")
2022
+ return;
2023
+ const [first, second] = children(p, "arguments");
2024
+ if (first !== node)
2025
+ return;
2026
+ const flags = second?.type === "Literal" ? stringField(second, "value") : undefined;
2027
+ for (const pattern of regexPatterns(node["value"], flags)) {
2028
+ ctx.emit(node.start, node.end, JSON.stringify(pattern), "Regex");
2029
+ }
2030
+ };
2031
+ var OPERATORS = [
2032
+ binary,
2033
+ logical,
2034
+ assignment,
2035
+ booleanLiteral,
2036
+ unary,
2037
+ update,
2038
+ stringLiteral,
2039
+ regex,
2040
+ conditional,
2041
+ block,
2042
+ arrayDeclaration,
2043
+ objectLiteral,
2044
+ arrowFunction,
2045
+ optionalChaining,
2046
+ methodExpression
2047
+ ];
2048
+
2049
+ // tools/mutate/src/engine/verify-callsites.ts
2050
+ var VERIFY_PRIMITIVES = new Set([
2051
+ "requires",
2052
+ "ensures",
2053
+ "invariant",
2054
+ "stateConstraint",
2055
+ "forAllPeers",
2056
+ "somePeer"
2057
+ ]);
2058
+ function verifyCallsiteReason(name) {
2059
+ return `Inside polly's ${name}(...) — a runtime no-op (compiled away in production, ` + `translated to a TLA+ assertion in verification). No test can observe or kill ` + `mutations here, so they are excluded from the score (polly#143).`;
2060
+ }
2061
+
2062
+ // tools/mutate/src/engine/generate.ts
2063
+ var TS_RUNTIME_WRAPPERS = new Set([
2064
+ "TSAsExpression",
2065
+ "TSSatisfiesExpression",
2066
+ "TSNonNullExpression",
2067
+ "TSInstantiationExpression",
2068
+ "TSTypeAssertion",
2069
+ "TSParameterProperty",
2070
+ "TSModuleBlock"
2071
+ ]);
2072
+ var PARSE_OPTIONS2 = { preserveParens: false };
2073
+ var TYPE_KEYS = new Set(["typeAnnotation", "returnType", "typeParameters", "typeArguments"]);
2074
+ var SKIPPED_STATEMENTS = new Set(["ImportDeclaration", "ExportAllDeclaration", "Decorator"]);
2075
+ function isSkipped(node) {
2076
+ if (SKIPPED_STATEMENTS.has(node.type))
2077
+ return true;
2078
+ if (node.type === "VariableDeclaration")
2079
+ return node["declare"] === true;
2080
+ if (node.type === "TSModuleDeclaration")
2081
+ return node["declare"] === true;
2082
+ return node.type.startsWith("TS") && !TS_RUNTIME_WRAPPERS.has(node.type);
2083
+ }
2084
+ function lineIndex(src) {
2085
+ const starts = [0];
2086
+ for (let i = 0;i < src.length; i++)
2087
+ if (src.charCodeAt(i) === 10)
2088
+ starts.push(i + 1);
2089
+ return (offset) => {
2090
+ let lo = 0;
2091
+ let hi = starts.length - 1;
2092
+ while (lo < hi) {
2093
+ const mid = lo + hi + 1 >> 1;
2094
+ if ((starts[mid] ?? 0) <= offset)
2095
+ lo = mid;
2096
+ else
2097
+ hi = mid - 1;
2098
+ }
2099
+ return { line: lo + 1, column: offset - (starts[lo] ?? 0) + 1 };
2100
+ };
2101
+ }
2102
+ function applyMutant(src, m) {
2103
+ return src.slice(0, m.start) + m.replacement + src.slice(m.end);
2104
+ }
2105
+ function verifyReason(node) {
2106
+ if (node.type !== "CallExpression")
2107
+ return;
2108
+ const name = calleeName(node);
2109
+ return name && VERIFY_PRIMITIVES.has(name) ? verifyCallsiteReason(name) : undefined;
2110
+ }
2111
+ var FUNCTION_NODES = new Set([
2112
+ "FunctionDeclaration",
2113
+ "FunctionExpression",
2114
+ "ArrowFunctionExpression"
2115
+ ]);
2116
+ function contractSite(file, node, ancestors, position) {
2117
+ if (node.type !== "CallExpression")
2118
+ return;
2119
+ const name = calleeName(node);
2120
+ if (name !== "requires" && name !== "ensures")
2121
+ return;
2122
+ const second = children(node, "arguments")[1];
2123
+ const message = second?.type === "Literal" && typeof second["value"] === "string" ? second["value"] : undefined;
2124
+ const handlerNode = [...ancestors].reverse().find((a) => a.type === "CallExpression" && calleeName(a) === "on") ?? [...ancestors].reverse().find((a) => FUNCTION_NODES.has(a.type));
2125
+ const handler = handlerNode ? { from: position(handlerNode.start).line, to: position(handlerNode.end).line } : undefined;
2126
+ return {
2127
+ file,
2128
+ line: position(node.start).line,
2129
+ primitive: name,
2130
+ ...message === undefined ? {} : { message },
2131
+ ...handler ? { handler } : {}
2132
+ };
2133
+ }
2134
+ function runtimeChildren(node) {
2135
+ const out = [];
2136
+ for (const [k, value] of Object.entries(node)) {
2137
+ if (TYPE_KEYS.has(k))
2138
+ continue;
2139
+ const list = Array.isArray(value) ? value : [value];
2140
+ for (const c of list)
2141
+ if (isAstNode(c))
2142
+ out.push([k, c]);
2143
+ }
2144
+ return out;
2145
+ }
2146
+ function generateMutants(file, src, opts = {}) {
2147
+ const parsed = parseSync2(file, src, PARSE_OPTIONS2);
2148
+ const first = parsed.errors[0];
2149
+ if (first)
2150
+ throw new Error(`${file}: cannot parse target: ${first.message}`);
2151
+ const position = lineIndex(src);
2152
+ const ignoreVerify = opts.ignoreVerifyCallsites ?? true;
2153
+ const prefix = opts.idPrefix ?? "";
2154
+ const seen = new Set;
2155
+ const excluded = new Set(opts.exclude ?? []);
2156
+ const all = [];
2157
+ const contracts = [];
2158
+ const ancestors = [];
2159
+ const visit = (node, key, ignored) => {
2160
+ if (isSkipped(node))
2161
+ return;
2162
+ const parent = ancestors[ancestors.length - 1];
2163
+ const site = contractSite(file, node, ancestors, position);
2164
+ if (site)
2165
+ contracts.push(site);
2166
+ const ignoredHere = ignored ?? (ignoreVerify ? verifyReason(node) : undefined);
2167
+ const ctx = {
2168
+ src,
2169
+ parent,
2170
+ key,
2171
+ ancestors,
2172
+ emit(start, end, replacement, mutatorName) {
2173
+ if (excluded.has(mutatorName))
2174
+ return;
2175
+ const dedupe = `${start}:${end}:${replacement}`;
2176
+ if (seen.has(dedupe))
2177
+ return;
2178
+ seen.add(dedupe);
2179
+ all.push({
2180
+ id: "",
2181
+ file,
2182
+ mutatorName,
2183
+ start,
2184
+ end,
2185
+ replacement,
2186
+ location: { start: position(start), end: position(end) },
2187
+ ...ignoredHere ? { ignoredReason: ignoredHere } : {}
2188
+ });
2189
+ }
2190
+ };
2191
+ for (const op of OPERATORS)
2192
+ op(node, ctx);
2193
+ ancestors.push(node);
2194
+ for (const [k, c] of runtimeChildren(node))
2195
+ visit(c, k, ignoredHere);
2196
+ ancestors.pop();
2197
+ };
2198
+ for (const statement of parsed.program.body) {
2199
+ if (isAstNode(statement))
2200
+ visit(statement, "body", undefined);
2201
+ }
2202
+ const inRange = opts.lines ? all.filter((m) => m.location.start.line >= (opts.lines?.from ?? 0) && m.location.start.line <= (opts.lines?.to ?? 0)) : all;
2203
+ inRange.sort((a, b) => a.start - b.start || a.end - b.end);
2204
+ inRange.forEach((m, i) => {
2205
+ m.id = `${prefix}${i}`;
2206
+ });
2207
+ const mutants = [];
2208
+ const compileErrors = [];
2209
+ for (const m of inRange) {
2210
+ if (parseSync2(file, applyMutant(src, m), PARSE_OPTIONS2).errors.length > 0)
2211
+ compileErrors.push(m);
2212
+ else
2213
+ mutants.push(m);
2214
+ }
2215
+ return { mutants, compileErrors, contracts };
2216
+ }
2217
+
2218
+ // tools/mutate/src/engine/graph.ts
2219
+ import { realpathSync as realpathSync3 } from "node:fs";
2220
+ import { dirname as dirname4, extname } from "node:path";
2221
+ import { Glob as Glob2 } from "bun";
2222
+ var SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
2223
+ function loaderFor(file) {
2224
+ const ext = extname(file);
2225
+ if (ext === ".tsx")
2226
+ return "tsx";
2227
+ if (ext === ".jsx")
2228
+ return "jsx";
2229
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts")
2230
+ return "ts";
2231
+ return "js";
2232
+ }
2233
+ function real2(path) {
2234
+ try {
2235
+ return realpathSync3(path);
2236
+ } catch {
2237
+ return path;
2238
+ }
2239
+ }
2240
+ async function findTestFiles(cwd, include) {
2241
+ const found = new Set;
2242
+ for (const pattern of include) {
2243
+ for await (const f of new Glob2(pattern).scan({ cwd, absolute: true, onlyFiles: true })) {
2244
+ if (!f.includes("/node_modules/"))
2245
+ found.add(real2(f));
2246
+ }
2247
+ }
2248
+ return [...found].sort();
2249
+ }
2250
+ var transpilers = new Map;
2251
+ function scan(file, text) {
2252
+ const loader = loaderFor(file);
2253
+ let t = transpilers.get(loader);
2254
+ if (!t) {
2255
+ t = new Bun.Transpiler({ loader });
2256
+ transpilers.set(loader, t);
2257
+ }
2258
+ try {
2259
+ return t.scanImports(text).map((i) => i.path);
2260
+ } catch {
2261
+ return [];
2262
+ }
2263
+ }
2264
+ function resolveImports(file, text) {
2265
+ const out = [];
2266
+ for (const spec of scan(file, text)) {
2267
+ if (spec.startsWith("bun:") || spec.startsWith("node:"))
2268
+ continue;
2269
+ let resolved;
2270
+ try {
2271
+ resolved = real2(Bun.resolveSync(spec, dirname4(file)));
2272
+ } catch {
2273
+ continue;
2274
+ }
2275
+ if (!resolved.includes("/node_modules/") && SOURCE_EXTENSIONS.has(extname(resolved))) {
2276
+ out.push(resolved);
2277
+ }
2278
+ }
2279
+ return out;
2280
+ }
2281
+ async function buildImportGraph(testFiles) {
2282
+ const imports = new Map;
2283
+ const queue = [...testFiles];
2284
+ for (let file = queue.pop();file !== undefined; file = queue.pop()) {
2285
+ if (imports.has(file))
2286
+ continue;
2287
+ const out = resolveImports(file, await Bun.file(file).text());
2288
+ imports.set(file, out);
2289
+ queue.push(...out.filter((f) => !imports.has(f)));
2290
+ }
2291
+ return { testFiles, imports };
2292
+ }
2293
+ function importersOf(graph) {
2294
+ const importers = new Map;
2295
+ for (const [from, tos] of graph.imports) {
2296
+ for (const to of tos)
2297
+ importers.set(to, [...importers.get(to) ?? [], from]);
2298
+ }
2299
+ return importers;
2300
+ }
2301
+ function coveringTests(graph, target) {
2302
+ const importers = importersOf(graph);
2303
+ const wanted = real2(target);
2304
+ const seen = new Set([wanted]);
2305
+ const stack = [wanted];
2306
+ for (let f = stack.pop();f !== undefined; f = stack.pop()) {
2307
+ const fresh = (importers.get(f) ?? []).filter((p) => !seen.has(p));
2308
+ for (const p of fresh)
2309
+ seen.add(p);
2310
+ stack.push(...fresh);
2311
+ }
2312
+ const tests = new Set(graph.testFiles);
2313
+ return [...seen].filter((f) => tests.has(f)).sort();
2314
+ }
2315
+ function closureOf(graph, files) {
2316
+ const seen = new Set(files);
2317
+ const stack = [...files];
2318
+ for (let f = stack.pop();f !== undefined; f = stack.pop()) {
2319
+ for (const next of graph.imports.get(f) ?? []) {
2320
+ if (!seen.has(next)) {
2321
+ seen.add(next);
2322
+ stack.push(next);
2323
+ }
2324
+ }
2325
+ }
2326
+ return [...seen].sort();
2327
+ }
2328
+
2329
+ // tools/mutate/src/engine/report-writer.ts
2330
+ import { mkdirSync as mkdirSync3 } from "node:fs";
2331
+ import { dirname as dirname5, relative as relative4 } from "node:path";
2332
+ var ENGINE_NAME = "polly mutate (bun engine)";
2333
+ async function toMutationReport(result, cwd, meta) {
2334
+ const files = {};
2335
+ const testFiles = {};
2336
+ for (const target of result.targets) {
2337
+ const rel = relative4(cwd, target.file);
2338
+ files[rel] = {
2339
+ language: target.file.endsWith(".js") || target.file.endsWith(".jsx") ? "javascript" : "typescript",
2340
+ source: await Bun.file(target.file).text(),
2341
+ mutants: target.results.map((r) => ({
2342
+ id: r.mutant.id,
2343
+ mutatorName: r.mutant.mutatorName,
2344
+ replacement: r.mutant.replacement,
2345
+ status: r.status,
2346
+ ...r.statusReason ? { statusReason: r.statusReason } : {},
2347
+ location: r.mutant.location,
2348
+ killedBy: r.killedBy ?? [],
2349
+ coveredBy: r.coveredBy ?? [],
2350
+ killedByContract: r.killedByContract ?? [],
2351
+ ...r.contractOnly ? { contractOnly: true } : {}
2352
+ }))
2353
+ };
2354
+ for (const t of target.coveringTests)
2355
+ testFiles[relative4(cwd, t)] ??= { tests: [] };
2356
+ for (const t of target.tests) {
2357
+ const rel = relative4(cwd, t.file);
2358
+ testFiles[rel] ??= { tests: [] };
2359
+ const entry = testFiles[rel];
2360
+ if (!entry.tests.some((x) => x.id === t.id)) {
2361
+ entry.tests.push({
2362
+ id: t.id,
2363
+ name: t.name,
2364
+ location: { start: { line: t.line, column: 1 } }
2365
+ });
2366
+ }
2367
+ }
2368
+ }
2369
+ const sites = result.targets.flatMap((t) => t.contracts.map((c) => ({
2370
+ id: `${relative4(cwd, c.file)}:${c.line}`,
2371
+ file: relative4(cwd, c.file),
2372
+ line: c.line,
2373
+ primitive: c.primitive,
2374
+ ...c.message === undefined ? {} : { message: c.message },
2375
+ ...c.handler ? { handler: c.handler } : {}
2376
+ })));
2377
+ return {
2378
+ schemaVersion: "1",
2379
+ thresholds: { high: 80, low: 60 },
2380
+ framework: { name: ENGINE_NAME },
2381
+ files,
2382
+ testFiles,
2383
+ contracts: {
2384
+ mode: meta.contracts,
2385
+ runner: meta.runner,
2386
+ sites,
2387
+ violations: result.contractViolations.map((v) => ({
2388
+ target: relative4(cwd, v.target),
2389
+ test: v.test,
2390
+ contracts: v.contracts
2391
+ }))
2392
+ }
2393
+ };
2394
+ }
2395
+ async function writeReport(report, path) {
2396
+ mkdirSync3(dirname5(path), { recursive: true });
2397
+ await Bun.write(path, `${JSON.stringify(report, null, 2)}
2398
+ `);
2399
+ }
2400
+
2401
+ // tools/mutate/src/engine/stray-writes.ts
2402
+ function git(cwd, args) {
2403
+ const proc = Bun.spawnSync(["git", "-C", cwd, ...args], { stdout: "pipe", stderr: "ignore" });
2404
+ return proc.exitCode === 0 ? proc.stdout.toString() : null;
2405
+ }
2406
+ function snapshotWorktree(cwd) {
2407
+ const root = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
2408
+ if (!root)
2409
+ return null;
2410
+ const out = git(root, [
2411
+ "status",
2412
+ "--porcelain=v1",
2413
+ "-z",
2414
+ "--untracked-files=all",
2415
+ "--ignored=matching"
2416
+ ]);
2417
+ if (out === null)
2418
+ return null;
2419
+ const entries = new Set;
2420
+ const tokens = out.split("\x00");
2421
+ for (let i = 0;i < tokens.length; i++) {
2422
+ const token = tokens[i];
2423
+ if (!token)
2424
+ continue;
2425
+ entries.add(token);
2426
+ if (token[0] === "R" || token[0] === "C")
2427
+ i++;
2428
+ }
2429
+ return { root, entries };
2430
+ }
2431
+ function newPaths(before, after) {
2432
+ if (!before || !after || before.root !== after.root)
2433
+ return [];
2434
+ const paths = new Set;
2435
+ for (const entry of after.entries)
2436
+ if (!before.entries.has(entry))
2437
+ paths.add(entry.slice(3));
2438
+ return [...paths].sort();
2439
+ }
2440
+
2441
+ // tools/mutate/src/engine/typecheck.ts
2442
+ import { existsSync as existsSync8 } from "node:fs";
2443
+ import { dirname as dirname6, join as join8, relative as relative5 } from "node:path";
2444
+ var TYPECHECK_OVERRIDES = {
2445
+ allowUnreachableCode: true,
2446
+ noUnusedLocals: false,
2447
+ noUnusedParameters: false
2448
+ };
2449
+ var TYPECHECK_CONFIG_NAME = "tsconfig.polly-mutate.json";
2450
+ var REASON_LIMIT = 300;
2451
+ async function loadApi() {
2452
+ try {
2453
+ return await import("typescript-7/unstable/async");
2454
+ } catch {
2455
+ return null;
2456
+ }
2457
+ }
2458
+ function tsconfigCandidates(file) {
2459
+ const out = [];
2460
+ let dir = dirname6(file);
2461
+ for (;; ) {
2462
+ const candidate = join8(dir, "tsconfig.json");
2463
+ if (existsSync8(candidate))
2464
+ out.push(candidate);
2465
+ const parent = dirname6(dir);
2466
+ if (parent === dir)
2467
+ return out;
2468
+ dir = parent;
2469
+ }
2470
+ }
2471
+ function virtualConfigFor(tsconfig) {
2472
+ return join8(dirname6(tsconfig), TYPECHECK_CONFIG_NAME);
2473
+ }
2474
+ var VIRTUAL_CONFIG_TEXT = JSON.stringify({
2475
+ extends: "./tsconfig.json",
2476
+ compilerOptions: TYPECHECK_OVERRIDES
2477
+ });
2478
+ function errorKeys(api, diagnostics) {
2479
+ return diagnostics.filter((d) => d.category === api.DiagnosticCategory.Error).map((d) => `${d.code}|${d.text}`);
2480
+ }
2481
+ function reasonOf(key) {
2482
+ const sep = key.indexOf("|");
2483
+ const text = key.slice(sep + 1).replace(/\s+/g, " ");
2484
+ const reason = `TS${key.slice(0, sep)}: ${text}`;
2485
+ return reason.length > REASON_LIMIT ? `${reason.slice(0, REASON_LIMIT - 1)}…` : reason;
2486
+ }
2487
+
2488
+ class Session {
2489
+ mod;
2490
+ snapshot = null;
2491
+ overlay = new Map;
2492
+ opened = new Map;
2493
+ api;
2494
+ constructor(mod, cwd) {
2495
+ this.mod = mod;
2496
+ this.api = new mod.API({
2497
+ cwd,
2498
+ fs: {
2499
+ readFile: (f) => this.overlay.get(f),
2500
+ fileExists: (f) => this.overlay.has(f) ? true : undefined
2501
+ }
2502
+ });
2503
+ }
2504
+ async update(params) {
2505
+ const next = await this.api.updateSnapshot(params);
2506
+ await this.snapshot?.dispose();
2507
+ this.snapshot = next;
2508
+ return next;
2509
+ }
2510
+ program(config) {
2511
+ const project = this.snapshot?.getProject(config);
2512
+ if (!project)
2513
+ throw new Error(`polly mutate: tsgo lost the project ${config}`);
2514
+ return project.program;
2515
+ }
2516
+ async projectFor(file) {
2517
+ for (const tsconfig of tsconfigCandidates(file)) {
2518
+ let config = this.opened.get(tsconfig);
2519
+ if (config === undefined) {
2520
+ config = virtualConfigFor(tsconfig);
2521
+ this.overlay.set(config, VIRTUAL_CONFIG_TEXT);
2522
+ const snap = await this.update({ openProjects: [config] });
2523
+ if (!snap.getProject(config))
2524
+ config = null;
2525
+ this.opened.set(tsconfig, config);
2526
+ }
2527
+ if (config === null)
2528
+ continue;
2529
+ const project = this.snapshot?.getProject(config);
2530
+ if (project?.rootFiles.some((f) => samePath(f, file)))
2531
+ return config;
2532
+ }
2533
+ return null;
2534
+ }
2535
+ async errorsIn(config, file) {
2536
+ const program = this.program(config);
2537
+ const [syntactic, semantic] = await Promise.all([
2538
+ program.getSyntacticDiagnostics(file),
2539
+ program.getSemanticDiagnostics(file)
2540
+ ]);
2541
+ return [...errorKeys(this.mod, syntactic), ...errorKeys(this.mod, semantic)];
2542
+ }
2543
+ async check(config, target, src) {
2544
+ const invalid = new Map;
2545
+ const baseline = new Set(await this.errorsIn(config, target.file));
2546
+ try {
2547
+ for (const m of target.mutants) {
2548
+ this.overlay.set(target.file, applyMutant(src, m));
2549
+ await this.update({ fileChanges: { changed: [target.file] } });
2550
+ const fresh = (await this.errorsIn(config, target.file)).find((k) => !baseline.has(k));
2551
+ if (fresh !== undefined)
2552
+ invalid.set(m.id, reasonOf(fresh));
2553
+ }
2554
+ } finally {
2555
+ this.overlay.delete(target.file);
2556
+ await this.update({ fileChanges: { changed: [target.file] } });
2557
+ }
2558
+ return invalid;
2559
+ }
2560
+ async close() {
2561
+ await this.api.close();
2562
+ }
2563
+ }
2564
+ function samePath(a, b) {
2565
+ return a === b || a.toLowerCase() === b.toLowerCase();
2566
+ }
2567
+ async function typecheckMutants(targets, opts) {
2568
+ const log = opts.log ?? (() => {
2569
+ return;
2570
+ });
2571
+ const started = performance.now();
2572
+ const outcome = { invalid: new Map, skipped: [], checked: 0, wallMs: 0 };
2573
+ const withConfig = targets.filter((t) => {
2574
+ if (tsconfigCandidates(t.file).length > 0)
2575
+ return true;
2576
+ outcome.skipped.push({ file: t.file, reason: "no tsconfig.json above it" });
2577
+ return false;
2578
+ });
2579
+ if (withConfig.length === 0) {
2580
+ for (const s of outcome.skipped)
2581
+ log(`type filter: ${relative5(opts.cwd, s.file)}: ${s.reason}`);
2582
+ outcome.wallMs = Math.round(performance.now() - started);
2583
+ return outcome;
2584
+ }
2585
+ const mod = await loadApi();
2586
+ if (!mod) {
2587
+ log("type filter off: typescript-7 is not installed (bun add typescript-7@npm:typescript@7.0.2)");
2588
+ return null;
2589
+ }
2590
+ const session = new Session(mod, opts.cwd);
2591
+ try {
2592
+ for (const target of withConfig) {
2593
+ const config = await session.projectFor(target.file);
2594
+ if (!config) {
2595
+ outcome.skipped.push({ file: target.file, reason: "no tsconfig.json includes it" });
2596
+ continue;
2597
+ }
2598
+ const src = await Bun.file(target.file).text();
2599
+ const verdicts = await session.check(config, target, src);
2600
+ for (const [id, reason] of verdicts)
2601
+ outcome.invalid.set(id, reason);
2602
+ outcome.checked += target.mutants.length;
2603
+ }
2604
+ } finally {
2605
+ await session.close();
2606
+ }
2607
+ outcome.wallMs = Math.round(performance.now() - started);
2608
+ for (const s of outcome.skipped)
2609
+ log(`type filter: ${relative5(opts.cwd, s.file)}: ${s.reason}`);
2610
+ log(`type filter: ${outcome.invalid.size} of ${outcome.checked} mutants fail to type-check (${(outcome.wallMs / 1000).toFixed(1)} s)`);
2611
+ return outcome;
2612
+ }
2613
+
2614
+ // tools/mutate/src/engine/index.ts
2615
+ function projectFiles(cfg) {
2616
+ return [
2617
+ ...cfg.testPreload,
2618
+ ...["tsconfig.json", "bunfig.toml", "bun.lock"].map((f) => join9(cfg.cwd, f))
2619
+ ];
2620
+ }
2621
+ async function runEngine(cfg, hooks = {}) {
2622
+ if (cfg.runner.kind === "command" && cfg.mode === "matrix") {
2623
+ throw new Error("matrix mode needs per-test results; the command runner has none");
2624
+ }
2625
+ const workdirs = cfg.scratchCwd ? createWorkdirs(cfg.cwd) : null;
2626
+ try {
2627
+ return await run(cfg, hooks, workdirs);
2628
+ } finally {
2629
+ workdirs?.remove();
2630
+ }
2631
+ }
2632
+ async function generateAll(cfg, graph) {
2633
+ const out = [];
2634
+ for (const [index, target] of cfg.targets.entries()) {
2635
+ const file = realpathSync4(target.file);
2636
+ const { mutants, compileErrors, contracts } = generateMutants(file, await Bun.file(file).text(), {
2637
+ ignoreVerifyCallsites: cfg.ignoreVerifyCallsites,
2638
+ lines: target.lines,
2639
+ idPrefix: `${index}.`,
2640
+ exclude: cfg.excludeMutators
2641
+ });
2642
+ out.push({
2643
+ file,
2644
+ mutants,
2645
+ compileErrors,
2646
+ covering: graph ? coveringTests(graph, file) : [],
2647
+ contracts
2648
+ });
2649
+ }
2650
+ return out;
2651
+ }
2652
+ async function dynamicCoverage(cfg, graph, generated, preloads, workdirs, log) {
2653
+ const targets = generated.map((g) => ({
2654
+ file: g.file,
2655
+ mutants: g.mutants.filter((m) => !m.ignoredReason),
2656
+ covering: g.covering
2657
+ }));
2658
+ const key = cfg.cacheDir ? await cacheKey({
2659
+ mutants: targets.flatMap((t) => t.mutants),
2660
+ closure: [...graph.imports.keys()].sort(),
2661
+ projectFiles: projectFiles(cfg),
2662
+ settings: {
2663
+ coverage: COVERAGE_VERSION,
2664
+ targets: targets.map((t) => [t.file, t.mutants.length]),
2665
+ tests: graph.testFiles,
2666
+ contracts: cfg.contracts
2667
+ }
2668
+ }) : null;
2669
+ const cached = cfg.cacheDir && key ? await readCoverageCache(cfg.cacheDir, key) : null;
2670
+ if (cached) {
2671
+ log("coverage pass: from cache");
2672
+ return cached;
2673
+ }
2674
+ const started = performance.now();
2675
+ const coverage = await collectCoverage({
2676
+ cwd: cfg.cwd,
2677
+ testFiles: graph.testFiles,
2678
+ targets,
2679
+ preloads,
2680
+ concurrency: cfg.concurrency,
2681
+ workdirs,
2682
+ contracts: cfg.contracts,
2683
+ log
2684
+ });
2685
+ if (!coverage)
2686
+ return null;
2687
+ log(`coverage pass: ${Object.keys(coverage.tests).length} tests in ` + `${((performance.now() - started) / 1000).toFixed(1)} s`);
2688
+ if (cfg.cacheDir && key)
2689
+ writeCoverageCache(cfg.cacheDir, key, coverage);
2690
+ return coverage;
178
2691
  }
179
- function queryAll(db, sql) {
180
- return db.query(sql).all();
2692
+ function sortedUnique(items) {
2693
+ return [...new Set(items)].sort();
181
2694
  }
182
- function queryGet(db, sql) {
183
- return db.query(sql).get();
2695
+ function dynamicSelection(g, target, coverage) {
2696
+ const selections = new Map;
2697
+ for (const m of g.mutants) {
2698
+ const cov = target.mutants[m.id];
2699
+ if (cov)
2700
+ selections.set(m.id, selectionFor(cov, coverage));
2701
+ }
2702
+ const covering = sortedUnique([...selections.values()].flatMap((sel) => sel.files));
2703
+ const coverageTests = covering.flatMap((f) => (coverage.byFile[f] ?? []).flatMap((id) => {
2704
+ const t = coverage.tests[id];
2705
+ return t ? [{ id: t.id, file: t.file, name: t.name, line: t.line }] : [];
2706
+ }));
2707
+ return { covering, selections, coverageTests };
184
2708
  }
185
- async function loadMutationReport(path) {
186
- return await Bun.file(path).json();
2709
+ function selectionKey(mutants, selections) {
2710
+ if (!selections)
2711
+ return null;
2712
+ return mutants.map((m) => {
2713
+ const sel = selections.get(m.id);
2714
+ return [mutantSig(m), sel?.files ?? [], sel?.namePattern ?? ""];
2715
+ });
187
2716
  }
188
- if (false) {}
189
-
190
- // tools/mutate/src/decisions.ts
191
- var DEFAULT_LOG = ".polly/test-debt/decisions.jsonl";
192
- var VERDICTS = ["keep", "prune", "rewrite", "investigate"];
193
- function normalizeSource(src) {
194
- return src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1").replace(/\s+/g, " ").trim();
2717
+ async function withCache(cfg, graph, g, picked) {
2718
+ const { covering, selections } = picked;
2719
+ const settings = {
2720
+ mode: cfg.mode,
2721
+ timeout: cfg.timeout,
2722
+ scratchCwd: cfg.scratchCwd,
2723
+ testPreload: cfg.testPreload,
2724
+ coverage: cfg.coverage,
2725
+ typecheck: cfg.typecheck,
2726
+ contracts: cfg.contracts,
2727
+ selections: selectionKey(g.mutants, selections)
2728
+ };
2729
+ const key = cfg.cacheDir && graph && covering.length > 0 ? await cacheKey({
2730
+ mutants: g.mutants,
2731
+ closure: closureOf(graph, covering),
2732
+ projectFiles: projectFiles(cfg),
2733
+ settings
2734
+ }) : null;
2735
+ return {
2736
+ file: g.file,
2737
+ mutants: g.mutants,
2738
+ compileErrors: g.compileErrors,
2739
+ ...picked,
2740
+ covered: cfg.runner.kind === "command" || covering.length > 0,
2741
+ cacheKey: key,
2742
+ cached: cfg.cacheDir && key ? await readCache(cfg.cacheDir, key) : null,
2743
+ contracts: g.contracts
2744
+ };
195
2745
  }
196
- async function fileHash(file) {
197
- const f = Bun.file(file);
198
- if (!await f.exists())
199
- return null;
200
- return createHash("sha256").update(normalizeSource(await f.text())).digest("hex").slice(0, 16);
2746
+ async function prepare(cfg, preloads, workdirs, log) {
2747
+ const command = cfg.runner.kind === "command";
2748
+ const testFiles = command ? [] : await findTestFiles(cfg.cwd, cfg.testInclude);
2749
+ if (!command && testFiles.length === 0) {
2750
+ throw new Error(`no test files match ${cfg.testInclude.join(", ")} under ${cfg.cwd}`);
2751
+ }
2752
+ const graph = command ? null : await buildImportGraph(testFiles);
2753
+ const generated = await generateAll(cfg, graph);
2754
+ const coverage = graph && cfg.coverage === "dynamic" ? await dynamicCoverage(cfg, graph, generated, preloads, workdirs, log) : null;
2755
+ const prepared = [];
2756
+ for (const [index, g] of generated.entries()) {
2757
+ const target = coverage?.targets[index];
2758
+ if (target?.kind === "static") {
2759
+ log(`${relative6(cfg.cwd, g.file)}: static test selection (${target.reason})`);
2760
+ }
2761
+ const picked = coverage && target?.kind === "dynamic" ? dynamicSelection(g, target, coverage) : { covering: g.covering, selections: null, coverageTests: [] };
2762
+ prepared.push(await withCache(cfg, graph, g, picked));
2763
+ }
2764
+ return { prepared, testFiles: testFiles.length };
201
2765
  }
202
- function fileSignals(db) {
203
- const rows = queryAll(db, `
204
- WITH file_kill AS (SELECT DISTINCT t.file file, k.mutant_id mid FROM kills k JOIN tests t ON t.id=k.test_id),
205
- owner AS (SELECT mid, count(DISTINCT file) nf FROM file_kill GROUP BY mid)
206
- SELECT fk.file file, count(DISTINCT fk.mid) kills,
207
- sum(CASE WHEN o.nf=1 THEN 1 ELSE 0 END) unique_kills
208
- FROM file_kill fk JOIN owner o ON o.mid=fk.mid GROUP BY fk.file`);
209
- const m = new Map;
210
- for (const r of rows)
211
- m.set(r.file, {
212
- kills: r.kills,
213
- uniqueKills: r.unique_kills,
214
- subsumed: r.kills > 0 && r.unique_kills === 0
215
- });
216
- return m;
2766
+ function collectContractViolations(cfg, baselines, log) {
2767
+ const out = [];
2768
+ for (const [p, baseline] of baselines) {
2769
+ for (const v of baseline?.contractViolations ?? []) {
2770
+ out.push({ target: p.file, test: v.test, contracts: v.contracts });
2771
+ const where = v.contracts.length > 0 ? ` → ${v.contracts.join(", ")}` : "";
2772
+ log(`${relative6(cfg.cwd, p.file)}: test violates contract: ${v.test}${where}`);
2773
+ }
2774
+ }
2775
+ return out;
217
2776
  }
218
- async function loadDecisions(logPath) {
219
- const m = new Map;
220
- const f = Bun.file(logPath);
221
- if (!await f.exists())
222
- return m;
223
- for (const line of (await f.text()).split(`
224
- `)) {
225
- const t = line.trim();
226
- if (!t)
227
- continue;
228
- const d = JSON.parse(t);
229
- m.set(d.file, d);
2777
+ function selected(p, mutant) {
2778
+ return !p.selections || (p.selections.get(mutant.id)?.files.length ?? 0) > 0;
2779
+ }
2780
+ async function runMutant(cfg, workdirs, preloads, p, baseline, job) {
2781
+ const matrix = cfg.mode === "matrix";
2782
+ const selection = p.selections?.get(job.mutant.id);
2783
+ const files = selection?.files ?? p.covering;
2784
+ const coveredBy = selection ? { coveredBy: selection.coveredBy } : {};
2785
+ let runCwd = cfg.cwd;
2786
+ const attempt = (namePattern) => inCwd(job.inTree ? null : workdirs, cfg.cwd, (cwd) => {
2787
+ runCwd = cwd;
2788
+ return runBunTest({
2789
+ cwd,
2790
+ files,
2791
+ preloads,
2792
+ contracts: cfg.contracts,
2793
+ env: {
2794
+ POLLY_MUTATE_FILE: job.mutant.file,
2795
+ POLLY_MUTATE_SPAN: JSON.stringify({
2796
+ start: job.mutant.start,
2797
+ end: job.mutant.end,
2798
+ replacement: job.mutant.replacement
2799
+ })
2800
+ },
2801
+ bail: !matrix,
2802
+ junit: matrix || namePattern !== undefined,
2803
+ timeoutMs: job.timeoutMs,
2804
+ ...namePattern ? { namePattern } : {}
2805
+ }, cfg.runner);
2806
+ });
2807
+ let outcome = await attempt(selection?.namePattern);
2808
+ let cases = outcome.junitXml ? parseJunit(outcome.junitXml, runCwd) : [];
2809
+ if (selection?.namePattern && !outcome.timedOut && outcome.exitCode !== 0 && matchedNothing(cases)) {
2810
+ outcome = await attempt(undefined);
2811
+ cases = outcome.junitXml ? parseJunit(outcome.junitXml, runCwd) : [];
230
2812
  }
231
- return m;
2813
+ const durationMs = Math.round(outcome.ms);
2814
+ const result = { mutant: job.mutant, durationMs, ...coveredBy };
2815
+ if (outcome.timedOut)
2816
+ return { ...result, status: "Timeout" };
2817
+ if (outcome.exitCode === 0)
2818
+ return { ...result, status: "Survived" };
2819
+ if (!matrix)
2820
+ return { ...result, status: "Killed" };
2821
+ const ran = new Set(files);
2822
+ const reported = new Set([...baseline.reportedFiles].filter((f) => ran.has(f)));
2823
+ const killedBy = killers(cases, reported, cfg.cwd);
2824
+ return { ...result, status: "Killed", killedBy, ...contractAttribution(cfg, cases, killedBy) };
232
2825
  }
233
- function staleReason(d, currentHash, current) {
234
- if (!current)
235
- return "file no longer kills any mutant (renamed/deleted/refactored?)";
236
- if (d.hash !== currentHash)
237
- return "test file changed since the decision";
238
- if (d.signal.subsumed !== current.subsumed)
239
- return `subsumption flipped (${d.signal.subsumed} → ${current.subsumed})`;
240
- if (d.signal.uniqueKills > 0 !== current.uniqueKills > 0)
241
- return `unique-kill status changed (${d.signal.uniqueKills} → ${current.uniqueKills})`;
242
- return null;
2826
+ function contractAttribution(cfg, cases, killedBy) {
2827
+ if (cfg.contracts === "off")
2828
+ return {};
2829
+ const kills = contractKills(cases, cfg.cwd);
2830
+ if (kills.length === 0)
2831
+ return {};
2832
+ const killedByContract = sortedUnique(kills.flatMap((k) => k.contracts));
2833
+ const failed = cases.filter((c) => c.status === "failed").length;
2834
+ const contractOnly = kills.length === failed && killedBy.length === failed;
2835
+ return { killedByContract, ...contractOnly ? { contractOnly: true } : {} };
243
2836
  }
244
- async function status(db, logPath = DEFAULT_LOG) {
245
- const signals = fileSignals(db);
246
- const decisions = await loadDecisions(logPath);
247
- const needsReview = [];
248
- const stale = [];
249
- const settled = [];
250
- for (const [file, sig] of [...signals].sort((a, b) => b[1].kills - a[1].kills)) {
251
- const d = decisions.get(file);
252
- if (!d) {
253
- if (sig.subsumed)
254
- needsReview.push(` ${file} (${sig.kills} kills, 0 unique)`);
255
- continue;
2837
+ function matchedNothing(cases) {
2838
+ return cases.length > 0 && cases.every((c) => c.status === "skipped");
2839
+ }
2840
+ function fromCache(p, entry) {
2841
+ const bySig = new Map(entry.results.map((r) => [r.sig, r]));
2842
+ const results = [...p.mutants, ...p.compileErrors].map((mutant) => {
2843
+ const hit = bySig.get(mutantSig(mutant));
2844
+ if (!hit)
2845
+ return { mutant, status: "RuntimeError", statusReason: "missing from the cache entry" };
2846
+ const { sig: _sig, ...rest } = hit;
2847
+ return { mutant, ...rest };
2848
+ });
2849
+ results.sort((a, b) => a.mutant.start - b.mutant.start);
2850
+ return {
2851
+ file: p.file,
2852
+ coveringTests: p.covering,
2853
+ baselineMs: entry.baselineMs,
2854
+ inTree: entry.inTree,
2855
+ cached: true,
2856
+ tests: entry.tests,
2857
+ results,
2858
+ contracts: p.contracts
2859
+ };
2860
+ }
2861
+ function testsFor(cfg, p, baseline, results) {
2862
+ const tests = [...baseline.tests];
2863
+ const known = new Set(tests.map((t) => t.id));
2864
+ for (const t of p.coverageTests) {
2865
+ if (!known.has(t.id)) {
2866
+ known.add(t.id);
2867
+ tests.push(t);
256
2868
  }
257
- const reason = staleReason(d, await fileHash(file), sig);
258
- if (reason)
259
- stale.push(` ${file} [${d.verdict}] — ${reason}`);
260
- else
261
- settled.push(` ${file} [${d.verdict}] ${d.rationale ? `— ${d.rationale}` : ""}`);
262
2869
  }
263
- for (const [file, d] of decisions) {
264
- if (!signals.has(file))
265
- stale.push(` ${file} [${d.verdict}] — file no longer in matrix`);
2870
+ const used = new Set(results.flatMap((r) => r.killedBy ?? []));
2871
+ for (const file of p.covering) {
2872
+ const id = loadFailureId(cfg.cwd, file);
2873
+ if (used.has(id) && !known.has(id))
2874
+ tests.push({ id, file, name: LOAD_FAILURE_NAME, line: 0 });
266
2875
  }
267
- const out = [];
268
- out.push(`NEEDS REVIEW (subsumed files with no decision — ${needsReview.length})`);
269
- out.push(needsReview.length ? needsReview.join(`
270
- `) : " none");
271
- out.push(`
272
- STALE (decision's basis drifted — re-review — ${stale.length})`);
273
- out.push(stale.length ? stale.join(`
274
- `) : " none");
275
- out.push(`
276
- SETTLED (fresh decisions, suppressed from action list — ${settled.length})`);
277
- out.push(settled.length ? settled.join(`
278
- `) : " none");
279
- return out.join(`
280
- `);
2876
+ return tests;
281
2877
  }
282
- async function decide(file, verdict, rationale, db, logPath = DEFAULT_LOG) {
283
- if (!VERDICTS.includes(verdict)) {
284
- console.log(`✗ verdict must be one of: ${VERDICTS.join(", ")}`);
285
- process.exit(1);
2878
+ function unrun(mutant, statusReason) {
2879
+ return { mutant, status: "RuntimeError", statusReason };
2880
+ }
2881
+ function notRun(p, baseline, mutant) {
2882
+ if (!p.covered) {
2883
+ const reason = p.selections ? "no test ran this target" : "no test file imports this target";
2884
+ return { mutant, status: "NoCoverage", statusReason: reason };
286
2885
  }
287
- const sig = fileSignals(db).get(file);
288
- if (!sig) {
289
- console.log(`✗ ${file} is not a test file that kills any mutant in the current matrix`);
290
- process.exit(1);
2886
+ if (baseline?.contractViolations)
2887
+ return unrun(mutant, baseline.reason);
2888
+ if (!selected(p, mutant)) {
2889
+ return { mutant, status: "NoCoverage", statusReason: "no test ran this code", coveredBy: [] };
291
2890
  }
292
- const decided = new Date().toISOString().slice(0, 10);
293
- const record = {
294
- file,
295
- verdict,
296
- rationale,
297
- signal: sig,
298
- hash: await fileHash(file),
299
- decided
2891
+ if (!baseline?.ok)
2892
+ return unrun(mutant, baseline?.reason);
2893
+ return null;
2894
+ }
2895
+ function summarise(cfg, p, baseline, byId, invalid, workdirs) {
2896
+ const results = p.mutants.map((mutant) => {
2897
+ if (mutant.ignoredReason)
2898
+ return { mutant, status: "Ignored", statusReason: mutant.ignoredReason };
2899
+ const typeError = invalid.get(mutant.id);
2900
+ if (typeError)
2901
+ return { mutant, status: "CompileError", statusReason: typeError };
2902
+ return notRun(p, baseline, mutant) ?? byId.get(mutant.id) ?? unrun(mutant, "mutant was not run");
2903
+ });
2904
+ for (const mutant of p.compileErrors) {
2905
+ results.push({ mutant, status: "CompileError", statusReason: "mutated source does not parse" });
2906
+ }
2907
+ results.sort((a, b) => a.mutant.start - b.mutant.start);
2908
+ return {
2909
+ file: p.file,
2910
+ coveringTests: p.covering,
2911
+ baselineMs: baseline?.ok ? Math.round(baseline.ms) : null,
2912
+ inTree: baseline?.inTree ?? !workdirs,
2913
+ cached: false,
2914
+ tests: baseline?.ok ? testsFor(cfg, p, baseline, results) : p.coverageTests,
2915
+ results,
2916
+ contracts: p.contracts
300
2917
  };
301
- await Bun.write(logPath, (await Bun.file(logPath).exists() ? await Bun.file(logPath).text() : "") + JSON.stringify(record) + `
302
- `);
303
- console.log(`✓ recorded: ${file} [${verdict}]${rationale ? ` — ${rationale}` : ""}`);
304
2918
  }
305
- if (false) {}
2919
+ async function run(cfg, hooks, workdirs) {
2920
+ const log = hooks.log ?? (() => {
2921
+ return;
2922
+ });
2923
+ const started = performance.now();
2924
+ const preloads = [...cfg.testPreload, preloadPath()];
2925
+ const beforeRun = snapshotWorktree(cfg.cwd);
2926
+ const { prepared, testFiles } = await prepare(cfg, preloads, workdirs, log);
2927
+ const totalMutants = prepared.reduce((n, p) => n + p.mutants.length, 0);
2928
+ const hits = prepared.filter((p) => p.cached).length;
2929
+ log(`${prepared.length} target(s), ${totalMutants} mutants, ` + (cfg.runner.kind === "command" ? `command \`${cfg.runner.argv.join(" ")}\`` : `${testFiles} test files in scope`) + `, ${cfg.mode} mode` + (cfg.runner.kind === "bun-test" ? `, ${cfg.coverage} coverage` : "") + (cfg.cacheDir ? `, ${hits} target(s) from cache` : ""));
2930
+ const fresh = prepared.filter((p) => !p.cached && p.covered);
2931
+ const [measured, typed] = await Promise.all([
2932
+ pool(fresh, cfg.concurrency, (p) => measureBaseline(cfg, workdirs, preloads, p, log)),
2933
+ cfg.typecheck ? typecheckMutants(prepared.filter((p) => !p.cached).map((p) => ({ file: p.file, mutants: p.mutants.filter((m) => !m.ignoredReason) })), { cwd: cfg.cwd, log }) : null
2934
+ ]);
2935
+ const invalid = typed?.invalid ?? new Map;
2936
+ const baselines = new Map(fresh.map((p, i) => [p, measured[i] ?? null]));
2937
+ const afterBaselines = snapshotWorktree(cfg.cwd);
2938
+ const contractViolations = collectContractViolations(cfg, baselines, log);
2939
+ const jobs = [];
2940
+ prepared.forEach((p, target) => {
2941
+ const baseline = baselines.get(p);
2942
+ if (!baseline?.ok)
2943
+ return;
2944
+ const timeoutMs = Math.round(baseline.ms * cfg.timeout.factor + cfg.timeout.extraMs);
2945
+ for (const mutant of p.mutants) {
2946
+ if (!mutant.ignoredReason && !invalid.has(mutant.id) && selected(p, mutant))
2947
+ jobs.push({ target, mutant, timeoutMs, inTree: baseline.inTree });
2948
+ }
2949
+ });
2950
+ jobs.sort((a, b) => b.timeoutMs - a.timeoutMs);
2951
+ let done = 0;
2952
+ const runResults = await pool(jobs, cfg.concurrency, async (job) => {
2953
+ const p = prepared[job.target];
2954
+ const baseline = p && baselines.get(p);
2955
+ if (!p || !baseline)
2956
+ throw new Error(`job for target ${job.target} has no baseline`);
2957
+ const result = await runMutant(cfg, workdirs, preloads, p, baseline, job);
2958
+ done++;
2959
+ hooks.progress?.(done, jobs.length);
2960
+ return result;
2961
+ });
2962
+ const byId = new Map(runResults.map((r) => [r.mutant.id, r]));
2963
+ const targets = prepared.map((p) => p.cached ? fromCache(p, p.cached) : summarise(cfg, p, baselines.get(p) ?? null, byId, invalid, workdirs));
2964
+ const afterMutants = snapshotWorktree(cfg.cwd);
2965
+ const strayWrites = beforeRun ? {
2966
+ root: beforeRun.root,
2967
+ baseline: newPaths(beforeRun, afterBaselines),
2968
+ mutants: newPaths(afterBaselines, afterMutants)
2969
+ } : null;
2970
+ for (const path of strayWrites?.mutants ?? [])
2971
+ log(`warning: a mutant run wrote ${path}`);
2972
+ if (cfg.cacheDir) {
2973
+ targets.forEach((t, i) => {
2974
+ const p = prepared[i];
2975
+ if (!cfg.cacheDir || !p?.cacheKey || t.cached || t.baselineMs === null)
2976
+ return;
2977
+ writeCache(cfg.cacheDir, p.cacheKey, {
2978
+ baselineMs: t.baselineMs,
2979
+ inTree: t.inTree,
2980
+ tests: t.tests,
2981
+ results: t.results.map(cachedResult)
2982
+ });
2983
+ });
2984
+ }
2985
+ const result = {
2986
+ targets,
2987
+ wallMs: Math.round(performance.now() - started),
2988
+ strayWrites,
2989
+ contractViolations
2990
+ };
2991
+ await writeReport(await toMutationReport(result, cfg.cwd, { contracts: cfg.contracts, runner: cfg.runner.kind }), cfg.reportPath);
2992
+ return result;
2993
+ }
2994
+ function mutationScore(results) {
2995
+ let detected = 0;
2996
+ let valid = 0;
2997
+ for (const r of results) {
2998
+ if (r.status === "Killed" || r.status === "Timeout")
2999
+ detected++;
3000
+ if (r.status === "Killed" || r.status === "Timeout" || r.status === "Survived" || r.status === "NoCoverage")
3001
+ valid++;
3002
+ }
3003
+ return valid === 0 ? null : 100 * detected / valid;
3004
+ }
306
3005
 
307
- // tools/mutate/src/init.ts
308
- import { existsSync as existsSync2 } from "node:fs";
309
- import { join as join2, relative } from "node:path";
310
- function resolvePluginRef(projectDir) {
311
- const resolved = Bun.resolveSync("@fairfox/polly/stryker", projectDir);
312
- const hoisted = resolved.includes("/node_modules/") && !resolved.includes("/.bun/");
313
- return hoisted ? "@fairfox/polly/stryker" : relative(projectDir, resolved);
3006
+ // tools/mutate/src/engine-config.ts
3007
+ import { availableParallelism } from "node:os";
3008
+ import { dirname as dirname7, join as join10, resolve as resolve4 } from "node:path";
3009
+ import { Glob as Glob3 } from "bun";
3010
+ var RANGE = /^(.*?):(\d+)(?::\d+)?-(\d+)(?::\d+)?$/;
3011
+ async function scanGlob(cwd, pattern) {
3012
+ const out = [];
3013
+ for await (const f of new Glob3(pattern).scan({ cwd, absolute: true, onlyFiles: true })) {
3014
+ if (!f.includes("/node_modules/"))
3015
+ out.push(f);
3016
+ }
3017
+ return out;
314
3018
  }
315
- function detectMutate(projectDir) {
316
- if (existsSync2(join2(projectDir, "src"))) {
317
- return ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.d.ts"];
3019
+ function parseEntry(entry) {
3020
+ const range = RANGE.exec(entry);
3021
+ if (!range?.[1])
3022
+ return { pattern: entry };
3023
+ return { pattern: range[1], lines: { from: Number(range[2]), to: Number(range[3]) } };
3024
+ }
3025
+ async function expandMutateEntries(cwd, entries) {
3026
+ const negated = entries.filter((x) => x.startsWith("!"));
3027
+ const excluded = new Set((await Promise.all(negated.map((e) => scanGlob(cwd, e.slice(1))))).flat());
3028
+ const targets = new Map;
3029
+ for (const entry of entries.filter((x) => !x.startsWith("!"))) {
3030
+ const { pattern, lines } = parseEntry(entry);
3031
+ const files = (await scanGlob(cwd, pattern)).filter((f) => !excluded.has(f));
3032
+ for (const f of files)
3033
+ targets.set(f, lines ? { file: f, lines } : { file: f });
318
3034
  }
319
- return ["**/*.ts", "!**/*.test.ts", "!**/*.d.ts", "!node_modules/**", "!dist/**"];
3035
+ return [...targets.values()].sort((a, b) => a.file.localeCompare(b.file));
320
3036
  }
321
- function detectTestGlob(projectDir) {
322
- for (const d of ["tests", "test"]) {
323
- if (existsSync2(join2(projectDir, d)))
324
- return `${d}/**/*.test.ts`;
3037
+ async function changedSince(cwd, ref) {
3038
+ const proc = Bun.spawn(["git", "diff", "--name-only", "--relative", ref], {
3039
+ cwd,
3040
+ stdout: "pipe",
3041
+ stderr: "pipe"
3042
+ });
3043
+ const [out, code] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
3044
+ if (code !== 0)
3045
+ throw new Error(`git diff --name-only ${ref} failed: ${await new Response(proc.stderr).text()}`);
3046
+ return new Set(out.split(`
3047
+ `).filter(Boolean).map((p) => resolve4(cwd, p)));
3048
+ }
3049
+ async function selectTargets(dir, config, args) {
3050
+ const entries = args.files ? args.files.split(",").map((s) => s.trim()).filter(Boolean) : config.targets;
3051
+ const targets = await expandMutateEntries(dir, entries);
3052
+ if (!args.since)
3053
+ return targets;
3054
+ const changed = await changedSince(dir, args.since);
3055
+ return targets.filter((t) => changed.has(t.file));
3056
+ }
3057
+ function resolveConcurrency(flag, fromConfig) {
3058
+ if (flag === undefined)
3059
+ return fromConfig ?? Math.max(1, availableParallelism() - 1);
3060
+ const n = Number(flag);
3061
+ if (!(Number.isInteger(n) && n > 0)) {
3062
+ throw new Error(`--concurrency must be a positive integer, got "${flag}"`);
325
3063
  }
326
- return "**/*.test.ts";
3064
+ return n;
327
3065
  }
328
- async function initConfig(projectDir, opts = {}) {
329
- const configPath = join2(projectDir, "stryker.conf.json");
330
- const warnings = [];
331
- let pluginRef;
332
- try {
333
- pluginRef = resolvePluginRef(projectDir);
334
- } catch {
335
- throw new Error("Cannot resolve @fairfox/polly from here. Run `polly mutate init` in a project that depends on @fairfox/polly.");
3066
+ function resolveMode(flag, config) {
3067
+ const mode = flag ?? config.mode ?? "fast";
3068
+ if (mode !== "fast" && mode !== "matrix") {
3069
+ throw new Error(`--mode ${mode}: expected fast or matrix`);
336
3070
  }
337
- const mutate = detectMutate(projectDir);
338
- const testGlob = detectTestGlob(projectDir);
339
- if (!existsSync2(join2(projectDir, "src"))) {
340
- warnings.push("no src/ directory — adjust the `mutate` globs to point at your source");
341
- }
342
- if (!existsSync2(join2(projectDir, "tests")) && !existsSync2(join2(projectDir, "test"))) {
343
- warnings.push(`no tests/ directory — using "${testGlob}"; adjust bun.testFiles if needed`);
344
- }
345
- if (existsSync2(configPath) && !opts.force) {
346
- return { configPath, created: false, pluginRef, mutate, testGlob, warnings };
347
- }
348
- const config = {
349
- testRunner: "bun",
350
- bun: { testFiles: [testGlob], timeout: 30000 },
351
- plugins: ["stryker-mutator-bun-runner", pluginRef],
352
- ignorers: ["polly-verify"],
353
- coverageAnalysis: "all",
354
- disableBail: true,
355
- reporters: ["json", "clear-text"],
356
- mutate,
357
- thresholds: { high: 90, low: 70, break: null },
358
- ignorePatterns: [
359
- "**/node_modules/**",
360
- "**/dist/**",
361
- "**/.git/**",
362
- "**/.stryker-tmp/**",
363
- "**/reports/**"
364
- ],
365
- timeoutMS: 60000,
366
- concurrency: 4
3071
+ if (mode === "matrix" && config.runner?.kind === "command") {
3072
+ throw new Error("matrix mode needs per-test results; the command runner has none (use fast)");
3073
+ }
3074
+ return mode;
3075
+ }
3076
+ function resolveCoverage(flag, config) {
3077
+ const coverage = flag ?? config.coverage ?? "dynamic";
3078
+ if (coverage !== "dynamic" && coverage !== "static") {
3079
+ throw new Error(`--coverage ${coverage}: expected dynamic or static`);
3080
+ }
3081
+ return coverage;
3082
+ }
3083
+ function resolveContracts(flag, config) {
3084
+ const contracts = flag ?? config.contracts ?? "all";
3085
+ if (!isContractsMode(contracts)) {
3086
+ throw new Error(`--contracts ${contracts}: expected off, ensures or all`);
3087
+ }
3088
+ return contracts;
3089
+ }
3090
+ async function engineConfigFor(cfg, args) {
3091
+ if (!cfg.mutation) {
3092
+ throw new Error(cfg.mutationError ?? `no ${MUTATION_CONFIG_FILE} found — run 'polly mutate init', or pass --config <path>`);
3093
+ }
3094
+ const { config, path } = cfg.mutation;
3095
+ const dir = dirname7(path);
3096
+ const mode = resolveMode(args.mode, config);
3097
+ const command = config.runner?.kind === "command" ? config.runner : null;
3098
+ return {
3099
+ cwd: dir,
3100
+ targets: await selectTargets(dir, config, args),
3101
+ runner: command ?? { kind: "bun-test" },
3102
+ testInclude: config.tests?.include ?? [],
3103
+ testPreload: (config.tests?.preload ?? []).map((p) => resolve4(dir, p)),
3104
+ mode,
3105
+ coverage: command ? "static" : resolveCoverage(args.coverage, config),
3106
+ concurrency: resolveConcurrency(args.concurrency, config.concurrency),
3107
+ timeout: config.timeout ?? { factor: 2, extraMs: 3000 },
3108
+ typecheck: !args.noTypecheck && (config.typecheck ?? true),
3109
+ excludeMutators: config.mutators?.exclude ?? [],
3110
+ ignoreVerifyCallsites: config.ignoreVerifyCallsites ?? true,
3111
+ contracts: resolveContracts(args.contracts, config),
3112
+ scratchCwd: !(args.inTree || command),
3113
+ cacheDir: args.noCache ? null : join10(dir, ".polly", "mutate", "cache"),
3114
+ reportPath: cfg.reportPath
367
3115
  };
368
- await Bun.write(configPath, `${JSON.stringify(config, null, 2)}
369
- `);
370
- return { configPath, created: true, pluginRef, mutate, testGlob, warnings };
371
3116
  }
372
3117
 
373
- // tools/mutate/src/run.ts
374
- import { resolve as resolve3 } from "node:path";
375
-
376
3118
  // tools/mutate/src/report.ts
3119
+ function contractsSection(db, p) {
3120
+ const meta = new Map(queryAll(db, "SELECT key, value FROM report_meta").map((r) => [
3121
+ r.key,
3122
+ r.value
3123
+ ]));
3124
+ const mode = meta.get("contracts_mode");
3125
+ if (mode === undefined)
3126
+ return;
3127
+ const nSites = queryGet(db, "SELECT count(*) n FROM contract_sites")?.n ?? 0;
3128
+ p(`
3129
+ CONTRACTS (requires/ensures as kill oracles — mode ${mode}, ${nSites} site(s))`);
3130
+ if (mode === "off") {
3131
+ p(` off — the sites are inventoried only; 'polly mutate run --contracts all' makes each one fail the test that falsifies it`);
3132
+ return;
3133
+ }
3134
+ const violations = queryAll(db, "SELECT target, test, contract_id FROM contract_violations ORDER BY target, test, contract_id");
3135
+ if (violations.length > 0) {
3136
+ p(` TEST VIOLATES CONTRACT (the unmutated code fails a contract under a test: ${violations.length})`);
3137
+ for (const v of violations) {
3138
+ p(` ${v.target}: ${v.test}${v.contract_id ? ` → ${v.contract_id}` : ""}`);
3139
+ }
3140
+ }
3141
+ if (meta.get("runner") === "command") {
3142
+ p(` command runner: no per-test results, so kills are not attributed to contracts; compare the killed count against a --contracts off run`);
3143
+ return;
3144
+ }
3145
+ if (mode === "ensures")
3146
+ p(` requires sites are inventoried, not enforced (mode ensures)`);
3147
+ const only = queryAll(db, "SELECT file, line, mutator, count(*) n FROM mutants WHERE contract_only=1 GROUP BY file, line, mutator ORDER BY file, line");
3148
+ const onlyTotal = only.reduce((a, r) => a + r.n, 0);
3149
+ p(` CONTRACT-ONLY KILLS (no test assertion caught these; a contract did: ${onlyTotal})`);
3150
+ for (const r of only)
3151
+ p(` ${r.file}:${r.line} ${r.mutator}${r.n > 1 ? ` ×${r.n}` : ""}`);
3152
+ if (nSites === 0)
3153
+ return;
3154
+ const sites = queryAll(db, `SELECT s.id, s.primitive, s.message,
3155
+ (SELECT count(*) FROM contract_kills k WHERE k.contract_id = s.id) n,
3156
+ (SELECT count(*) FROM mutants m
3157
+ WHERE m.file = s.file AND s.handler_from IS NOT NULL
3158
+ AND m.line BETWEEN s.handler_from AND s.handler_to
3159
+ AND m.status IN ('Killed', 'Survived', 'Timeout')) exercised
3160
+ FROM contract_sites s ORDER BY n DESC, s.id`);
3161
+ p(` KILLS PER CONTRACT`);
3162
+ for (const s of sites) {
3163
+ p(` ${s.id} ${s.primitive} ${s.n} kill(s)${s.message ? ` “${s.message}”` : ""}`);
3164
+ }
3165
+ const toothless = sites.filter((s) => s.n === 0 && s.exercised > 0);
3166
+ const idle = sites.filter((s) => s.n === 0 && s.exercised === 0);
3167
+ p(` CONTRACTS WITHOUT TEETH (the handler's mutants ran, the contract never fired: ${toothless.length})`);
3168
+ if (toothless.length === 0)
3169
+ p(` none`);
3170
+ for (const s of toothless)
3171
+ p(` ${s.id} ${s.primitive}${s.message ? ` “${s.message}”` : ""}`);
3172
+ if (idle.length > 0) {
3173
+ p(` HANDLER NOT EXERCISED (no mutant in the contract's handler ran: ${idle.length})`);
3174
+ for (const s of idle)
3175
+ p(` ${s.id} ${s.primitive}`);
3176
+ }
3177
+ }
377
3178
  function greedyCover(units, universe) {
378
3179
  const remaining = new Set(universe);
379
3180
  const chosen = [];
@@ -404,11 +3205,16 @@ function report(db, opts = {}) {
404
3205
  const matrixComplete = opts.matrixComplete ?? true;
405
3206
  const out = [];
406
3207
  const p = (s = "") => out.push(s);
407
- const tot = queryGet(db, "SELECT count(*) n, sum(status='Killed') killed, sum(status='Survived') survived, sum(status='Timeout') timeout, sum(status='NoCoverage') nocov FROM mutants") ?? { n: 0, killed: 0, survived: 0, timeout: 0, nocov: 0 };
3208
+ const tot = queryGet(db, "SELECT count(*) n, sum(status='Killed') killed, sum(status='Survived') survived, sum(status='Timeout') timeout, sum(status='NoCoverage') nocov, sum(status='CompileError') invalid, sum(status='Ignored') ignored FROM mutants") ?? { n: 0, killed: 0, survived: 0, timeout: 0, nocov: 0, invalid: 0, ignored: 0 };
408
3209
  const nTests = queryGet(db, "SELECT count(*) n FROM tests")?.n ?? 0;
409
3210
  const detected = tot.killed + tot.timeout;
410
- const score = (detected / (tot.n - tot.nocov || 1) * 100).toFixed(1);
411
- p(`MUTATION score ${score}% ${tot.killed} killed · ${tot.timeout} timeout · ${tot.survived} survived · ${tot.nocov} no-coverage (${tot.n} mutants, ${nTests} tests)`);
3211
+ const valid = detected + tot.survived + tot.nocov;
3212
+ const score = valid === 0 ? "n/a" : `${(detected / valid * 100).toFixed(1)}%`;
3213
+ const excluded = [
3214
+ tot.invalid > 0 ? `${tot.invalid} invalid` : "",
3215
+ tot.ignored > 0 ? `${tot.ignored} ignored` : ""
3216
+ ].filter(Boolean).map((s) => ` · ${s}`).join("");
3217
+ p(`MUTATION score ${score} ${tot.killed} killed · ${tot.timeout} timeout · ${tot.survived} survived · ${tot.nocov} no-coverage${excluded} (${tot.n} mutants, ${nTests} tests)`);
412
3218
  if (matrixComplete) {
413
3219
  const mult = queryAll(db, `
414
3220
  SELECT CASE WHEN c=1 THEN '1' WHEN c=2 THEN '2' WHEN c BETWEEN 3 AND 5 THEN '3-5' ELSE '6+' END bucket, count(*) n
@@ -473,26 +3279,28 @@ SUBSUMED CASES (${subsumedCases.length} individual tests whose every kill is ca
473
3279
  p(`
474
3280
  ⚠ KILL MATRIX INCOMPLETE — redundancy/subsumption analysis suppressed.`);
475
3281
  p(` Every mutant has at most one recorded killer, so "which tests are redundant"`);
476
- p(` cannot be derived. This needs the no-bail patched Bun runner (not shipped with`);
477
- p(` @fairfox/polly). Run 'polly mutate verify' to diagnose. Score/gaps/theatre below still hold.`);
3282
+ p(` cannot be derived. Run 'polly mutate run --mode matrix' (every`);
3283
+ p(` killer recorded), or 'polly mutate verify' to diagnose. Score/gaps/theatre below still hold.`);
478
3284
  }
479
- const srcFile = queryGet(db, "SELECT file FROM mutants LIMIT 1")?.file;
480
- const gaps = queryAll(db, "SELECT line, mutator, count(*) n FROM mutants WHERE status='NoCoverage' GROUP BY line, mutator ORDER BY line");
3285
+ const byLine = (status) => queryAll(db, `SELECT file, line, mutator, count(*) n FROM mutants WHERE status='${status}' GROUP BY file, line, mutator ORDER BY file, line`);
3286
+ const lineOf = (r) => ` ${r.file}:${r.line} ${r.mutator}${r.n > 1 ? ` ×${r.n}` : ""}`;
3287
+ const gaps = byLine("NoCoverage");
481
3288
  const gapTotal = gaps.reduce((a, r) => a + r.n, 0);
482
3289
  p(`
483
3290
  GAPS (NoCoverage — no test executes this code: ${gapTotal})`);
484
3291
  if (gapTotal === 0)
485
3292
  p(` none — every mutable location is reached by some test`);
486
3293
  for (const r of gaps)
487
- p(` ${srcFile}:${r.line} ${r.mutator}${r.n > 1 ? ` ×${r.n}` : ""}`);
488
- const theatre = queryAll(db, "SELECT line, mutator, count(*) n FROM mutants WHERE status='Survived' GROUP BY line, mutator ORDER BY line");
3294
+ p(lineOf(r));
3295
+ const theatre = byLine("Survived");
489
3296
  const theatreTotal = theatre.reduce((a, r) => a + r.n, 0);
490
3297
  p(`
491
3298
  THEATRE (Survived — code is covered but no test detects the mutation: ${theatreTotal})`);
492
3299
  if (theatreTotal === 0)
493
3300
  p(` none`);
494
3301
  for (const r of theatre)
495
- p(` ${srcFile}:${r.line} ${r.mutator}${r.n > 1 ? ` ×${r.n}` : ""}`);
3302
+ p(lineOf(r));
3303
+ contractsSection(db, p);
496
3304
  return out.join(`
497
3305
  `);
498
3306
  }
@@ -512,20 +3320,6 @@ function isMatrixComplete(report) {
512
3320
  }
513
3321
  async function verifyMatrix(opts = {}) {
514
3322
  const reportPath = opts.reportPath ?? DEFAULT_REPORT2;
515
- if (opts.run) {
516
- console.log("Running mutation pass (this can take many minutes for a large mutate set)...");
517
- const cmd = [
518
- "bunx",
519
- "stryker",
520
- "run",
521
- ...opts.strykerConfig ? ["--configFile", opts.strykerConfig] : []
522
- ];
523
- const proc = Bun.spawn(cmd, { stdout: "inherit", stderr: "inherit" });
524
- const code = await proc.exited;
525
- if (code !== 0) {
526
- return { ok: false, checks: [{ name: "stryker run", ok: false, detail: `exited ${code}` }] };
527
- }
528
- }
529
3323
  if (!await Bun.file(reportPath).exists()) {
530
3324
  return {
531
3325
  ok: false,
@@ -533,7 +3327,7 @@ async function verifyMatrix(opts = {}) {
533
3327
  {
534
3328
  name: "report exists",
535
3329
  ok: false,
536
- detail: `no report at ${reportPath}. Run with --run, or 'bun run mutation' first.`
3330
+ detail: `no report at ${reportPath}. Run 'polly mutate verify --run' first.`
537
3331
  }
538
3332
  ]
539
3333
  };
@@ -558,24 +3352,118 @@ async function verifyMatrix(opts = {}) {
558
3352
  add("coverage collected (not all NoCoverage)", noCov < mutants.length, `${noCov}/${mutants.length} NoCoverage — all-NoCoverage means the coverage dump broke`);
559
3353
  return { ok: checks.every((c) => c.ok), checks };
560
3354
  }
561
- if (false) {}
562
3355
 
563
3356
  // tools/mutate/src/run.ts
564
- async function runStryker(cfg) {
565
- const autoDiscoverable = cfg.strykerConfigPath === resolve3(cfg.cwd, "stryker.conf.json");
566
- const configFlag = cfg.strykerConfigPath && !autoDiscoverable ? ["--configFile", cfg.strykerConfigPath] : [];
567
- const proc = Bun.spawn(["bunx", "stryker", "run", ...configFlag], {
568
- cwd: cfg.cwd,
569
- stdout: "inherit",
570
- stderr: "inherit",
571
- stdin: "inherit",
572
- env: process.env
3357
+ function resolveEngine(args) {
3358
+ const engine = args.engine ?? "bun";
3359
+ if (engine === "bun")
3360
+ return engine;
3361
+ if (engine === "stryker") {
3362
+ throw new Error("--engine stryker was removed; the bun engine (the default) replaces it");
3363
+ }
3364
+ throw new Error(`unknown --engine "${engine}" (expected bun)`);
3365
+ }
3366
+ function deprecationNotice(cfg) {
3367
+ const m = cfg.mutation;
3368
+ if (m?.format !== "stryker")
3369
+ return null;
3370
+ return [
3371
+ `deprecated: reading ${relative7(cfg.cwd, m.path) || m.path} — Stryker is no longer supported; its config is read for migration only.`,
3372
+ " 'polly mutate migrate --write' writes the equivalent polly.mutate.ts.",
3373
+ ...m.notes.map((n) => ` ${n}`)
3374
+ ].join(`
3375
+ `);
3376
+ }
3377
+ function thresholdFailure(score, cfg) {
3378
+ const floor = cfg.mutation?.config.thresholds?.break;
3379
+ if (floor === undefined || score === null || score >= floor)
3380
+ return null;
3381
+ return `mutation score ${score.toFixed(1)}% is below thresholds.break ${floor}%`;
3382
+ }
3383
+ async function runBunEngine(cfg, args) {
3384
+ const notice = deprecationNotice(cfg);
3385
+ if (notice)
3386
+ console.log(`${notice}
3387
+ `);
3388
+ const engineCfg = await engineConfigFor(cfg, args);
3389
+ if (engineCfg.targets.length === 0) {
3390
+ console.log(args.since ? `no mutate targets changed since ${args.since}` : "no mutate targets matched");
3391
+ return 0;
3392
+ }
3393
+ let lastPct = -1;
3394
+ const result = await runEngine(engineCfg, {
3395
+ log: (line) => console.log(line),
3396
+ progress: (done, total) => {
3397
+ const pct = Math.floor(100 * done / total);
3398
+ if (pct >= lastPct + 10 || done === total) {
3399
+ lastPct = pct;
3400
+ console.log(` ${done}/${total} mutants`);
3401
+ }
3402
+ }
573
3403
  });
574
- return await proc.exited;
3404
+ console.log(`
3405
+ file | tests | killed | survived | timeout | no-cov | invalid | other | score`);
3406
+ const all = result.targets.flatMap((t) => t.results);
3407
+ for (const t of result.targets) {
3408
+ const count = (s) => t.results.filter((r) => r.status === s).length;
3409
+ const other = t.results.length - count("Killed") - count("Survived") - count("Timeout") - count("NoCoverage") - count("CompileError");
3410
+ const score = mutationScore(t.results);
3411
+ console.log([
3412
+ relative7(engineCfg.cwd, t.file),
3413
+ t.coveringTests.length,
3414
+ count("Killed"),
3415
+ count("Survived"),
3416
+ count("Timeout"),
3417
+ count("NoCoverage"),
3418
+ count("CompileError"),
3419
+ other,
3420
+ score === null ? "n/a" : `${score.toFixed(1)}%`
3421
+ ].join(" | "));
3422
+ }
3423
+ const total = mutationScore(all);
3424
+ console.log(`
3425
+ ${all.length} mutants in ${(result.wallMs / 1000).toFixed(1)} s · score ${total === null ? "n/a" : `${total.toFixed(1)}%`} · report ${cfg.reportPath}`);
3426
+ const stray = result.strayWrites;
3427
+ if (stray && stray.mutants.length > 0) {
3428
+ console.log(`
3429
+ warning: mutant runs wrote ${stray.mutants.length} path(s) into ${stray.root} (not deleted — check, then remove):`);
3430
+ for (const path of stray.mutants)
3431
+ console.log(` ${path}`);
3432
+ }
3433
+ if (result.contractViolations.length > 0) {
3434
+ console.log(contractViolationsBlock(result, engineCfg.cwd));
3435
+ return 1;
3436
+ }
3437
+ const failure = thresholdFailure(total, cfg);
3438
+ if (failure) {
3439
+ console.log(`
3440
+ ✗ ${failure}`);
3441
+ return 1;
3442
+ }
3443
+ return 0;
3444
+ }
3445
+ function contractViolationsBlock(result, cwd) {
3446
+ const sites = new Map(result.targets.flatMap((t) => t.contracts.map((c) => [`${relative7(cwd, c.file)}:${c.line}`, c])));
3447
+ const lines = [
3448
+ `
3449
+ ✗ TEST VIOLATES CONTRACT (${result.contractViolations.length}; the mutants of these targets did not run)`
3450
+ ];
3451
+ for (const v of result.contractViolations) {
3452
+ const where = v.contracts.length === 0 ? "" : ` → ${v.contracts.join(", ")}`;
3453
+ lines.push(` ${relative7(cwd, v.target)}: ${v.test}${where}`);
3454
+ for (const id of v.contracts) {
3455
+ const site = sites.get(id);
3456
+ if (site)
3457
+ lines.push(` ${site.primitive}${site.message ? ` “${site.message}”` : ""}`);
3458
+ }
3459
+ }
3460
+ lines.push(" A test drives a handler outside its declared precondition, or a handler breaks its own", " postcondition. Fix the test or the contract; '--contracts ensures' leaves requires inert,", " '--contracts off' restores the no-op primitives.");
3461
+ return lines.join(`
3462
+ `);
575
3463
  }
576
3464
  async function reportFromFile(cfg) {
577
3465
  if (!await Bun.file(cfg.reportPath).exists()) {
578
- throw new Error(`no mutation report at ${cfg.reportPath}. Run 'polly mutate run' (or 'bun run mutation') first, or pass --report <path>.`);
3466
+ throw new Error(`no mutation report at ${cfg.reportPath}. Run 'polly mutate run' first, or pass --report <path>.`);
579
3467
  }
580
3468
  const mreport = await loadMutationReport(cfg.reportPath);
581
3469
  const db = buildDb(mreport, cfg.dbPath);
@@ -585,18 +3473,6 @@ async function reportFromFile(cfg) {
585
3473
  db.close();
586
3474
  }
587
3475
  }
588
- async function presetAdvisory(cfg) {
589
- if (!cfg.strykerConfigPath?.endsWith(".json"))
590
- return null;
591
- try {
592
- const conf = await Bun.file(cfg.strykerConfigPath).json();
593
- if ((conf.plugins ?? []).includes("@fairfox/polly/stryker"))
594
- return null;
595
- return "Tip: spread pollyStrykerPreset (from @fairfox/polly/stryker) into your Stryker config — " + "verify primitives (requires/ensures/…) are runtime no-ops and their mutants always survive, " + "dragging the score down with noise. See polly#143.";
596
- } catch {
597
- return null;
598
- }
599
- }
600
3476
 
601
3477
  // tools/mutate/src/cli.ts
602
3478
  var HELP = `polly mutate — mutation testing + useless-test detection
@@ -609,8 +3485,10 @@ theatre (code a test ran but never actually checked). How the matrix is built:
609
3485
  tools/mutate/README.md.
610
3486
 
611
3487
  Usage:
612
- polly mutate init [--force] Scaffold a stryker.conf.json for this project
613
- polly mutate [run] Run Stryker, then print the useless-test report
3488
+ polly mutate init [--force] Scaffold a polly.mutate.ts for this project
3489
+ polly mutate migrate [--write] Convert stryker.conf.json to polly.mutate.ts (prints it
3490
+ unless --write; --force overwrites an existing one)
3491
+ polly mutate [run] Run mutation testing, then print the useless-test report
614
3492
  polly mutate report Print the report from an existing mutation.json
615
3493
  polly mutate decisions Review verdicts: needs-review / stale / settled
616
3494
  polly mutate decisions decide <file> <keep|prune|rewrite|investigate> "<rationale>"
@@ -618,16 +3496,35 @@ Usage:
618
3496
  polly mutate help Show this help
619
3497
 
620
3498
  Flags:
621
- --config <path> Stryker config (default: auto-discovered)
3499
+ --config <path> polly.mutate.ts, or a stryker.conf.json (default: ./polly.mutate.ts,
3500
+ else the discovered Stryker config, deprecated)
622
3501
  --report <path> mutation report JSON (default: reports/mutation/mutation.json)
623
3502
  --decisions <path> verdict log (default: .polly/test-debt/decisions.jsonl)
624
3503
  --db <path> intermediate SQLite (default: in-memory)
625
3504
  --no-report 'run' only — skip the analysis
3505
+ --files <a,b> mutate only these files (globs and :from-to ranges allowed)
3506
+ --since <git-ref> mutate only targets changed since the ref
3507
+ --in-tree run tests in the project dir, not a scratch cwd
3508
+ --concurrency <n> parallel test processes (default: config, else cores-1)
3509
+ --mode <fast|matrix> fast stops each run at the first failing test (default
3510
+ unless the config sets mode);
3511
+ matrix runs every test and records each killer (the kill matrix)
3512
+ --coverage <dynamic|static> dynamic (default) runs one probed pass to find the
3513
+ tests that run each mutant, and marks unrun code NoCoverage;
3514
+ static runs every test file that imports the target
3515
+ --no-cache rerun targets whose inputs are unchanged
3516
+ --no-typecheck run mutants the project's tsconfig rejects (default: report
3517
+ them CompileError without a run; needs typescript-7)
3518
+ --contracts <off|ensures|all> POLLY_CONTRACTS for every test process: a false
3519
+ requires/ensures throws, so each contract kills the mutants
3520
+ that falsify it (default all; ensures leaves requires inert;
3521
+ a baseline that violates a contract stops the run)
626
3522
  -h, --help
627
3523
 
628
- The redundancy/subsumption sections need a COMPLETE kill matrix (the no-bail
629
- patched Bun runner). Without it the report degrades to score + gaps + theatre;
630
- 'polly mutate verify' diagnoses the matrix.`;
3524
+ The redundancy/subsumption sections need a COMPLETE kill matrix ('--mode matrix').
3525
+ Without it the report degrades
3526
+ to score + gaps + theatre; 'polly mutate verify' diagnoses the matrix
3527
+ ('verify --run' runs a matrix pass first).`;
631
3528
  async function openDb(reportPath, dbPath) {
632
3529
  if (!await Bun.file(reportPath).exists()) {
633
3530
  console.log(`no mutation report at ${reportPath}. Run 'polly mutate run' first, or pass --report <path>.`);
@@ -635,6 +3532,46 @@ async function openDb(reportPath, dbPath) {
635
3532
  }
636
3533
  return buildDb(await loadMutationReport(reportPath), dbPath);
637
3534
  }
3535
+ async function init(cwd, force) {
3536
+ const result = await initConfig(cwd, { force });
3537
+ if (!result.created) {
3538
+ console.log(`${result.configPath} already exists. Re-run with --force to overwrite.`);
3539
+ return 1;
3540
+ }
3541
+ console.log(`✓ wrote ${result.configPath}`);
3542
+ console.log(` import: ${result.specifier}`);
3543
+ console.log(` targets: ${result.mutate.join(", ")}`);
3544
+ console.log(` tests: ${result.testGlob}`);
3545
+ for (const w of result.warnings)
3546
+ console.log(` ⚠ ${w}`);
3547
+ console.log(`
3548
+ Next: polly mutate run`);
3549
+ return 0;
3550
+ }
3551
+ async function migrate(cwd, args) {
3552
+ const strykerPath = args.config ? resolve5(cwd, args.config) : (await findStrykerConfigs(cwd))[0] ?? null;
3553
+ if (!strykerPath) {
3554
+ console.log("no stryker.conf.json found — pass --config <path>");
3555
+ return 1;
3556
+ }
3557
+ const result = await migrateConfig(strykerPath, { write: args.write, force: args.force });
3558
+ for (const n of result.notes)
3559
+ console.log(`note: ${n}`);
3560
+ if (!args.write) {
3561
+ console.log(`
3562
+ // ${result.path}
3563
+ ${result.source}`);
3564
+ console.log("Re-run with --write to write it.");
3565
+ return 0;
3566
+ }
3567
+ if (!result.written) {
3568
+ console.log(`${result.path} already exists. Re-run with --force to overwrite.`);
3569
+ return 1;
3570
+ }
3571
+ console.log(`✓ wrote ${result.path}`);
3572
+ console.log(` ${strykerPath} is no longer read once polly.mutate.ts exists; delete it.`);
3573
+ return 0;
3574
+ }
638
3575
  async function main() {
639
3576
  const args = parseMutateArgs(process.argv.slice(2));
640
3577
  if (args.help) {
@@ -642,30 +3579,15 @@ async function main() {
642
3579
  return 0;
643
3580
  }
644
3581
  const cwd = process.cwd();
3582
+ if (args.verb === "init")
3583
+ return await init(cwd, args.force);
3584
+ if (args.verb === "migrate")
3585
+ return await migrate(cwd, args);
645
3586
  const cfg = await resolveMutateConfig(cwd, args);
646
3587
  switch (args.verb) {
647
- case "init": {
648
- const result = await initConfig(cwd, { force: args.force });
649
- if (!result.created) {
650
- console.log(`stryker.conf.json already exists at ${result.configPath}. Re-run with --force to overwrite.`);
651
- return 1;
652
- }
653
- console.log(`✓ wrote ${result.configPath}`);
654
- console.log(` plugin: ${result.pluginRef}`);
655
- console.log(` mutate: ${result.mutate.join(", ")}`);
656
- console.log(` testFiles: ${result.testGlob}`);
657
- for (const w of result.warnings)
658
- console.log(` ⚠ ${w}`);
659
- console.log(`
660
- Next: polly mutate run`);
661
- return 0;
662
- }
663
3588
  case "run": {
664
- const tip = await presetAdvisory(cfg);
665
- if (tip)
666
- console.log(`${tip}
667
- `);
668
- const code = await runStryker(cfg);
3589
+ resolveEngine(args);
3590
+ const code = await runBunEngine(cfg, args);
669
3591
  if (code !== 0)
670
3592
  return code;
671
3593
  if (args.noReport)
@@ -699,18 +3621,18 @@ ${await reportFromFile(cfg)}`);
699
3621
  return 0;
700
3622
  }
701
3623
  case "verify": {
702
- const result = await verifyMatrix({
703
- reportPath: cfg.reportPath,
704
- run: args.run,
705
- strykerConfig: cfg.strykerConfigPath ?? undefined
706
- });
3624
+ if (args.run) {
3625
+ resolveEngine(args);
3626
+ await runBunEngine(cfg, { ...args, mode: "matrix" });
3627
+ }
3628
+ const result = await verifyMatrix({ reportPath: cfg.reportPath });
707
3629
  console.log(`
708
3630
  Kill-matrix contract:`);
709
3631
  for (const c of result.checks)
710
3632
  console.log(` ${c.ok ? "✓" : "✗"} ${c.name} (${c.detail})`);
711
3633
  if (!result.ok) {
712
3634
  console.log(`
713
- ✗ Contract broken. The pinned pair has drifted — re-check Bun version and that the patch applies (bun install).`);
3635
+ ✗ Contract broken. Re-check the Bun version: matrix mode reads Bun's junit output (engine/junit.ts).`);
714
3636
  return 1;
715
3637
  }
716
3638
  console.log(`
@@ -730,4 +3652,4 @@ main().then((code) => process.exit(code)).catch((err) => {
730
3652
  process.exit(1);
731
3653
  });
732
3654
 
733
- //# debugId=C09CAFE7F39DD42A64756E2164756E21
3655
+ //# debugId=CC8EAB1F4899808564756E2164756E21