mutant-cafe 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -129,18 +129,36 @@ var Baseline = Schema3.Struct({
129
129
  unreliable: Schema3.optional(Schema3.Array(SelectionIssue))
130
130
  });
131
131
  var NotMutated = Schema3.Struct({
132
+ // Optional on decode for existing schemaVersion 2 reports; discovery always supplies it.
133
+ span: Schema3.optional(Span),
132
134
  file: Schema3.String,
133
135
  functionName: Schema3.String,
134
136
  reason: Schema3.String
135
137
  });
138
+ var SelectionCounts = Schema3.Struct({
139
+ selected: Schema3.Int,
140
+ run: Schema3.Int,
141
+ budgetSkipped: Schema3.Int
142
+ });
143
+ var MutantList = Schema3.Struct({
144
+ schemaVersion: Schema3.Literal(2),
145
+ tool: Schema3.Literal("mutant.cafe"),
146
+ mutants: Schema3.Array(Mutant),
147
+ notMutated: Schema3.Array(NotMutated),
148
+ counts: SelectionCounts
149
+ });
136
150
  var RunReport = Schema3.Struct({
151
+ selected: Schema3.optional(Schema3.Int),
152
+ run: Schema3.optional(Schema3.Int),
153
+ budgetSkipped: Schema3.optional(Schema3.Int),
137
154
  schemaVersion: Schema3.Literal(2),
138
155
  tool: Schema3.Literal("mutant.cafe"),
139
156
  root: Schema3.String,
140
157
  baseline: Baseline,
141
158
  timeoutMs: Schema3.Int,
142
159
  results: Schema3.Array(MutantResult),
143
- failure: Schema3.optional(Schema3.String)
160
+ failure: Schema3.optional(Schema3.String),
161
+ notMutated: Schema3.optional(Schema3.Array(NotMutated))
144
162
  });
145
163
 
146
164
  // packages/core/src/Services.ts
@@ -162,33 +180,39 @@ import * as Schema4 from "effect/Schema";
162
180
 
163
181
  // packages/engine/src/Generate.ts
164
182
  import { createHash } from "node:crypto";
165
- function* generateFunction(fn8) {
166
- const api = fn8.api;
183
+ function* generateFunction(fn9) {
184
+ const issue = fn9.generationIssue?.();
185
+ if (issue) return issue;
186
+ const api = fn9.api;
167
187
  const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
168
- const pinned = `((): ${fn8.returnType} => (${expression}))()`;
169
- const text = fn8.block ? `{ return ${fn8.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
170
- return makeMutant(fn8, genre, text, value.synthetic, description);
188
+ const pinned = `((): ${fn9.returnType} => (${expression}))()`;
189
+ const text = fn9.block ? `{ return ${fn9.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
190
+ return makeMutant(fn9, genre, text, value.synthetic, description);
171
191
  };
172
- const shape = fn8.shape;
192
+ const shape = fn9.shape;
193
+ const fits = (value) => new TextEncoder().encode(value.text).byteLength <= 2048;
194
+ const values = "values" in shape ? shape.values.filter(fits) : [];
173
195
  switch (shape.kind) {
174
196
  case "Effect": {
175
- const succeed3 = api("Effect", "succeed");
176
- if (succeed3) {
177
- for (const value of shape.values) {
178
- if (!fn8.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed3}(${value.text})`, value);
197
+ const succeed4 = api("Effect", "succeed");
198
+ if (succeed4) {
199
+ for (const value of values) {
200
+ if (!fn9.equivalentValues.includes(value.text) && !(fn9.generator && value.text === fn9.literal)) yield candidate("EffectSucceed", `${succeed4}(${value.text})`, value);
179
201
  }
180
202
  }
181
203
  const fail3 = api("Effect", "fail");
182
- const catchTag2 = api("Effect", "catchTag");
183
- for (const error2 of shape.errors) {
184
- if (fail3) yield candidate("EffectFail", `${fail3}(${error2.text})`, error2, `${fail3}(${error2.text}) [${error2.synthetic ? "synthetic tag cast" : "constructed error"}]`);
185
- const value = shape.values[0];
186
- const die3 = api("Effect", "die");
187
- const recovery = value && succeed3 ? `${succeed3}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error2.tag}`)})` : void 0;
188
- if (catchTag2 && recovery) {
189
- const gen8 = api("Effect", "gen");
190
- const original = fn8.generator ? gen8 && `((): ${fn8.returnType} => ${gen8}(function* () ${fn8.original}))()` : fn8.block ? `((): ${fn8.returnType} => ${fn8.original})()` : `((): ${fn8.returnType} => (${fn8.original}))()`;
191
- if (original) yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))` : `turn ${error2.tag} into a defect`);
204
+ const catchTag3 = api("Effect", "catchTag");
205
+ for (const error3 of shape.errors) {
206
+ if (fail3 && fits(error3)) yield candidate("EffectFail", `${fail3}(${error3.text})`, error3, `${fail3}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
207
+ const recoveries = values.length ? shape.enumerateRecoveries ? values : values.slice(0, 1) : [void 0];
208
+ const gen9 = api("Effect", "gen");
209
+ const original = fn9.generator ? gen9 && `((): ${fn9.returnType} => ${gen9}(function* () ${fn9.original}))()` : fn9.block ? `((): ${fn9.returnType} => ${fn9.original})()` : `((): ${fn9.returnType} => (${fn9.original}))()`;
210
+ for (const value of recoveries) {
211
+ const die3 = api("Effect", "die");
212
+ const recovery = value && succeed4 ? `${succeed4}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
213
+ if (catchTag3 && recovery && original) {
214
+ yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))` : `turn ${error3.tag} into a defect`);
215
+ }
192
216
  }
193
217
  }
194
218
  const die2 = api("Effect", "die");
@@ -201,16 +225,18 @@ function* generateFunction(fn8) {
201
225
  const none = api("Option", "none");
202
226
  const some = api("Option", "some");
203
227
  if (none) yield candidate("OptionNone", `${none}()`);
204
- if (some) for (const value of shape.values) yield candidate("OptionSome", `${some}(${value.text})`, value);
228
+ if (some) for (const value of values) yield candidate("OptionSome", `${some}(${value.text})`, value);
205
229
  break;
206
230
  }
207
231
  case "Stream": {
208
232
  const empty = api("Stream", "empty");
209
- const make8 = api("Stream", "make");
233
+ const make9 = api("Stream", "make");
210
234
  const fail3 = api("Stream", "fail");
211
235
  if (empty) yield candidate("StreamEmpty", empty);
212
- if (make8) for (const value of shape.values) yield candidate("StreamOne", `${make8}(${value.text})`, value);
213
- if (fail3) for (const error2 of shape.errors) yield candidate("StreamFail", `${fail3}(${error2.text})`, error2);
236
+ if (make9) for (const value of values) yield candidate("StreamOne", `${make9}(${value.text})`, value);
237
+ if (fail3) {
238
+ for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${fail3}(${error3.text})`, error3);
239
+ }
214
240
  break;
215
241
  }
216
242
  case "Layer": {
@@ -219,37 +245,37 @@ function* generateFunction(fn8) {
219
245
  const die2 = api("Effect", "die");
220
246
  if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
221
247
  if (layer2 && fail3) {
222
- for (const error2 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail3}(${error2.text}))`, error2);
248
+ for (const error3 of shape.errors) if (fits(error3)) yield candidate("LayerFail", `${layer2}(${fail3}(${error3.text}))`, error3);
223
249
  }
224
250
  break;
225
251
  }
226
252
  case "Void":
227
- yield makeMutant(fn8, "FnValue", "{}", false, "an empty body");
253
+ yield makeMutant(fn9, "FnValue", "{}", false, "an empty body");
228
254
  break;
229
255
  default: {
230
256
  const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
231
- for (const value of shape.values) {
232
- if (shape.kind === "Literal" && value.text === fn8.literal) continue;
257
+ for (const value of values) {
258
+ if (value.text === fn9.literal) continue;
233
259
  yield candidate(genre, value.text, value);
234
260
  }
235
261
  }
236
262
  }
237
263
  }
238
- function makeMutant(fn8, genre, text, synthetic, description) {
239
- const additions = fn8.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
240
- const prefix = fn8.sourcePrefix ?? "";
241
- const insertion = fn8.importInsertionOffset ?? 0;
242
- const replacement = additions.length && fn8.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn8.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn8.startOffset, endOffset: fn8.endOffset, text };
243
- const id = createHash("sha256").update(JSON.stringify([fn8.identityFile ?? fn8.file, fn8.name, fn8.identityOrdinal ?? 0, fn8.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
264
+ function makeMutant(fn9, genre, text, synthetic, description) {
265
+ const additions = fn9.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
266
+ const prefix = fn9.sourcePrefix ?? "";
267
+ const insertion = fn9.importInsertionOffset ?? 0;
268
+ const replacement = additions.length && fn9.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn9.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn9.startOffset, endOffset: fn9.endOffset, text };
269
+ const id = createHash("sha256").update(JSON.stringify([fn9.identityFile ?? fn9.file, fn9.name, fn9.identityOrdinal ?? 0, fn9.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
244
270
  return {
245
271
  id,
246
- file: fn8.file,
247
- functionName: fn8.name,
248
- returnType: fn8.returnType,
249
- displayReturnType: fn8.displayReturnType,
272
+ file: fn9.file,
273
+ functionName: fn9.name,
274
+ returnType: fn9.returnType,
275
+ displayReturnType: fn9.displayReturnType,
250
276
  genre,
251
- description: `replace ${fn8.name} -> ${fn8.returnType} with ${description}`,
252
- span: fn8.span,
277
+ description: `replace ${fn9.name} -> ${fn9.returnType} with ${description}`,
278
+ span: fn9.span,
253
279
  replacement,
254
280
  synthetic
255
281
  };
@@ -294,18 +320,27 @@ var ProgramSession = class {
294
320
  check(mutant) {
295
321
  const file = resolve(mutant.file);
296
322
  const source = this.originals.get(file);
297
- if (!source) throw new ProgramLoadError({ tsconfig: this.configPath, diagnostics: [`File not loaded: ${mutant.file}`] });
323
+ if (!source) return { viable: false, diagnostics: [], analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason: "analysis failed: source file was not loaded" } };
298
324
  const { startOffset, endOffset, text } = mutant.replacement;
299
325
  if (startOffset < 0 || endOffset < startOffset || endOffset > source.text.length) {
300
326
  return { viable: false, diagnostics: ["Replacement offsets are outside the original file"] };
301
327
  }
328
+ const analysisFailed = (reason) => ({
329
+ viable: false,
330
+ diagnostics: [],
331
+ analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason }
332
+ });
302
333
  this.overlay = { file, text: source.text.slice(0, startOffset) + text + source.text.slice(endOffset) };
303
334
  try {
304
335
  const mutated = ts.createProgram({ rootNames: this.program.getRootFileNames(), options: this.program.getCompilerOptions(), host: this.host, oldProgram: this.program });
305
336
  const changed = mutated.getSourceFile(file);
306
337
  if (!changed) throw new Error(`Mutated source not found: ${file}`);
338
+ const issue = typedCallIssue(changed, mutated.getTypeChecker(), true);
339
+ if (issue) return analysisFailed(issue);
307
340
  const diagnostics = [...mutated.getSyntacticDiagnostics(changed), ...mutated.getSemanticDiagnostics(changed)];
308
341
  return { viable: diagnostics.length === 0, diagnostics: diagnosticsText(diagnostics) };
342
+ } catch (error3) {
343
+ return analysisFailed(`analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`);
309
344
  } finally {
310
345
  this.overlay = void 0;
311
346
  }
@@ -336,98 +371,122 @@ function makeTypeScriptOracle() {
336
371
  if (config.exclude.some((glob) => matchesGlob(local, glob))) continue;
337
372
  owners.set(file, session);
338
373
  const api = imports(source);
374
+ const excluded = /* @__PURE__ */ new Set();
339
375
  const visit = (node) => {
340
- if (isFunction(node) && node.body && !mutable(node, checker)) {
341
- notMutated.push({ file, functionName: functionName(node, checker), reason: "unsupported function position: callback, array element or curried implementation" });
342
- }
343
- if (isFunction(node) && node.body && mutable(node, checker)) {
344
- const name = functionName(node, checker);
345
- const reason = skipped(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
346
- if (reason) notMutated.push({ file, functionName: name, reason });
347
- if (!reason && (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter)))) {
348
- const signature = checker.getSignatureFromDeclaration(node);
349
- if (signature) {
350
- const wrapped = wrappedEffect(node, checker);
351
- const type = wrapped ?? checker.getReturnTypeOfSignature(signature);
352
- const generator = wrapped && ts.isFunctionExpression(node) ? node : generatorBody(node, checker);
353
- const body = generator?.body ?? node.body;
354
- const start = body.getStart(source);
355
- const end = body.getEnd();
356
- const a = source.getLineAndCharacterOfPosition(start);
357
- const b = source.getLineAndCharacterOfPosition(end);
358
- const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
359
- const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
360
- const originals = equivalentSuccessValues(body, api);
361
- if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
362
- notMutated.push({ file, functionName: name, reason: "generic: naked or context-only type-parameter return" });
363
- } else found.push({
364
- file,
365
- name,
366
- returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
367
- displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
368
- skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
369
- equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
370
- span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
371
- startOffset: start,
372
- endOffset: end,
373
- original: body.getText(source),
374
- identityFile: local,
375
- logicalSpan: { offset: start - node.getStart(source), length: end - start },
376
- sourcePrefix: source.text.slice(0, start),
377
- importInsertionOffset: importInsertionOffset(source),
378
- extraImports: mutationImports(source),
379
- literal: literalOfBody(body, checker),
380
- block: ts.isBlock(body),
381
- generator: generator !== void 0,
382
- shape,
383
- api
384
- });
385
- } else notMutated.push({ file, functionName: name, reason: "missing callable signature" });
376
+ try {
377
+ if (isFunction(node) && node.body && !mutable(node, checker)) {
378
+ if (!ts.findAncestor(node.parent, (parent) => excluded.has(parent))) notMutated.push({ file, functionName: `${functionName(node, checker)}.<callback>`, span: nodeSpan(node), reason: "callback position (not mutated yet)" });
386
379
  }
387
- }
388
- if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
389
- const type = checker.getTypeAtLocation(node.initializer);
390
- if (family(type, checker)?.kind === "Layer") {
391
- const name = valuePath(node);
392
- const reason = skippedNode(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
393
- if (reason) notMutated.push({ file, functionName: name, reason });
394
- else if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
395
- const body = node.initializer;
396
- const a = source.getLineAndCharacterOfPosition(body.getStart(source));
397
- const b = source.getLineAndCharacterOfPosition(body.getEnd());
398
- found.push({
399
- file,
400
- name,
401
- returnType: returnTypeText(type, checker, node),
402
- displayReturnType: checker.typeToString(type, node),
403
- equivalentValues: [],
404
- span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
405
- startOffset: body.getStart(source),
406
- endOffset: body.getEnd(),
407
- original: body.getText(source),
408
- literal: void 0,
409
- identityFile: local,
410
- logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
411
- sourcePrefix: source.text.slice(0, body.getStart(source)),
412
- importInsertionOffset: importInsertionOffset(source),
413
- extraImports: mutationImports(source),
414
- block: false,
415
- generator: false,
416
- shape: shapeOf(type, checker, node, body),
417
- api
418
- });
380
+ if (isFunction(node) && node.body && mutable(node, checker)) {
381
+ const name = functionName(node, checker);
382
+ const reason = skipped(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
383
+ if (reason) {
384
+ excluded.add(node);
385
+ notMutated.push({ file, functionName: name, span: nodeSpan(node.body), reason });
386
+ }
387
+ if (!reason && (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter)))) {
388
+ const signature = checker.getSignatureFromDeclaration(node);
389
+ if (signature) {
390
+ const wrapped = wrappedEffect(node, checker);
391
+ const type = wrapped ?? checker.getReturnTypeOfSignature(signature);
392
+ const generator = wrapped && ts.isFunctionExpression(node) ? node : generatorBody(node, checker);
393
+ const body = generator?.body ?? node.body;
394
+ const start = body.getStart(source);
395
+ const end = body.getEnd();
396
+ const a = source.getLineAndCharacterOfPosition(start);
397
+ const b = source.getLineAndCharacterOfPosition(end);
398
+ const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
399
+ const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
400
+ const originals = equivalentSuccessValues(body, api);
401
+ if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
402
+ notMutated.push({ file, functionName: name, span: nodeSpan(node), reason: "generic: naked or context-only type-parameter return" });
403
+ } else found.push({
404
+ file,
405
+ name,
406
+ functionLike: true,
407
+ functionSpan: nodeSpan(body),
408
+ generationIssue: () => typedCallIssue(body, checker),
409
+ notices: shapeNotices(shape, type, checker, node),
410
+ returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
411
+ displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
412
+ skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
413
+ equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
414
+ span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
415
+ startOffset: start,
416
+ endOffset: end,
417
+ original: body.getText(source),
418
+ identityFile: local,
419
+ logicalSpan: { offset: start - node.getStart(source), length: end - start },
420
+ sourcePrefix: source.text.slice(0, start),
421
+ importInsertionOffset: importInsertionOffset(source),
422
+ extraImports: mutationImports(source),
423
+ literal: literalOfBody(body, checker),
424
+ block: ts.isBlock(body),
425
+ generator: generator !== void 0,
426
+ shape,
427
+ api
428
+ });
429
+ } else notMutated.push({ file, functionName: name, span: nodeSpan(node), reason: "missing callable signature" });
430
+ }
431
+ }
432
+ if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
433
+ const type = checker.getTypeAtLocation(node.initializer);
434
+ if (family(type, checker)?.kind === "Layer") {
435
+ const name = valuePath(node);
436
+ const reason = skippedNode(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
437
+ if (reason) {
438
+ excluded.add(node.initializer);
439
+ notMutated.push({ file, functionName: name, span: nodeSpan(node.initializer), reason });
440
+ }
441
+ if (!reason) {
442
+ const body = node.initializer;
443
+ const a = source.getLineAndCharacterOfPosition(body.getStart(source));
444
+ const b = source.getLineAndCharacterOfPosition(body.getEnd());
445
+ found.push({
446
+ file,
447
+ name,
448
+ functionLike: false,
449
+ generationIssue: () => typedCallIssue(body, checker),
450
+ notices: shapeNotices(shapeOf(type, checker, node, body), type, checker, node),
451
+ returnType: returnTypeText(type, checker, node),
452
+ displayReturnType: checker.typeToString(type, node),
453
+ equivalentValues: [],
454
+ span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
455
+ startOffset: body.getStart(source),
456
+ endOffset: body.getEnd(),
457
+ original: body.getText(source),
458
+ literal: void 0,
459
+ identityFile: local,
460
+ logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
461
+ sourcePrefix: source.text.slice(0, body.getStart(source)),
462
+ importInsertionOffset: importInsertionOffset(source),
463
+ extraImports: mutationImports(source),
464
+ block: false,
465
+ generator: false,
466
+ shape: shapeOf(type, checker, node, body),
467
+ api
468
+ });
469
+ }
419
470
  }
420
471
  }
472
+ } catch (error3) {
473
+ const target = isFunction(node) ? node.body : ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node) ? node.initializer : void 0;
474
+ if (target) notMutated.push({
475
+ file,
476
+ functionName: valuePath(node),
477
+ span: nodeSpan(target),
478
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
479
+ });
421
480
  }
422
481
  ts.forEachChild(node, visit);
423
482
  };
424
483
  const found = [];
425
484
  visit(source);
426
485
  const occurrences = /* @__PURE__ */ new Map();
427
- for (const fn8 of found) {
428
- const ordinal = occurrences.get(fn8.name) ?? 0;
429
- occurrences.set(fn8.name, ordinal + 1);
430
- functions.push({ ...fn8, identityOrdinal: ordinal });
486
+ for (const fn9 of found) {
487
+ const ordinal = occurrences.get(fn9.name) ?? 0;
488
+ occurrences.set(fn9.name, ordinal + 1);
489
+ functions.push({ ...fn9, identityOrdinal: ordinal });
431
490
  }
432
491
  }
433
492
  const unmatched = config.include.filter((glob) => !matched.has(glob));
@@ -436,15 +495,37 @@ function makeTypeScriptOracle() {
436
495
  const outside = target === ".." || target.startsWith("../");
437
496
  return `No source file matched ${JSON.stringify(glob)}${outside ? " (path is outside the package root)" : ""}`;
438
497
  }) });
439
- return { functions, notMutated };
498
+ return { functions, notMutated: [...new Map(notMutated.map((item) => [JSON.stringify(item), item])).values()] };
440
499
  },
441
500
  checkViable(mutant) {
442
501
  const session = owners.get(resolve(mutant.file));
443
- if (!session) throw new ProgramLoadError({ tsconfig: "", diagnostics: ["Generate mutants before checking viability"] });
502
+ if (!session) return { viable: false, diagnostics: [], analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason: "analysis failed: generate mutants before checking viability" } };
444
503
  return session.check(mutant);
445
504
  }
446
505
  };
447
506
  }
507
+ function typedCallIssue(body, checker, includeNested = false) {
508
+ let issue;
509
+ const visit = (node) => {
510
+ if (isFunction(node) && !includeNested) return;
511
+ if (ts.isCallExpression(node) && node.typeArguments?.length) {
512
+ const signature = checker.getResolvedSignature(node);
513
+ if (!signature || !signature.declaration && checker.getTypeAtLocation(node.expression).flags & ts.TypeFlags.Any) {
514
+ issue = `analysis failed: compiler supplied no declaration for typed call ${node.expression.getText()}; check its import or receiver type`;
515
+ return;
516
+ }
517
+ }
518
+ ts.forEachChild(node, visit);
519
+ };
520
+ visit(body);
521
+ return issue;
522
+ }
523
+ function nodeSpan(node) {
524
+ const source = node.getSourceFile();
525
+ const a = source.getLineAndCharacterOfPosition(node.getStart(source));
526
+ const b = source.getLineAndCharacterOfPosition(node.getEnd());
527
+ return { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } };
528
+ }
448
529
  function isFunction(node) {
449
530
  return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
450
531
  }
@@ -600,8 +681,8 @@ function nameableContract(contract, checker, node) {
600
681
  return contract.types.every((type) => !hasUnnameableType(type, checker, node));
601
682
  }
602
683
  function hasUnnameableType(type, checker, location) {
603
- const printed = checker.typeToTypeNode(type, location, ts.NodeBuilderFlags.NoTruncation);
604
- if (!printed) return true;
684
+ if (isFunction(location) && location.type && !location.asteriskToken) return false;
685
+ const printed = ts.createSourceFile("contract.ts", `type Contract = ${returnTypeText(type, checker, location)};`, ts.ScriptTarget.Latest, true);
605
686
  let missing = false;
606
687
  const visit = (node) => {
607
688
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !checker.resolveName(node.typeName.text, location, ts.SymbolFlags.Type, false)) missing = true;
@@ -626,7 +707,7 @@ function generatorContract(node, checker) {
626
707
  return {
627
708
  types: [success, ...effects.flatMap((effect5) => effect5.args.slice(1))],
628
709
  text: `import("effect/Effect").Effect<${print(success)}, ${union(1)}, ${union(2)}>`,
629
- shape: { kind: "Effect", values: valuesOf(success, checker, node), errors: [...new Map(effects.flatMap((f) => f.args[1] ? taggedValues(f.args[1], checker, node) : []).map((e) => [e.tag, e])).values()] }
710
+ shape: { kind: "Effect", values: boundedValues(success, checker, node).values, omittedValues: boundedValues(success, checker, node).omitted, synthesisIssues: boundedValues(success, checker, node).issues, enumerateRecoveries: smallFinite(success), errors: [...new Map(effects.flatMap((f) => f.args[1] ? taggedValues(f.args[1], checker, node) : []).map((e) => [e.tag, e])).values()] }
630
711
  };
631
712
  }
632
713
  function literalOfBody(body, checker) {
@@ -634,7 +715,7 @@ function literalOfBody(body, checker) {
634
715
  const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
635
716
  if (!expression) return void 0;
636
717
  const type = checker.getTypeAtLocation(expression);
637
- return type.isStringLiteral() ? JSON.stringify(type.value) : type.isNumberLiteral() ? String(type.value) : void 0;
718
+ return type.isStringLiteral() ? JSON.stringify(type.value) : type.isNumberLiteral() ? String(type.value) : type.flags & ts.TypeFlags.BooleanLiteral ? checker.typeToString(type) : void 0;
638
719
  }
639
720
  function generatorBody(node, checker) {
640
721
  if (!node.body) return void 0;
@@ -726,34 +807,40 @@ function family(type, checker) {
726
807
  function shapeOf(type, checker, node, body) {
727
808
  if (type.isUnion() && type.types.every((member) => family(member, checker)?.kind === "Effect")) {
728
809
  const shapes = type.types.map((member) => shapeOf(member, checker, node, body));
729
- const values2 = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
810
+ const successes = type.types.flatMap((member) => family(member, checker)?.args[0] ?? []);
811
+ const bounded2 = boundCandidates(successes.flatMap((success) => valuesOf(success, checker, node)), successes, node);
730
812
  const errors = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.errors : []);
731
813
  return {
732
814
  kind: "Effect",
733
- values: [...new Map(values2.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
734
- errors: [...new Map(errors.map((error2) => [error2.tag, error2])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
815
+ values: bounded2.values,
816
+ omittedValues: bounded2.omitted,
817
+ synthesisIssues: shapes.flatMap((shape) => shape.synthesisIssues ?? []),
818
+ enumerateRecoveries: bounded2.values.length <= 4 && successes.every(smallFinite),
819
+ errors: [...new Map(errors.map((error3) => [error3.tag, error3])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
735
820
  };
736
821
  }
737
822
  const detected = family(type, checker);
738
823
  if (detected) {
739
824
  const [a, e] = detected.args;
740
- const values2 = a ? valuesOf(a, checker, node) : [];
741
- if (detected.kind === "Option") return { kind: "Option", values: values2 };
825
+ if (detected.kind === "Layer") return { kind: "Layer", errors: e ? taggedValues(e, checker, node) : [] };
826
+ const bounded2 = a ? boundedValues(a, checker, node) : { values: [], omitted: 0, issues: [] };
827
+ const values2 = bounded2.values;
828
+ if (detected.kind === "Option") return { kind: "Option", values: values2, omittedValues: bounded2.omitted, synthesisIssues: bounded2.issues };
742
829
  const errors = e ? taggedValues(e, checker, node) : [];
743
- if (detected.kind === "Layer") return { kind: "Layer", errors };
744
- return { kind: detected.kind, values: values2, errors };
830
+ return { kind: detected.kind, values: values2, errors, omittedValues: bounded2.omitted, synthesisIssues: bounded2.issues, enumerateRecoveries: a !== void 0 && smallFinite(a) };
745
831
  }
746
832
  if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
747
833
  const members = type.isUnion() ? type.types : [type];
748
834
  const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
749
835
  const literal = members.every((t) => t.isLiteral());
750
- const values = valuesOf(type, checker, node);
836
+ const bounded = boundedValues(type, checker, node);
837
+ const values = bounded.values;
751
838
  if (isFunction(node)) for (const parameter of node.parameters) {
752
- if (ts.isIdentifier(parameter.name) && !parameter.questionToken && !parameter.dotDotDotToken && checker.getTypeAtLocation(parameter) === type) {
839
+ if (ts.isIdentifier(parameter.name) && checker.isTypeAssignableTo(checker.getTypeAtLocation(parameter), type)) {
753
840
  values.push({ text: parameter.name.text, synthetic: false });
754
841
  }
755
842
  }
756
- return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values };
843
+ return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values, omittedValues: bounded.omitted, synthesisIssues: bounded.issues };
757
844
  }
758
845
  function taggedValues(type, checker, location) {
759
846
  return (type.isUnion() ? type.types : [type]).flatMap((member) => {
@@ -766,32 +853,60 @@ function taggedValues(type, checker, location) {
766
853
  });
767
854
  }
768
855
  function constructError(type, checker, location, tag) {
856
+ const synthetic = (reason) => ({
857
+ text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${returnTypeText(type, checker, location)})`,
858
+ synthetic: true,
859
+ ...reason ? { reason } : {}
860
+ });
769
861
  const symbol = type.getSymbol();
770
862
  if (symbol) {
771
863
  const visible = checker.getSymbolsInScope(location, ts.SymbolFlags.Value | ts.SymbolFlags.Alias).find((candidate) => {
772
- if (candidate.declarations?.some((declaration) => ts.isImportSpecifier(declaration) && (declaration.isTypeOnly || declaration.parent.parent.isTypeOnly))) return false;
864
+ if (candidate.declarations?.some((declaration) => ts.isImportClause(declaration) && declaration.isTypeOnly || ts.isImportSpecifier(declaration) && (declaration.isTypeOnly || declaration.parent.parent.isTypeOnly))) return false;
773
865
  const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
774
866
  return target === symbol || (symbol.declarations?.some((declaration) => target.declarations?.includes(declaration)) ?? false);
775
867
  });
776
868
  if (visible) {
777
869
  const constructor = checker.getTypeOfSymbolAtLocation(visible, location).getConstructSignatures()[0];
778
870
  if (constructor) {
779
- const param = constructor.parameters[0];
780
- if (!param) return { text: `new ${visible.name}()`, synthetic: false };
781
- const fields = checker.getTypeOfSymbolAtLocation(param, location);
782
- if (fields.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) return { text: `new ${visible.name}()`, synthetic: false };
783
- const value = valuesOf(fields, checker, location)[0];
784
- if (value && !value.synthetic) {
785
- const rest = param.valueDeclaration && ts.isParameter(param.valueDeclaration) && param.valueDeclaration.dotDotDotToken;
786
- return { text: `new ${visible.name}(${rest ? "..." : ""}${value.text})`, synthetic: false };
871
+ const arguments_ = [];
872
+ for (const param of constructor.parameters) {
873
+ const fields = checker.getTypeOfSymbolAtLocation(param, location);
874
+ if (fields.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) continue;
875
+ const issues = /* @__PURE__ */ new Set();
876
+ const value = valuesOf(fields, checker, location, /* @__PURE__ */ new Set(), 0, issues)[0];
877
+ if (!value || value.synthetic) {
878
+ const reason = synthesisReason(fields, checker, location);
879
+ const field = /\(field ([^)]+)\)/.exec(reason)?.[1];
880
+ const detail = field ? `field ${field}` : `argument ${param.name} is not synthesizable`;
881
+ return synthetic(detail + (issues.size ? ` (${[...issues].join("; ")})` : ""));
882
+ }
883
+ const declaration = param.valueDeclaration;
884
+ const rest = declaration && ts.isParameter(declaration) && declaration.dotDotDotToken;
885
+ arguments_.push(`${rest ? "..." : ""}${value.text}`);
787
886
  }
887
+ return { text: `new ${visible.name}(${arguments_.join(", ")})`, synthetic: false };
788
888
  }
789
889
  }
890
+ if (symbol.declarations?.some(ts.isClassDeclaration)) {
891
+ return synthetic(visible ? "constructor arguments are not synthesizable" : "class is not available as a value; import its constructor");
892
+ }
790
893
  }
791
- return { text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${checker.typeToString(type, location, ts.TypeFormatFlags.NoTruncation)})`, synthetic: true };
894
+ return synthetic();
792
895
  }
793
896
  function returnTypeText(type, checker, node) {
794
- const print = (t) => checker.typeToString(t, node, ts.TypeFormatFlags.NoTruncation);
897
+ if (isFunction(node) && node.type && !node.asteriskToken && checker.getTypeFromTypeNode(node.type) === type) return node.type.getText();
898
+ const print = (t) => {
899
+ if (t.isUnion()) return t.types.map(print).join(" | ");
900
+ const symbol = t.getSymbol();
901
+ if (symbol && !checker.resolveName(symbol.name, node, ts.SymbolFlags.Type, false)) {
902
+ const alias = checker.getSymbolsInScope(node, ts.SymbolFlags.Type | ts.SymbolFlags.Alias).find((candidate) => {
903
+ const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
904
+ return !!target.declarations?.length && checker.getDeclaredTypeOfSymbol(target) === t;
905
+ });
906
+ if (alias) return alias.name;
907
+ }
908
+ return checker.typeToString(t, node, ts.TypeFormatFlags.NoTruncation);
909
+ };
795
910
  if (type.isUnion()) {
796
911
  const members = type.types.map((member) => family(member, checker));
797
912
  if (members.every((member) => member?.kind === "Effect")) {
@@ -799,11 +914,19 @@ function returnTypeText(type, checker, node) {
799
914
  return `import("effect/Effect").Effect<${args.join(", ")}>`;
800
915
  }
801
916
  }
917
+ const detected = family(type, checker);
918
+ if (detected) return `import("effect/${detected.kind}").${detected.kind}<${detected.args.map(print).join(", ")}>`;
802
919
  return print(type);
803
920
  }
804
921
  function literalData(node) {
805
922
  if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return literalData(node.expression);
806
923
  if (ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return [node.kind, node.text];
924
+ if (ts.isIdentifier(node) && node.text === "undefined") return ["undefined"];
925
+ if (ts.isPrefixUnaryExpression(node)) return [node.operator, literalData(node.operand)];
926
+ if (ts.isArrayLiteralExpression(node)) {
927
+ const items = node.elements.map(literalData);
928
+ return items.every((item) => item !== void 0) ? ["array", items] : void 0;
929
+ }
807
930
  if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword) return [node.kind];
808
931
  if (ts.isObjectLiteralExpression(node)) {
809
932
  const fields = [];
@@ -838,23 +961,102 @@ function isEquivalentSuccess(text, values) {
838
961
  }
839
962
  function synthesisReason(type, checker, node) {
840
963
  if (type.flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess)) return "generic return cannot be synthesized";
841
- const detected = family(type, checker);
842
- const valueType = detected?.args[0] ?? type;
843
- for (const field of valueType.getProperties()) {
844
- if (!(field.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field, node), checker, node).length) {
845
- return `no synthesizable value for field ${field.name}`;
846
- }
964
+ const valueType = family(type, checker)?.args[0] ?? type;
965
+ const field = valueType.getProperties().find((field2) => /^[$\w]+$/.test(field2.name) && !(field2.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field2, node), checker, node).length);
966
+ const symbol = valueType.aliasSymbol ?? valueType.getSymbol();
967
+ const name = symbol && !symbol.name.startsWith("__") ? symbol.name : valueType.isUnion() ? "union" : valueType.flags & ts.TypeFlags.Object || valueType.isIntersection() ? "object" : checker.typeToString(valueType, node);
968
+ return field ? `return not synthesizable (field ${field.name})` : `return not synthesizable (type ${name})`;
969
+ }
970
+ function valueKey(text) {
971
+ const source = ts.createSourceFile("value.ts", `(${text})`, ts.ScriptTarget.Latest, true);
972
+ const statement = source.statements[0];
973
+ const data = statement && ts.isExpressionStatement(statement) ? literalData(statement.expression) : void 0;
974
+ return data === void 0 ? text : JSON.stringify(data);
975
+ }
976
+ function boundedValues(type, checker, node) {
977
+ const issues = /* @__PURE__ */ new Set();
978
+ return { ...boundCandidates(valuesOf(type, checker, node, /* @__PURE__ */ new Set(), 0, issues), [type], node), issues: [...issues] };
979
+ }
980
+ function smallFinite(type) {
981
+ const members = type.isUnion() ? type.types : [type];
982
+ return members.length <= 4 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
983
+ }
984
+ function boundCandidates(candidates, types2, node) {
985
+ const unique = [...new Map(candidates.map((value) => [valueKey(value.text), value])).values()];
986
+ const members = types2.flatMap((type) => type.isUnion() ? type.types : [type]);
987
+ const finite = members.length <= 8 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
988
+ if (finite || unique.length <= 6) return { values: unique, omitted: 0 };
989
+ const absence = unique.find((value) => value.text === "undefined");
990
+ const defined = unique.filter((value) => value !== absence);
991
+ const preferred = ["null", '""', "0", "false", "[]", "({ })"].flatMap((text) => {
992
+ const candidate = defined.find((value) => valueKey(value.text) === valueKey(text));
993
+ return candidate ? [candidate] : [];
994
+ });
995
+ const original = returnedDiscriminants(node);
996
+ const priority = defined.filter((candidate) => {
997
+ const source = ts.createSourceFile("value.ts", `(${candidate.text})`, ts.ScriptTarget.Latest, true);
998
+ const statement = source.statements[0];
999
+ return statement && ts.isExpressionStatement(statement) && objectDiscriminants(statement.expression).some((key) => original.has(key));
1000
+ });
1001
+ const selected = [.../* @__PURE__ */ new Set([...priority, ...preferred, ...defined])].slice(0, 6);
1002
+ if (absence) selected.push(absence);
1003
+ return { values: selected, omitted: unique.length - selected.length };
1004
+ }
1005
+ function objectDiscriminants(node) {
1006
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) node = node.expression;
1007
+ if (!ts.isObjectLiteralExpression(node)) return [];
1008
+ return node.properties.flatMap((field) => {
1009
+ if (!ts.isPropertyAssignment(field) || ts.isComputedPropertyName(field.name)) return [];
1010
+ let value = field.initializer;
1011
+ while (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isSatisfiesExpression(value)) value = value.expression;
1012
+ return ts.isStringLiteral(value) || ts.isNumericLiteral(value) ? [JSON.stringify([field.name.getText().replace(/^["']|["']$/g, ""), value.text])] : [];
1013
+ });
1014
+ }
1015
+ function returnedDiscriminants(node) {
1016
+ if (!isFunction(node) || !node.body) return /* @__PURE__ */ new Set();
1017
+ const result2 = new Set(objectDiscriminants(node.body));
1018
+ const visit = (child) => {
1019
+ if (isFunction(child)) return;
1020
+ if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression)) result2.add(key);
1021
+ ts.forEachChild(child, visit);
1022
+ };
1023
+ visit(node.body);
1024
+ return result2;
1025
+ }
1026
+ function shapeNotices(shape, type, checker, node) {
1027
+ const notices = [...shape.synthesisIssues ?? []];
1028
+ const valueType = family(type, checker)?.args[0] ?? type;
1029
+ if ("values" in shape && shape.values.some((value) => new TextEncoder().encode(value.text).byteLength > 2048)) notices.push("synthesized value exceeds 2048 bytes");
1030
+ const omitted = shape.omittedValues ?? 0;
1031
+ if (omitted) notices.push(`${omitted} more values not generated (representative cap)`);
1032
+ if ("errors" in shape) for (const error3 of shape.errors) {
1033
+ if (error3.reason !== void 0) notices.push(`cannot construct ${error3.tag}: ${error3.reason}`);
1034
+ if (new TextEncoder().encode(error3.text).byteLength > 2048) notices.push(`cannot construct ${error3.tag}: synthesized value exceeds 2048 bytes`);
1035
+ }
1036
+ if ("values" in shape && !shape.values.length && !(valueType.flags & ts.TypeFlags.Never) && shape.kind !== "Void") {
1037
+ notices.push(synthesisReason(type, checker, node));
1038
+ }
1039
+ return notices;
1040
+ }
1041
+ function valuesOf(type, checker, location, ancestors = /* @__PURE__ */ new Set(), depth = 0, issues = /* @__PURE__ */ new Set()) {
1042
+ if (depth > 4) {
1043
+ issues.add("synthesis depth limit (4) reached");
1044
+ return [];
847
1045
  }
848
- return `opaque return: ${checker.typeToString(type, node)}`;
1046
+ if (ancestors.has(type) || type.flags & ts.TypeFlags.Never) return [];
1047
+ const values = synthesizeValues(type, checker, location, ancestors, depth, issues);
1048
+ const bounded = values.filter((value) => new TextEncoder().encode(value.text).byteLength <= 2048);
1049
+ if (bounded.length !== values.length) issues.add("synthesized value exceeds 2048 bytes");
1050
+ return bounded;
849
1051
  }
850
- function valuesOf(type, checker, location, depth = 0) {
851
- if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
1052
+ function synthesizeValues(type, checker, location, ancestors, depth, issues) {
1053
+ const descend = (inner) => valuesOf(inner, checker, location, /* @__PURE__ */ new Set([...ancestors, type]), depth + 1, issues);
852
1054
  const value = (text) => ({ text, synthetic: false });
853
1055
  const detected = family(type, checker);
854
1056
  if (detected && (detected.kind === "Option" || detected.kind === "Effect")) {
855
1057
  const api = imports(location.getSourceFile());
856
1058
  const inner = detected.args[0];
857
- const values = inner ? valuesOf(inner, checker, location, depth + 1) : [];
1059
+ const values = inner ? descend(inner) : [];
858
1060
  const wrap = api(detected.kind, detected.kind === "Option" ? "some" : "succeed");
859
1061
  const none = detected.kind === "Option" ? api("Option", "none") : void 0;
860
1062
  return [
@@ -865,13 +1067,19 @@ function valuesOf(type, checker, location, depth = 0) {
865
1067
  if (type.isIntersection()) {
866
1068
  const primitive = type.types.find((member) => member.flags & (ts.TypeFlags.String | ts.TypeFlags.Number));
867
1069
  const brand = type.types.some((member) => member.getProperties().some((prop) => prop.name.includes("Brand")));
868
- if (primitive && brand) return valuesOf(primitive, checker, location, depth + 1).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
1070
+ if (primitive && brand) return descend(primitive).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
869
1071
  }
870
1072
  const symbol = type.getSymbol();
871
1073
  if ((symbol?.name === "ReadonlySet" || symbol?.name === "Set" || symbol?.name === "ReadonlyMap" || symbol?.name === "Map") && symbol.declarations?.some((d) => /\/lib\.es.*\.d\.ts$/.test(d.getSourceFile().fileName))) {
872
1074
  return [value(symbol.name.endsWith("Set") ? "new Set()" : "new Map()")];
873
1075
  }
874
- if (type.isUnion()) return [...type.types].sort((a, b) => a.isNumberLiteral() && b.isNumberLiteral() ? a.value - b.value : checker.typeToString(a).localeCompare(checker.typeToString(b), "en")).flatMap((member) => valuesOf(member, checker, location, depth + 1));
1076
+ if (type.isUnion()) {
1077
+ const members = [...type.types];
1078
+ if (members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)))) {
1079
+ members.sort((a, b) => a.isNumberLiteral() && b.isNumberLiteral() ? a.value - b.value : checker.typeToString(a).localeCompare(checker.typeToString(b), "en"));
1080
+ }
1081
+ return members.flatMap((member) => descend(member));
1082
+ }
875
1083
  if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
876
1084
  if (type.isNumberLiteral()) return [value(String(type.value))];
877
1085
  if (type.flags & ts.TypeFlags.BooleanLiteral) return [value(checker.typeToString(type))];
@@ -883,34 +1091,48 @@ function valuesOf(type, checker, location, depth = 0) {
883
1091
  if (type.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) return [value("undefined")];
884
1092
  if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) return [value("undefined")];
885
1093
  if (checker.isTupleType(type)) {
886
- const elements = checker.getTypeArguments(type).map((t) => valuesOf(t, checker, location, depth + 1)[0]);
1094
+ const elements = checker.getTypeArguments(type).map((t) => descend(t)[0]);
887
1095
  return elements.every((v) => v !== void 0) ? [value(`[${elements.map((v) => v.text).join(", ")}]`)] : [];
888
1096
  }
889
1097
  if (checker.isArrayType(type) || checker.isArrayLikeType(type)) {
890
1098
  const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
891
- const elements = element ? valuesOf(element, checker, location, depth + 1) : [];
1099
+ const elements = element ? descend(element) : [];
892
1100
  return [value("[]"), ...elements.map((v) => ({ text: `[${v.text}]`, synthetic: v.synthetic }))];
893
1101
  }
894
- if (type.flags & ts.TypeFlags.Object && !type.getCallSignatures().length && !type.getConstructSignatures().length) {
1102
+ if ((type.flags & ts.TypeFlags.Object || type.isIntersection()) && !type.getCallSignatures().length && !type.getConstructSignatures().length) {
895
1103
  const fields = [];
896
1104
  for (const prop of type.getProperties()) {
897
1105
  if (prop.flags & ts.SymbolFlags.Optional) continue;
898
1106
  if (!/^[$\w]+$/.test(prop.name)) return [];
899
- const values = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1);
1107
+ const values = descend(checker.getTypeOfSymbolAtLocation(prop, location));
900
1108
  if (!values.length) return [];
901
1109
  fields.push({ name: prop.name, values });
902
1110
  }
903
1111
  const literalFields = fields.filter((field) => {
904
1112
  const prop = type.getProperty(field.name);
1113
+ if (!prop) return false;
905
1114
  const t = checker.getTypeOfSymbolAtLocation(prop, location);
906
1115
  return (t.isUnion() ? t.types : [t]).every((member) => member.isLiteral() || !!(member.flags & ts.TypeFlags.BooleanLiteral));
907
1116
  });
908
- const render = (changed, replacement) => value(`({ ${fields.map((field) => {
909
- const v = (field === changed ? replacement : field.values[0]).text;
910
- return `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
911
- }).join(", ")} })`);
1117
+ const render = (changed, replacement) => {
1118
+ const parts = [];
1119
+ let bytes = 6;
1120
+ for (const field of fields) {
1121
+ const v = (field === changed ? replacement : field.values[0]).text;
1122
+ const part = `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
1123
+ bytes += new TextEncoder().encode(part).byteLength + (parts.length ? 2 : 0);
1124
+ if (bytes > 2048) {
1125
+ issues.add("synthesized value exceeds 2048 bytes");
1126
+ return void 0;
1127
+ }
1128
+ parts.push(part);
1129
+ }
1130
+ return value(`({ ${parts.join(", ")} })`);
1131
+ };
1132
+ const first = render();
1133
+ if (!first) return [];
912
1134
  const anonymous = !type.aliasSymbol && (!type.getSymbol() || ["__type", "__object"].includes(type.getSymbol().name));
913
- return [render(), ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))) : []];
1135
+ return [first, ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))).filter((value2) => value2 !== void 0) : []];
914
1136
  }
915
1137
  return [];
916
1138
  }
@@ -926,30 +1148,70 @@ function makeMutantSource(oracle) {
926
1148
  const discovered = oracle.discover(config);
927
1149
  const notMutated = [...discovered.notMutated];
928
1150
  const mutants = [];
929
- for (const fn8 of discovered.functions) {
930
- const generated = [...generateFunction(fn8)];
931
- if (!generated.length) notMutated.push({ file: fn8.file, functionName: fn8.name, reason: fn8.skipReason ?? `opaque return or no synthesizable value: ${fn8.displayReturnType}` });
1151
+ const failed = /* @__PURE__ */ new Set();
1152
+ const generatedFunctions = discovered.functions.map((fn9) => {
1153
+ try {
1154
+ const iterator = generateFunction(fn9);
1155
+ const generated = [];
1156
+ let step = iterator.next();
1157
+ while (!step.done) {
1158
+ generated.push(step.value);
1159
+ step = iterator.next();
1160
+ }
1161
+ if (step.value) {
1162
+ failed.add(fn9);
1163
+ notMutated.push({ file: fn9.file, functionName: fn9.name, span: fn9.span, reason: step.value });
1164
+ return { fn: fn9, generated: [] };
1165
+ }
1166
+ return { fn: fn9, generated };
1167
+ } catch (error3) {
1168
+ failed.add(fn9);
1169
+ notMutated.push({
1170
+ file: fn9.file,
1171
+ functionName: fn9.name,
1172
+ span: fn9.span,
1173
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
1174
+ });
1175
+ return { fn: fn9, generated: [] };
1176
+ }
1177
+ });
1178
+ for (const { fn: fn9, generated } of generatedFunctions) {
1179
+ if (failed.has(fn9)) continue;
1180
+ {
1181
+ const reasons = [...fn9.notices ?? []];
1182
+ if (!generated.length && !reasons.length) reasons.push(fn9.skipReason ?? `return not synthesizable (type ${fn9.displayReturnType})`);
1183
+ const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file === fn9.file && inner.startOffset > fn9.startOffset && inner.endOffset < fn9.endOffset && generated2.length > 0);
1184
+ if (innerMutated && !generated.length) {
1185
+ for (let i = 0; i < reasons.length; i++) if (reasons[i].startsWith("return not synthesizable")) reasons[i] += "; inner functions mutated";
1186
+ }
1187
+ if (reasons.length) notMutated.push({ file: fn9.file, functionName: fn9.name, span: fn9.span, reason: [...new Set(reasons)].join("; ") });
1188
+ }
932
1189
  mutants.push(...generated);
933
1190
  }
934
- return { mutants, notMutated };
1191
+ return { mutants, notMutated: [...new Map(notMutated.map((item) => [JSON.stringify(item), item])).values()] };
935
1192
  },
936
- catch: (error2) => loadError(config.tsconfig, error2)
1193
+ catch: (error3) => {
1194
+ if (Schema4.is(ProgramLoadError)(error3)) return error3;
1195
+ throw error3;
1196
+ }
937
1197
  });
938
1198
  return {
939
1199
  notMutated: (config) => discover(config).pipe(Effect.map((result2) => result2.notMutated)),
940
1200
  generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result2) => Stream.fromIterable(result2.mutants)))),
941
- checkViable: (mutant) => Effect.try({
942
- try: () => oracle.checkViable(mutant),
943
- catch: (error2) => loadError("", error2)
1201
+ checkViable: (mutant) => Effect.sync(() => {
1202
+ try {
1203
+ return oracle.checkViable(mutant);
1204
+ } catch (error3) {
1205
+ return { viable: false, diagnostics: [], analysisFailed: {
1206
+ file: mutant.file,
1207
+ functionName: mutant.functionName,
1208
+ span: mutant.span,
1209
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
1210
+ } };
1211
+ }
944
1212
  })
945
1213
  };
946
1214
  }
947
- function loadError(tsconfig, error2) {
948
- return Schema4.is(ProgramLoadError)(error2) ? error2 : new ProgramLoadError({
949
- tsconfig,
950
- diagnostics: [error2 instanceof Error ? error2.message : String(error2)]
951
- });
952
- }
953
1215
 
954
1216
  // packages/runner/src/Scratch.ts
955
1217
  import * as Effect2 from "effect/Effect";
@@ -959,7 +1221,7 @@ import * as Path from "effect/Path";
959
1221
  var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
960
1222
  const fs = yield* FileSystem.FileSystem;
961
1223
  const path = yield* Path.Path;
962
- const failure = (operation, location, error2) => new ScratchError({ operation, path: location, message: error2.message });
1224
+ const failure = (operation, location, error3) => new ScratchError({ operation, path: location, message: error3.message });
963
1225
  return Scratch.of({
964
1226
  acquire: Effect2.fn("Scratch.acquire")(function* (root) {
965
1227
  const source = path.resolve(root);
@@ -976,7 +1238,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
976
1238
  }
977
1239
  const temp = yield* Effect2.acquireRelease(
978
1240
  fs.makeTempDirectory({ prefix: "mutant-cafe-" }).pipe(
979
- Effect2.mapError((error2) => failure("create", source, error2))
1241
+ Effect2.mapError((error3) => failure("create", source, error3))
980
1242
  ),
981
1243
  (dir2) => fs.remove(dir2, { recursive: true }).pipe(Effect2.orDie)
982
1244
  );
@@ -1018,10 +1280,10 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
1018
1280
  } else if (info.type === "File") {
1019
1281
  yield* fs.copyFile(from, to);
1020
1282
  }
1021
- }).pipe(Effect2.mapError((error2) => failure("copy", from, error2)));
1283
+ }).pipe(Effect2.mapError((error3) => failure("copy", from, error3)));
1022
1284
  yield* copy(copyRoot, temp, []);
1023
1285
  const packageRoot = yield* fs.realPath(path.join(temp, path.relative(copyRoot, source))).pipe(
1024
- Effect2.mapError((error2) => failure("resolve", source, error2))
1286
+ Effect2.mapError((error3) => failure("resolve", source, error3))
1025
1287
  );
1026
1288
  const originals = /* @__PURE__ */ new Map();
1027
1289
  const target = (mutant) => Effect2.gen(function* () {
@@ -1031,7 +1293,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
1031
1293
  if (rel === "" || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel) || rel.split(path.sep).includes("node_modules")) {
1032
1294
  return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file must be inside the copied source tree" }));
1033
1295
  }
1034
- const real = yield* fs.realPath(location).pipe(Effect2.mapError((error2) => failure("resolve", location, error2)));
1296
+ const real = yield* fs.realPath(location).pipe(Effect2.mapError((error3) => failure("resolve", location, error3)));
1035
1297
  const realRelative = path.relative(packageRoot, real);
1036
1298
  if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
1037
1299
  return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file resolves outside the scratch package" }));
@@ -1050,7 +1312,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
1050
1312
  return yield* Effect2.fail(new ScratchError({ operation: "apply", path: location, message: "Replacement offsets are outside the file" }));
1051
1313
  }
1052
1314
  yield* fs.writeFileString(location, original.slice(0, startOffset) + text + original.slice(endOffset));
1053
- }, (effect5, mutant) => effect5.pipe(Effect2.mapError((error2) => failure("apply", mutant.file, error2)))),
1315
+ }, (effect5, mutant) => effect5.pipe(Effect2.mapError((error3) => failure("apply", mutant.file, error3)))),
1054
1316
  revert: Effect2.fn("Scratch.revert")(function* (mutant) {
1055
1317
  const location = yield* target(mutant);
1056
1318
  const bytes = originals.get(location);
@@ -1058,10 +1320,10 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
1058
1320
  yield* fs.writeFile(location, bytes);
1059
1321
  originals.delete(location);
1060
1322
  }
1061
- }, (effect5, mutant) => effect5.pipe(Effect2.mapError((error2) => failure("revert", mutant.file, error2))))
1323
+ }, (effect5, mutant) => effect5.pipe(Effect2.mapError((error3) => failure("revert", mutant.file, error3))))
1062
1324
  };
1063
1325
  return dir;
1064
- }, (effect5, root) => effect5.pipe(Effect2.mapError((error2) => error2._tag === "ScratchError" ? error2 : failure("acquire", root, error2))))
1326
+ }, (effect5, root) => effect5.pipe(Effect2.mapError((error3) => error3._tag === "ScratchError" ? error3 : failure("acquire", root, error3))))
1065
1327
  });
1066
1328
  }));
1067
1329
 
@@ -1253,7 +1515,7 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1253
1515
  const path = yield* Path3.Path;
1254
1516
  const execute = Effect4.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
1255
1517
  const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
1256
- Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) }))
1518
+ Effect4.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) }))
1257
1519
  );
1258
1520
  const reporter = path.join(reporterDir, "reporter.mjs");
1259
1521
  const marker = `mutant-cafe:${path.basename(reporterDir)}:`;
@@ -1264,7 +1526,7 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1264
1526
  onTestModuleCollected() { console.log(${JSON.stringify(marker + "collected")}); }
1265
1527
  onTestCaseResult(test) { if (test.result().state === "failed") console.log(${JSON.stringify(marker + "failed")}); }
1266
1528
  onTestRunEnd() { if (this.files === 0) console.log(${JSON.stringify(marker + "empty")}); }
1267
- }`).pipe(Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) })));
1529
+ }`).pipe(Effect4.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
1268
1530
  const command = [
1269
1531
  "npx",
1270
1532
  "--no",
@@ -1278,7 +1540,7 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1278
1540
  "--no-cache",
1279
1541
  "--no-fsModuleCache"
1280
1542
  ];
1281
- if (timeoutMs === void 0) yield* Console.log(`Baseline command: ${command.join(" ")} (cwd: ${dir.path})`);
1543
+ if (timeoutMs === void 0) yield* Console.error(`Baseline command: ${command.join(" ")} (cwd: ${dir.path})`);
1282
1544
  const started = yield* Clock.currentTimeMillis;
1283
1545
  const chunks = [];
1284
1546
  let exitCode = 1;
@@ -1301,13 +1563,13 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1301
1563
  const status = yield* (timeoutMs === void 0 ? child : child.pipe(
1302
1564
  Effect4.timeout(timeoutMs),
1303
1565
  Effect4.catchTag("TimeoutError", () => Effect4.succeed("timedOut"))
1304
- )).pipe(Effect4.mapError((error2) => new TestSpawnError({ command, message: error2.message })));
1566
+ )).pipe(Effect4.mapError((error3) => new TestSpawnError({ command, message: error3.message })));
1305
1567
  const ended = yield* Clock.currentTimeMillis;
1306
1568
  const output = chunks.join("");
1307
1569
  const failed = output.includes(marker + "failed");
1308
1570
  const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
1309
1571
  const selected = selection === void 0 ? [] : yield* Schema6.decodeEffect(Schema6.fromJsonString(Schema6.Array(Schema6.String)))(selection).pipe(
1310
- Effect4.mapError((error2) => new TestSpawnError({ command, message: `Cannot decode Vitest selected files: ${String(error2)}` }))
1572
+ Effect4.mapError((error3) => new TestSpawnError({ command, message: `Cannot decode Vitest selected files: ${String(error3)}` }))
1311
1573
  );
1312
1574
  const run2 = {
1313
1575
  status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
@@ -1321,7 +1583,7 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1321
1583
  }, Effect4.scoped);
1322
1584
  return TestRunner.of({
1323
1585
  baseline: Effect4.fn("TestRunner.baseline")(function* (dir, tsconfig) {
1324
- const unreliable = yield* preflight(dir.path, tsconfig).pipe(Effect4.provideService(ChildProcessSpawner3.ChildProcessSpawner, spawner), Effect4.catch((error2) => Effect4.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error2)}` }])));
1586
+ const unreliable = yield* preflight(dir.path, tsconfig).pipe(Effect4.provideService(ChildProcessSpawner3.ChildProcessSpawner, spawner), Effect4.catch((error3) => Effect4.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error3)}` }])));
1325
1587
  for (const issue of unreliable) yield* Console.warn(`Warning (${issue.kind}): ${issue.reason}`);
1326
1588
  if (unreliable.some((issue) => issue.kind === "runner")) {
1327
1589
  const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
@@ -1380,6 +1642,7 @@ var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
1380
1642
  baseline: state2.baseline,
1381
1643
  timeoutMs: state2.timeoutMs,
1382
1644
  results: state2.results,
1645
+ notMutated: state2.notMutated,
1383
1646
  ...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${state2.failure.command.join(" ")}
1384
1647
  ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1385
1648
  });
@@ -1418,6 +1681,10 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1418
1681
  yield* Stream3.fromIterable(input.state.pending).pipe(
1419
1682
  Stream3.mapEffect((mutant) => Effect5.scoped(Effect5.gen(function* () {
1420
1683
  const viability = yield* source.checkViable(mutant);
1684
+ if (viability.analysisFailed) {
1685
+ yield* input.skip(viability.analysisFailed);
1686
+ return;
1687
+ }
1421
1688
  if (!viability.viable) {
1422
1689
  const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
1423
1690
  yield* input.record(result3);
@@ -1461,7 +1728,7 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1461
1728
  const machine = setupEffect({
1462
1729
  schemas: {
1463
1730
  context: types(),
1464
- events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }) }
1731
+ events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }), SKIP: Schema7.Struct({ entry: NotMutated }) }
1465
1732
  },
1466
1733
  actors: { copying, baselining, generating, testing, reporting }
1467
1734
  }).createMachine({
@@ -1472,12 +1739,14 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1472
1739
  pool: void 0,
1473
1740
  pending: [],
1474
1741
  results: [],
1475
- reported: false
1742
+ reported: false,
1743
+ notMutated: []
1476
1744
  },
1477
1745
  output: ({ context }) => context,
1478
- initial: "copying",
1746
+ initial: "generating",
1479
1747
  on: {
1480
1748
  CANCEL: { target: ".interrupted" },
1749
+ SKIP: ({ context, event }) => ({ context: { ...context, notMutated: [...new Map([...context.notMutated, event.entry].map((entry) => [JSON.stringify(entry), entry])).values()] } }),
1481
1750
  RESULT: ({ context, event }) => ({ context: { ...context, results: [...context.results, event.result] } })
1482
1751
  },
1483
1752
  states: {
@@ -1485,20 +1754,21 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1485
1754
  baseline: { invoke: {
1486
1755
  src: "baselining",
1487
1756
  input: ({ context }) => context.pool,
1488
- onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
1757
+ onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "testing", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
1489
1758
  ...context,
1490
1759
  failure: event.output.failure,
1491
1760
  baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
1492
1761
  } }
1493
1762
  } },
1494
- generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "testing", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
1763
+ generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: event.output.success.length ? "copying" : "reporting", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
1495
1764
  testing: { invoke: {
1496
1765
  src: "testing",
1497
1766
  input: ({ context, self }) => ({
1498
1767
  state: context,
1499
1768
  // Queue completion before progress can trigger CANCEL. The parent's
1500
1769
  // FIFO mailbox commits this result before handling that cancellation.
1501
- record: (result2) => send(self, { type: "RESULT", result: result2 })
1770
+ record: (result2) => send(self, { type: "RESULT", result: result2 }),
1771
+ skip: (entry) => send(self, { type: "SKIP", entry })
1502
1772
  }),
1503
1773
  onDone: ({ context, event }) => ({ target: "reporting", context: {
1504
1774
  ...context,
@@ -1539,19 +1809,19 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1539
1809
  }, Effect5.scoped);
1540
1810
 
1541
1811
  // packages/cli/src/bin.ts
1542
- import * as Effect9 from "effect/Effect";
1812
+ import * as Effect10 from "effect/Effect";
1543
1813
  import * as Layer5 from "effect/Layer";
1544
- import * as Stream6 from "effect/Stream";
1814
+ import * as Stream7 from "effect/Stream";
1545
1815
 
1546
1816
  // packages/cli/src/Command.ts
1547
1817
  import * as Console3 from "effect/Console";
1548
- import * as Effect8 from "effect/Effect";
1549
- import * as FileSystem9 from "effect/FileSystem";
1818
+ import * as Effect9 from "effect/Effect";
1819
+ import * as FileSystem11 from "effect/FileSystem";
1550
1820
  import * as Option from "effect/Option";
1551
- import * as Path11 from "effect/Path";
1821
+ import * as Path13 from "effect/Path";
1552
1822
  import * as Ref from "effect/Ref";
1553
- import * as Schema10 from "effect/Schema";
1554
- import * as Stream5 from "effect/Stream";
1823
+ import * as Schema11 from "effect/Schema";
1824
+ import * as Stream6 from "effect/Stream";
1555
1825
  import * as Command from "effect/cli/Command";
1556
1826
  import * as Flag from "effect/cli/Flag";
1557
1827
 
@@ -1643,13 +1913,13 @@ var parseDiff = (text, path) => Effect6.try({
1643
1913
  if (!sawFile) fail3("No unified diff found");
1644
1914
  return patches;
1645
1915
  },
1646
- catch: (error2) => Schema8.is(DiffParseError)(error2) ? error2 : new DiffParseError({ path, message: String(error2) })
1916
+ catch: (error3) => Schema8.is(DiffParseError)(error3) ? error3 : new DiffParseError({ path, message: String(error3) })
1647
1917
  });
1648
1918
  var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
1649
1919
  const fs = yield* FileSystem5.FileSystem;
1650
1920
  const path = yield* Path7.Path;
1651
1921
  const diffPath = path.resolve(options.root, options.diffPath);
1652
- const text = yield* fs.readFileString(diffPath).pipe(Effect6.mapError((error2) => new DiffParseError({ path: diffPath, message: String(error2) })));
1922
+ const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(Effect6.mapError((error3) => new DiffParseError({ path: diffPath, message: String(error3) }))));
1653
1923
  const patches = yield* parseDiff(text, diffPath);
1654
1924
  const gitRoot = yield* Effect6.scoped(Effect6.gen(function* () {
1655
1925
  const handle = yield* ChildProcess3.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
@@ -1669,7 +1939,7 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
1669
1939
  return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
1670
1940
  }
1671
1941
  if (!(yield* fs.exists(candidate))) continue;
1672
- const current = yield* fs.readFileString(candidate).pipe(Effect6.mapError((error2) => new DiffMismatch({ path: patch.file, message: String(error2) })));
1942
+ const current = yield* fs.readFileString(candidate).pipe(Effect6.mapError((error3) => new DiffMismatch({ path: patch.file, message: String(error3) })));
1673
1943
  const lines2 = current.split("\n");
1674
1944
  const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
1675
1945
  if (patch.lines.every((line) => {
@@ -1697,8 +1967,8 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
1697
1967
 
1698
1968
  // packages/cli/src/ExitCode.ts
1699
1969
  var reportExitCode = (report) => report.results.some((result2) => result2.outcome === "missed") ? 2 : report.results.some((result2) => result2.outcome === "unreliable") ? 7 : report.results.some((result2) => result2.outcome === "untested") ? 2 : report.results.some((result2) => result2.outcome === "timeout") ? 3 : 0;
1700
- var errorExitCode = (error2) => {
1701
- switch (error2._tag) {
1970
+ var errorExitCode = (error3) => {
1971
+ switch (error3._tag) {
1702
1972
  case "BaselineFailed":
1703
1973
  return 4;
1704
1974
  case "DiffMismatch":
@@ -1815,6 +2085,28 @@ var unifiedDiff = (original, modified, file) => {
1815
2085
  return [...output, ""].join("\n");
1816
2086
  };
1817
2087
 
2088
+ // packages/cli/src/Summary.ts
2089
+ var outcomeNames = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
2090
+ var countsLine = (report, notMutated) => `${report.selected ?? report.results.length} selected, ${report.run ?? report.results.length} run, ${report.budgetSkipped ?? 0} budget-skipped; ` + outcomeNames.map((outcome) => `${report.results.filter((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${notMutated} not mutated`;
2091
+ var cell = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\\", "\\\\").replaceAll("|", "\\|").replaceAll("`", "&#96;").replace(/[\r\n]+/g, " ");
2092
+ var markdownSummary = (options) => {
2093
+ const { report, path } = options;
2094
+ const rows = report.results.filter((result2) => result2.outcome === "missed" || result2.outcome === "timeout" || result2.outcome === "untested" || result2.outcome === "unreliable");
2095
+ const exit = report.failure?.startsWith("BaselineFailed") ? 4 : reportExitCode(report);
2096
+ return [
2097
+ options.marker,
2098
+ countsLine(report, options.notMutated),
2099
+ "",
2100
+ ...report.failure === void 0 ? [] : [`Failure: ${cell(report.failure)}`, ""],
2101
+ options.advisory ? `Advisory: would exit ${exit} without --advisory.` : `Exit code: ${exit}.`,
2102
+ "",
2103
+ ...rows.length ? ["| File:line | Function | Description | Outcome |", "| --- | --- | --- | --- |"] : report.failure === void 0 ? ["No actionable mutants."] : [],
2104
+ ...rows.slice(0, 50).map(({ mutant, outcome }) => `| ${cell(path.relative(options.gitRoot, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))}:${mutant.span.start.line} | ${cell(mutant.functionName)} | ${cell(mutant.description)} | ${outcome} |`),
2105
+ ...rows.length > 50 ? ["", `and ${rows.length - 50} more`] : [],
2106
+ ""
2107
+ ].join("\n");
2108
+ };
2109
+
1818
2110
  // packages/cli/src/Reporter.ts
1819
2111
  var mutantLine = (mutant, root, path) => `${path.relative(root, path.resolve(root, mutant.file))}:${mutant.span.start.line}:${mutant.span.start.column}: ${mutant.description.replace(mutant.returnType, shortType(mutant.displayReturnType ?? mutant.returnType))} [${mutant.id}]`;
1820
2112
  var shortType = (text) => {
@@ -1836,7 +2128,7 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1836
2128
  const results = [];
1837
2129
  let pendingError;
1838
2130
  let summarized = false;
1839
- const writeError = (error2) => new ReportWriteError({ path: dir, message: String(error2) });
2131
+ const writeError = (error3) => new ReportWriteError({ path: dir, message: String(error3) });
1840
2132
  const ids = /* @__PURE__ */ new Set();
1841
2133
  for (const mutant of options.mutants) {
1842
2134
  if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
@@ -1860,7 +2152,7 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1860
2152
  }).pipe(Effect7.mapError(writeError));
1861
2153
  const encodedMutants = yield* Schema9.encodeEffect(Schema9.fromJsonString(Schema9.Array(Mutant)))(options.mutants).pipe(Effect7.mapError(writeError));
1862
2154
  yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect7.mapError(writeError));
1863
- yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}: ${item.functionName}: ${item.reason}
2155
+ yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
1864
2156
  `).join("")).pipe(Effect7.mapError(writeError));
1865
2157
  yield* Effect7.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect7.mapError(writeError));
1866
2158
  for (const mutant of options.mutants) {
@@ -1874,21 +2166,31 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1874
2166
  const service = Reporter.of({
1875
2167
  progress: (result2) => semaphore.withPermit(Effect7.gen(function* () {
1876
2168
  results.push(result2);
1877
- yield* Console2.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
2169
+ if (!options.markdown?.stdout) yield* Console2.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
1878
2170
  yield* Effect7.gen(function* () {
1879
2171
  if (!ids.has(result2.mutant.id)) return yield* writeError("Progress result does not belong to this report");
1880
2172
  yield* writeLists(results);
1881
2173
  yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2));
1882
- }).pipe(Effect7.catch((error2) => Effect7.gen(function* () {
2174
+ }).pipe(Effect7.catch((error3) => Effect7.gen(function* () {
1883
2175
  if (pendingError === void 0) {
1884
- pendingError = writeError(error2);
2176
+ pendingError = writeError(error3);
1885
2177
  yield* Console2.warn(`Report write failed: ${pendingError.message}`);
1886
2178
  }
1887
2179
  })));
1888
2180
  })),
1889
2181
  write: (report) => semaphore.withPermit(Effect7.gen(function* () {
1890
2182
  if (pendingError !== void 0) return yield* pendingError;
1891
- const encoded = yield* jsonReport(report).pipe(Effect7.mapError(writeError));
2183
+ const notMutated = [...new Map([...options.notMutated ?? [], ...report.notMutated ?? []].map((item) => [JSON.stringify(item), item])).values()];
2184
+ yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), notMutated.map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
2185
+ `).join("")).pipe(Effect7.mapError(writeError));
2186
+ const counted = {
2187
+ ...report,
2188
+ notMutated,
2189
+ selected: options.selected ?? options.mutants.length,
2190
+ run: report.results.length,
2191
+ budgetSkipped: options.budgetSkipped ?? 0
2192
+ };
2193
+ const encoded = yield* jsonReport(counted).pipe(Effect7.mapError(writeError));
1892
2194
  yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect7.mapError(writeError));
1893
2195
  yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect7.mapError(writeError));
1894
2196
  yield* writeLists(report.results).pipe(Effect7.mapError(writeError));
@@ -1896,22 +2198,65 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1896
2198
  if (!ids.has(result2.mutant.id)) return yield* writeError("Final result does not belong to this report");
1897
2199
  yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect7.mapError(writeError));
1898
2200
  }
2201
+ if (options.markdown !== void 0) {
2202
+ const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: notMutated.length });
2203
+ for (const file of new Set(options.markdown.files)) {
2204
+ yield* fs.writeFileString(file, markdown).pipe(Effect7.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) })));
2205
+ }
2206
+ if (!summarized && options.markdown.stdout) yield* Console2.log(markdown);
2207
+ }
1899
2208
  if (summarized) return;
1900
2209
  summarized = true;
1901
2210
  if (report.results.some((result2) => result2.outcome === "unreliable")) yield* Console2.warn("Unreliable: the configured Vitest run cannot see all tests. See unreliable.txt and per-mutant diagnostics; these are not missed mutants.");
1902
2211
  const elapsed = (yield* Clock2.currentTimeMillis) - started;
1903
- yield* Console2.log(outcomes.map((outcome) => `${report.results.filter((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${options.notMutated?.length ?? 0} not mutated; ${(elapsed / 1e3).toFixed(2)}s`);
2212
+ if (!options.markdown?.stdout) yield* Console2.log(countsLine(counted, notMutated.length) + `; ${(elapsed / 1e3).toFixed(2)}s`);
2213
+ if (options.markdown === void 0 && report.failure !== void 0) yield* Console2.warn(report.failure);
1904
2214
  }))
1905
2215
  });
1906
2216
  return service;
1907
2217
  });
1908
2218
 
1909
- // packages/cli/src/Command.ts
2219
+ // packages/cli/src/Git.ts
2220
+ import * as Effect8 from "effect/Effect";
2221
+ import * as FileSystem9 from "effect/FileSystem";
2222
+ import * as Path11 from "effect/Path";
2223
+ import * as Schema10 from "effect/Schema";
2224
+ import * as Stream5 from "effect/Stream";
2225
+ import * as ChildProcess4 from "effect/process/ChildProcess";
1910
2226
  var UsageError = class extends Schema10.TaggedError()("UsageError", { message: Schema10.String }) {
1911
2227
  };
2228
+ var git = Effect8.fn("git")(function* (root, args) {
2229
+ const command = `git ${args.join(" ")}`;
2230
+ return yield* Effect8.scoped(Effect8.gen(function* () {
2231
+ const handle = yield* ChildProcess4.make("git", args, { cwd: root });
2232
+ const [stdout, stderr, code] = yield* Effect8.all([
2233
+ Stream5.mkString(Stream5.decodeText(handle.stdout)),
2234
+ Stream5.mkString(Stream5.decodeText(handle.stderr)),
2235
+ handle.exitCode
2236
+ ], { concurrency: "unbounded" });
2237
+ if (Number(code) !== 0) return yield* new UsageError({ message: `${command}:
2238
+ ${stderr}` });
2239
+ return stdout;
2240
+ })).pipe(Effect8.mapError((error3) => error3._tag === "UsageError" ? error3 : new UsageError({ message: `${command}: ${String(error3)}` })));
2241
+ });
2242
+ var repositoryRoot = Effect8.fn("repositoryRoot")(function* (root) {
2243
+ const path = yield* Path11.Path;
2244
+ const fs = yield* FileSystem9.FileSystem;
2245
+ const top = (yield* git(root, ["rev-parse", "--show-toplevel"])).trim();
2246
+ const physical = yield* fs.realPath(root).pipe(Effect8.mapError((error3) => new UsageError({ message: String(error3) })));
2247
+ return path.resolve(root, path.relative(physical, top));
2248
+ });
2249
+
2250
+ // packages/cli/src/Command.ts
1912
2251
  var flags = {
1913
2252
  list: Flag.Boolean("list").pipe(Flag.withDefault(false), Flag.withDescription("List mutants and skipped function count without running tests")),
1914
2253
  inDiff: Flag.String("in-diff").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping this unified diff")),
2254
+ inDiffRange: Flag.String("in-diff-range").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping git diff A...B or A..B; exclusive with --in-diff")),
2255
+ maxMutants: Flag.Int("max-mutants").pipe(Flag.optional, Flag.withDescription("Keep first N selected mutants ordered by repository path, line, column, id; N >= 0")),
2256
+ format: Flag.String("format").pipe(Flag.withDefault("text"), Flag.withDescription("Output format: text (default), json (--list only), or github (Markdown and GITHUB_STEP_SUMMARY)")),
2257
+ summaryMd: Flag.String("summary-md").pipe(Flag.optional, Flag.withDescription("Write Markdown summary to this file")),
2258
+ summaryMarker: Flag.String("summary-marker").pipe(Flag.withDefault("<!-- mutant.cafe -->"), Flag.withDescription("Override the first-line sticky-comment marker")),
2259
+ advisory: Flag.Boolean("advisory").pipe(Flag.withDefault(false), Flag.withDescription("Exit 0 for outcomes and baseline failure; keep usage/internal errors")),
1915
2260
  include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
1916
2261
  exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
1917
2262
  exportedOnly: Flag.Boolean("exported-only").pipe(Flag.withDefault(false), Flag.withDescription("Only exported binding paths, returned curried functions and Layer service methods; exclude local helpers")),
@@ -1922,18 +2267,30 @@ var flags = {
1922
2267
  output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
1923
2268
  tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
1924
2269
  };
1925
- var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect8.gen(function* () {
1926
- const fs = yield* FileSystem9.FileSystem;
1927
- const path = yield* Path11.Path;
2270
+ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect9.gen(function* () {
2271
+ const fs = yield* FileSystem11.FileSystem;
2272
+ const path = yield* Path13.Path;
1928
2273
  const root = path.resolve(options.root);
2274
+ const range = Option.getOrUndefined(input.inDiffRange);
2275
+ const inDiff = Option.getOrUndefined(input.inDiff);
2276
+ const maxMutants = Option.getOrUndefined(input.maxMutants);
2277
+ const summaryMd = Option.getOrUndefined(input.summaryMd);
2278
+ if (range !== void 0 && inDiff !== void 0) return yield* new UsageError({ message: "--in-diff-range and --in-diff are mutually exclusive" });
2279
+ if (range !== void 0 && (!/^[^\s.][^\s]*\.{2,3}[^\s.][^\s]*$/.test(range) || range.startsWith("-") || range.includes("...."))) {
2280
+ return yield* new UsageError({ message: "--in-diff-range expects A...B or A..B" });
2281
+ }
2282
+ if (maxMutants !== void 0 && (!Number.isSafeInteger(maxMutants) || maxMutants < 0)) return yield* new UsageError({ message: "--max-mutants must be a nonnegative safe integer" });
2283
+ if (!["text", "json", "github"].includes(input.format) || input.format === "json" && !input.list) return yield* new UsageError({ message: "--format expects text, github, or json with --list" });
2284
+ if (/[\r\n]/.test(input.summaryMarker)) return yield* new UsageError({ message: "--summary-marker must be one line" });
2285
+ const gitRoot = range !== void 0 ? yield* repositoryRoot(root) : yield* repositoryRoot(root).pipe(Effect9.catch(() => Effect9.succeed(root)));
2286
+ const diffText = range === void 0 ? void 0 : yield* git(gitRoot, ["diff", "--no-ext-diff", "--no-color", range, "--"]);
1929
2287
  const configPath = path.join(root, "mutants.config.json");
1930
2288
  const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
1931
- Effect8.flatMap(Schema10.decodeEffect(Schema10.fromJsonString(ConfigFile))),
1932
- Effect8.mapError((error2) => new UsageError({ message: `Invalid mutants.config.json: ${String(error2)}` }))
2289
+ Effect9.flatMap(Schema11.decodeEffect(Schema11.fromJsonString(ConfigFile))),
2290
+ Effect9.mapError((error3) => new UsageError({ message: `Invalid mutants.config.json: ${String(error3)}` }))
1933
2291
  ) : {};
1934
2292
  const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
1935
- const inDiff = Option.getOrUndefined(input.inDiff);
1936
- const config = yield* Schema10.decodeEffect(RunConfig)({
2293
+ const config = yield* Schema11.decodeEffect(RunConfig)({
1937
2294
  root,
1938
2295
  tsconfig: input.tsconfig,
1939
2296
  exportedOnly: input.exportedOnly,
@@ -1947,45 +2304,112 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
1947
2304
  minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
1948
2305
  neverTimeoutMs: 1e3,
1949
2306
  outDir: input.output
1950
- }).pipe(Effect8.mapError((error2) => new UsageError({ message: String(error2) })));
2307
+ }).pipe(Effect9.mapError((error3) => new UsageError({ message: String(error3) })));
1951
2308
  if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
1952
2309
  return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
1953
2310
  }
1954
2311
  const source = yield* MutantSource;
1955
- const generated = yield* Stream5.runCollect(source.generate(config)).pipe(
1956
- Effect8.mapError((error2) => error2.reason === "selection" ? new UsageError({ message: error2.diagnostics.join("\n") }) : error2)
2312
+ const generated = yield* Stream6.runCollect(source.generate(config)).pipe(
2313
+ Effect9.mapError((error3) => error3.reason === "selection" ? new UsageError({ message: error3.diagnostics.join("\n") }) : error3)
1957
2314
  );
1958
2315
  const skipped2 = yield* source.notMutated(config);
1959
- const selected = inDiff === void 0 ? { mutants: generated, notMutated: skipped2 } : yield* selectDiffScope({ root, diffPath: inDiff, mutants: generated, notMutated: skipped2 });
1960
- const { mutants, notMutated } = selected;
2316
+ const selected = inDiff === void 0 && diffText === void 0 ? { mutants: generated, notMutated: skipped2 } : yield* selectDiffScope({ root, diffPath: inDiff ?? `git diff ${range}`, ...diffText === void 0 ? {} : { diffText }, mutants: generated, notMutated: skipped2 });
2317
+ const relative2 = (mutant) => path.relative(gitRoot, path.resolve(root, mutant.file)).replaceAll("\\", "/");
2318
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
2319
+ const ordered = [...selected.mutants].sort((a, b) => compare(relative2(a), relative2(b)) || a.span.start.line - b.span.start.line || a.span.start.column - b.span.start.column || compare(a.id, b.id));
2320
+ const mutants = ordered.slice(0, maxMutants);
2321
+ const notMutated = selected.notMutated;
2322
+ const counts = { selected: ordered.length, run: 0, budgetSkipped: ordered.length - mutants.length };
2323
+ if (mutants.length === 0) {
2324
+ const cause = ordered.length > 0 ? "budget" : range !== void 0 ? "range" : inDiff !== void 0 || diffText !== void 0 ? "diff" : config.functionFilter.length || config.exportedOnly ? "filter" : "file selection";
2325
+ yield* Console3.error(`0 mutants selected (${counts.selected} before budget); cause: ${cause}. Baseline skipped.`);
2326
+ }
2327
+ const markdown = input.format === "github" || summaryMd !== void 0 ? {
2328
+ gitRoot,
2329
+ marker: input.summaryMarker,
2330
+ advisory: input.advisory,
2331
+ stdout: input.format === "github",
2332
+ files: [
2333
+ ...summaryMd === void 0 ? [] : [path.resolve(root, summaryMd)],
2334
+ ...input.format === "github" && process.env.GITHUB_STEP_SUMMARY ? [process.env.GITHUB_STEP_SUMMARY] : []
2335
+ ]
2336
+ } : void 0;
2337
+ if (input.list && markdown !== void 0) {
2338
+ const text = markdownSummary({
2339
+ ...markdown,
2340
+ root,
2341
+ path,
2342
+ notMutated: notMutated.length,
2343
+ report: { schemaVersion: 2, tool: "mutant.cafe", root, baseline: { durationMs: 0, testCommand: [] }, timeoutMs: 0, results: [], ...counts }
2344
+ });
2345
+ for (const file of new Set(markdown.files)) yield* fs.writeFileString(file, text).pipe(
2346
+ Effect9.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) }))
2347
+ );
2348
+ if (markdown.stdout) {
2349
+ yield* Console3.log(text);
2350
+ if (options.onExit !== void 0) yield* options.onExit(0);
2351
+ return;
2352
+ }
2353
+ }
2354
+ if (input.list && input.format === "json") {
2355
+ yield* Console3.log(yield* Schema11.encodeEffect(Schema11.fromJsonString(MutantList))({ schemaVersion: 2, tool: "mutant.cafe", mutants, notMutated, counts }));
2356
+ if (options.onExit !== void 0) yield* options.onExit(0);
2357
+ return;
2358
+ }
1961
2359
  if (input.list) {
1962
2360
  for (const mutant of mutants) yield* Console3.log(mutantLine(mutant, config.root, path));
1963
- const counts = /* @__PURE__ */ new Map();
2361
+ const perFile = /* @__PURE__ */ new Map();
1964
2362
  for (const mutant of mutants) {
1965
2363
  const file = path.relative(root, path.resolve(root, mutant.file));
1966
- counts.set(file, (counts.get(file) ?? 0) + 1);
2364
+ perFile.set(file, (perFile.get(file) ?? 0) + 1);
1967
2365
  }
1968
- for (const [file, count] of [...counts].sort(([a], [b]) => a.localeCompare(b))) yield* Console3.log(`${file}: ${count} mutants`);
1969
- yield* Console3.log(`${mutants.length} mutants total; ${notMutated.length} not mutated`);
2366
+ for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield* Console3.log(`${file}: ${count} mutants`);
2367
+ yield* Console3.log(`${mutants.length} mutants total; ${notMutated.length} not mutated; ${counts.selected} selected, 0 run, ${counts.budgetSkipped} budget-skipped`);
1970
2368
  if (options.onExit !== void 0) yield* options.onExit(0);
1971
2369
  return;
1972
2370
  }
1973
- const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated });
1974
- const report = yield* options.run(config, mutants).pipe(Effect8.provideService(Reporter, reporter));
2371
+ const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated, selected: counts.selected, budgetSkipped: counts.budgetSkipped, ...markdown === void 0 ? {} : { markdown } });
2372
+ const report = yield* (mutants.length === 0 ? Effect9.succeed({
2373
+ schemaVersion: 2,
2374
+ tool: "mutant.cafe",
2375
+ root,
2376
+ baseline: { durationMs: 0, testCommand: [] },
2377
+ timeoutMs: 0,
2378
+ results: []
2379
+ }) : options.run(config, mutants)).pipe(
2380
+ Effect9.provideService(Reporter, reporter),
2381
+ Effect9.catchTag("BaselineFailed", (error3) => Effect9.gen(function* () {
2382
+ const failed = {
2383
+ schemaVersion: 2,
2384
+ tool: "mutant.cafe",
2385
+ root,
2386
+ baseline: { durationMs: 0, testCommand: error3.command },
2387
+ timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
2388
+ results: [],
2389
+ failure: `BaselineFailed: ${error3.command.join(" ")}
2390
+ ${error3.output.slice(-8e3)}`
2391
+ };
2392
+ yield* reporter.write(failed);
2393
+ if (!input.advisory) return yield* error3;
2394
+ if (markdown === void 0) yield* Console3.log("Advisory: baseline failed; would exit 4 without --advisory.");
2395
+ return failed;
2396
+ }))
2397
+ );
2398
+ if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield* Console3.log(`Advisory: would exit ${reportExitCode(report)} without --advisory.`);
1975
2399
  yield* reporter.write(report);
1976
- if (options.onExit !== void 0) yield* options.onExit(reportExitCode(report));
2400
+ if (options.onExit !== void 0) yield* options.onExit(input.advisory ? 0 : reportExitCode(report));
1977
2401
  }));
1978
- var runCli = Effect8.fn("runCli")(function* (options) {
2402
+ var runCli = Effect9.fn("runCli")(function* (options) {
1979
2403
  const code = yield* Ref.make(0);
1980
2404
  const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
1981
- yield* Command.runWith(command, { version: "0.1.3" })(options.args).pipe(
1982
- Effect8.catch((error2) => Effect8.gen(function* () {
1983
- yield* Console3.error(error2._tag === "ProgramLoadError" ? `${error2.tsconfig}:
1984
- ${error2.diagnostics.join("\n")}` : error2._tag === "BaselineFailed" ? `Baseline failed (${error2.exitCode}): ${error2.command.join(" ")}
1985
- ${error2.output.slice(-8e3)}` : String(error2));
1986
- yield* Ref.set(code, errorExitCode(error2));
2405
+ yield* Command.runWith(command, { version: "0.1.5" })(options.args).pipe(
2406
+ Effect9.catch((error3) => Effect9.gen(function* () {
2407
+ yield* Console3.error(error3._tag === "ProgramLoadError" ? `${error3.tsconfig}:
2408
+ ${error3.diagnostics.join("\n")}` : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${error3.command.join(" ")}
2409
+ ${error3.output.slice(-8e3)}` : String(error3));
2410
+ yield* Ref.set(code, errorExitCode(error3));
1987
2411
  })),
1988
- Effect8.catchDefect((defect) => Effect8.gen(function* () {
2412
+ Effect9.catchDefect((defect) => Effect9.gen(function* () {
1989
2413
  yield* Console3.error(`Internal error: ${String(defect)}`);
1990
2414
  yield* Ref.set(code, 70);
1991
2415
  }))
@@ -1994,15 +2418,15 @@ ${error2.output.slice(-8e3)}` : String(error2));
1994
2418
  });
1995
2419
 
1996
2420
  // packages/cli/src/bin.ts
1997
- var run = (config, mutants) => runMutants(config, Stream6.fromIterable(mutants));
2421
+ var run = (config, mutants) => runMutants(config, Stream7.fromIterable(mutants));
1998
2422
  var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
1999
2423
  Layer5.provideMerge(NodeServices.layer)
2000
2424
  );
2001
- var main = Effect9.gen(function* () {
2425
+ var main = Effect10.gen(function* () {
2002
2426
  const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
2003
- yield* Effect9.sync(() => {
2427
+ yield* Effect10.sync(() => {
2004
2428
  process.exitCode = code;
2005
2429
  });
2006
- }).pipe(Effect9.provide(live));
2430
+ }).pipe(Effect10.provide(live));
2007
2431
  NodeRuntime.runMain(main);
2008
2432
  //# sourceMappingURL=bin.js.map