mutant-cafe 0.1.2 → 0.1.3

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
@@ -13,6 +13,7 @@ var RunConfig = Schema.Struct({
13
13
  exclude: Schema.Array(Schema.String),
14
14
  functionFilter: Schema.Array(Schema.String),
15
15
  inDiff: Schema.optional(Schema.String),
16
+ exportedOnly: Schema.optional(Schema.Boolean),
16
17
  jobs: Schema.Int,
17
18
  timeoutMs: Schema.optional(Schema.Int),
18
19
  timeoutMultiplier: Schema.Finite,
@@ -39,6 +40,7 @@ var ProgramLoadError = class extends Schema2.TaggedError()("ProgramLoadError", {
39
40
  };
40
41
  var BaselineFailed = class extends Schema2.TaggedError()("BaselineFailed", {
41
42
  exitCode: Schema2.Int,
43
+ command: Schema2.Array(Schema2.String),
42
44
  output: Schema2.String
43
45
  }) {
44
46
  };
@@ -79,6 +81,7 @@ var Genre = Schema3.Literals([
79
81
  "StreamOne",
80
82
  "StreamFail",
81
83
  "LayerFail",
84
+ "LayerDie",
82
85
  "SchemaAcceptAnything",
83
86
  "BooleanFlip",
84
87
  "LiteralCycle",
@@ -105,7 +108,7 @@ var Mutant = Schema3.Struct({
105
108
  replacement: Replacement,
106
109
  synthetic: Schema3.Boolean
107
110
  });
108
- var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout", "untested"]);
111
+ var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout", "untested", "unreliable"]);
109
112
  var MutantResult = Schema3.Struct({
110
113
  mutant: Mutant,
111
114
  outcome: Outcome,
@@ -114,17 +117,30 @@ var MutantResult = Schema3.Struct({
114
117
  diagnostics: Schema3.Array(Schema3.String),
115
118
  output: Schema3.optional(Schema3.String)
116
119
  });
120
+ var SelectionIssue = Schema3.Union([
121
+ Schema3.Struct({ kind: Schema3.Literal("runner"), reason: Schema3.String }),
122
+ Schema3.Struct({ kind: Schema3.Literal("warning"), reason: Schema3.String }),
123
+ Schema3.Struct({ kind: Schema3.Literal("target"), file: Schema3.String, reason: Schema3.String }),
124
+ Schema3.Struct({ kind: Schema3.Literal("built"), files: Schema3.optional(Schema3.Array(Schema3.String)), testFiles: Schema3.Array(Schema3.String), reason: Schema3.String })
125
+ ]);
117
126
  var Baseline = Schema3.Struct({
118
127
  durationMs: Schema3.Int,
119
- testCommand: Schema3.Array(Schema3.String)
128
+ testCommand: Schema3.Array(Schema3.String),
129
+ unreliable: Schema3.optional(Schema3.Array(SelectionIssue))
130
+ });
131
+ var NotMutated = Schema3.Struct({
132
+ file: Schema3.String,
133
+ functionName: Schema3.String,
134
+ reason: Schema3.String
120
135
  });
121
136
  var RunReport = Schema3.Struct({
122
- schemaVersion: Schema3.Literal(1),
137
+ schemaVersion: Schema3.Literal(2),
123
138
  tool: Schema3.Literal("mutant.cafe"),
124
139
  root: Schema3.String,
125
140
  baseline: Baseline,
126
141
  timeoutMs: Schema3.Int,
127
- results: Schema3.Array(MutantResult)
142
+ results: Schema3.Array(MutantResult),
143
+ failure: Schema3.optional(Schema3.String)
128
144
  });
129
145
 
130
146
  // packages/core/src/Services.ts
@@ -146,32 +162,32 @@ import * as Schema4 from "effect/Schema";
146
162
 
147
163
  // packages/engine/src/Generate.ts
148
164
  import { createHash } from "node:crypto";
149
- function* generateFunction(fn7) {
150
- const api = fn7.api;
165
+ function* generateFunction(fn8) {
166
+ const api = fn8.api;
151
167
  const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
152
- const pinned = `((): ${fn7.returnType} => (${expression}))()`;
153
- const text = fn7.block ? `{ return ${fn7.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
154
- return makeMutant(fn7, genre, text, value.synthetic, description);
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);
155
171
  };
156
- const shape = fn7.shape;
172
+ const shape = fn8.shape;
157
173
  switch (shape.kind) {
158
174
  case "Effect": {
159
175
  const succeed3 = api("Effect", "succeed");
160
176
  if (succeed3) {
161
177
  for (const value of shape.values) {
162
- if (!fn7.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed3}(${value.text})`, value);
178
+ if (!fn8.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed3}(${value.text})`, value);
163
179
  }
164
180
  }
165
- const fail4 = api("Effect", "fail");
181
+ const fail3 = api("Effect", "fail");
166
182
  const catchTag2 = api("Effect", "catchTag");
167
183
  for (const error2 of shape.errors) {
168
- if (fail4) yield candidate("EffectFail", `${fail4}(${error2.text})`, error2, `${fail4}(${error2.text}) [${error2.synthetic ? "synthetic tag cast" : "constructed error"}]`);
184
+ if (fail3) yield candidate("EffectFail", `${fail3}(${error2.text})`, error2, `${fail3}(${error2.text}) [${error2.synthetic ? "synthetic tag cast" : "constructed error"}]`);
169
185
  const value = shape.values[0];
170
186
  const die3 = api("Effect", "die");
171
187
  const recovery = value && succeed3 ? `${succeed3}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error2.tag}`)})` : void 0;
172
188
  if (catchTag2 && recovery) {
173
189
  const gen8 = api("Effect", "gen");
174
- const original = fn7.generator ? gen8 && `((): ${fn7.returnType} => ${gen8}(function* () ${fn7.original}))()` : fn7.block ? `((): ${fn7.returnType} => ${fn7.original})()` : `((): ${fn7.returnType} => (${fn7.original}))()`;
190
+ const original = fn8.generator ? gen8 && `((): ${fn8.returnType} => ${gen8}(function* () ${fn8.original}))()` : fn8.block ? `((): ${fn8.returnType} => ${fn8.original})()` : `((): ${fn8.returnType} => (${fn8.original}))()`;
175
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`);
176
192
  }
177
193
  }
@@ -190,45 +206,50 @@ function* generateFunction(fn7) {
190
206
  }
191
207
  case "Stream": {
192
208
  const empty = api("Stream", "empty");
193
- const make7 = api("Stream", "make");
194
- const fail4 = api("Stream", "fail");
209
+ const make8 = api("Stream", "make");
210
+ const fail3 = api("Stream", "fail");
195
211
  if (empty) yield candidate("StreamEmpty", empty);
196
- if (make7) for (const value of shape.values) yield candidate("StreamOne", `${make7}(${value.text})`, value);
197
- if (fail4) for (const error2 of shape.errors) yield candidate("StreamFail", `${fail4}(${error2.text})`, error2);
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);
198
214
  break;
199
215
  }
200
216
  case "Layer": {
201
217
  const layer2 = api("Layer", "effectContext");
202
- const fail4 = api("Effect", "fail");
203
- if (layer2 && fail4 && shape.service) {
204
- for (const error2 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail4}(${error2.text}))`, error2);
218
+ const fail3 = api("Effect", "fail");
219
+ const die2 = api("Effect", "die");
220
+ if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
221
+ if (layer2 && fail3) {
222
+ for (const error2 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail3}(${error2.text}))`, error2);
205
223
  }
206
224
  break;
207
225
  }
208
226
  case "Void":
209
- yield makeMutant(fn7, "FnValue", "{}", false, "an empty body");
227
+ yield makeMutant(fn8, "FnValue", "{}", false, "an empty body");
210
228
  break;
211
229
  default: {
212
230
  const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
213
231
  for (const value of shape.values) {
214
- if (shape.kind === "Literal" && value.text === fn7.literal) continue;
232
+ if (shape.kind === "Literal" && value.text === fn8.literal) continue;
215
233
  yield candidate(genre, value.text, value);
216
234
  }
217
235
  }
218
236
  }
219
237
  }
220
- function makeMutant(fn7, genre, text, synthetic, description) {
221
- const replacement = { startOffset: fn7.startOffset, endOffset: fn7.endOffset, text };
222
- const id = createHash("sha256").update(JSON.stringify([fn7.file, fn7.span, genre, text])).digest("hex").slice(0, 24);
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);
223
244
  return {
224
245
  id,
225
- file: fn7.file,
226
- functionName: fn7.name,
227
- returnType: fn7.returnType,
228
- displayReturnType: fn7.displayReturnType,
246
+ file: fn8.file,
247
+ functionName: fn8.name,
248
+ returnType: fn8.returnType,
249
+ displayReturnType: fn8.displayReturnType,
229
250
  genre,
230
- description: `replace ${fn7.name} -> ${fn7.returnType} with ${description}`,
231
- span: fn7.span,
251
+ description: `replace ${fn8.name} -> ${fn8.returnType} with ${description}`,
252
+ span: fn8.span,
232
253
  replacement,
233
254
  synthetic
234
255
  };
@@ -294,7 +315,9 @@ function makeTypeScriptOracle() {
294
315
  const sessions = /* @__PURE__ */ new Map();
295
316
  const owners = /* @__PURE__ */ new Map();
296
317
  return {
297
- *discover(config) {
318
+ discover(config) {
319
+ const notMutated = [];
320
+ const functions = [];
298
321
  const configPath = resolve(config.root, config.tsconfig);
299
322
  let session = sessions.get(configPath);
300
323
  if (!session) {
@@ -314,9 +337,14 @@ function makeTypeScriptOracle() {
314
337
  owners.set(file, session);
315
338
  const api = imports(source);
316
339
  const visit = (node) => {
317
- if (isFunction(node) && node.body && mutable(node, checker) && !skipped(node)) {
318
- const name = functionName(node);
319
- if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
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)))) {
320
348
  const signature = checker.getSignatureFromDeclaration(node);
321
349
  if (signature) {
322
350
  const wrapped = wrappedEffect(node, checker);
@@ -327,33 +355,80 @@ function makeTypeScriptOracle() {
327
355
  const end = body.getEnd();
328
356
  const a = source.getLineAndCharacterOfPosition(start);
329
357
  const b = source.getLineAndCharacterOfPosition(end);
330
- const shape = shapeOf(type, checker, node, body);
358
+ const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
359
+ const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
331
360
  const originals = equivalentSuccessValues(body, api);
332
- found.push({
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({
333
364
  file,
334
365
  name,
335
- returnType: returnTypeText(type, checker, node),
366
+ returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
336
367
  displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
368
+ skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
337
369
  equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
338
370
  span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
339
371
  startOffset: start,
340
372
  endOffset: end,
341
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),
342
379
  literal: literalOfBody(body, checker),
343
380
  block: ts.isBlock(body),
344
381
  generator: generator !== void 0,
345
382
  shape,
346
383
  api
347
384
  });
385
+ } else notMutated.push({ file, functionName: name, reason: "missing callable signature" });
386
+ }
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
+ });
348
419
  }
349
420
  }
350
- return;
351
421
  }
352
422
  ts.forEachChild(node, visit);
353
423
  };
354
424
  const found = [];
355
425
  visit(source);
356
- yield* found;
426
+ 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 });
431
+ }
357
432
  }
358
433
  const unmatched = config.include.filter((glob) => !matched.has(glob));
359
434
  if (unmatched.length) throw new ProgramLoadError({ tsconfig: configPath, reason: "selection", diagnostics: unmatched.map((glob) => {
@@ -361,6 +436,7 @@ function makeTypeScriptOracle() {
361
436
  const outside = target === ".." || target.startsWith("../");
362
437
  return `No source file matched ${JSON.stringify(glob)}${outside ? " (path is outside the package root)" : ""}`;
363
438
  }) });
439
+ return { functions, notMutated };
364
440
  },
365
441
  checkViable(mutant) {
366
442
  const session = owners.get(resolve(mutant.file));
@@ -372,21 +448,120 @@ function makeTypeScriptOracle() {
372
448
  function isFunction(node) {
373
449
  return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
374
450
  }
375
- function exported(node) {
376
- return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false);
451
+ function functionValue(node, checker) {
452
+ const wrapper = wrappedEffect(node, checker);
453
+ return wrapper && checker.getTypeAtLocation(node.parent).getCallSignatures().length ? node.parent : node;
454
+ }
455
+ function returnedBy(node, checker) {
456
+ let value = functionValue(node, checker);
457
+ while (ts.isParenthesizedExpression(value.parent)) value = value.parent;
458
+ const parent = value.parent;
459
+ if (ts.isArrowFunction(parent) && parent.body === value) return parent;
460
+ if (ts.isReturnStatement(parent) && parent.expression === value && ts.isBlock(parent.parent) && isFunction(parent.parent.parent)) return parent.parent.parent;
461
+ return void 0;
377
462
  }
378
463
  function mutable(node, checker) {
379
- if (ts.isMethodDeclaration(node)) return true;
380
- if (ts.isFunctionDeclaration(node)) return exported(node);
381
- const wrapper = wrappedEffect(node, checker);
382
- let current = node;
383
- if (wrapper) current = node.parent;
464
+ if (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) return true;
465
+ let current = wrappedEffect(node, checker) ? node.parent : node;
384
466
  while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
385
- if (!ts.isVariableDeclaration(current.parent) || current.parent.initializer !== current) return false;
386
- const statement = current.parent.parent.parent;
387
- return ts.isVariableStatement(statement) && exported(statement);
467
+ return returnedBy(node, checker) !== void 0 || (ts.isVariableDeclaration(current.parent) || ts.isPropertyAssignment(current.parent) || ts.isPropertyDeclaration(current.parent)) && current.parent.initializer === current;
468
+ }
469
+ function layerBody(boundary, checker) {
470
+ let enclosing = boundary.parent;
471
+ while (!ts.isSourceFile(enclosing) && !isFunction(enclosing)) {
472
+ if (ts.isCallExpression(enclosing) && family(checker.getTypeAtLocation(enclosing), checker)?.kind === "Layer") return true;
473
+ enclosing = enclosing.parent;
474
+ }
475
+ return false;
476
+ }
477
+ function returnsLayer(node, checker) {
478
+ const signature = checker.getSignatureFromDeclaration(node);
479
+ if (!signature) return false;
480
+ const type = checker.getReturnTypeOfSignature(signature);
481
+ return (type.isUnion() ? type.types : [type]).every((member) => family(member, checker)?.kind === "Layer");
482
+ }
483
+ function serviceProperty(node, boundary, checker) {
484
+ if (!(ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) || !ts.isObjectLiteralExpression(node.parent)) return false;
485
+ const object = node.parent;
486
+ const call = object.parent;
487
+ return ts.isCallExpression(call) && call.arguments[0] === object && ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === "of" && ts.isReturnStatement(call.parent) && call.parent.parent === boundary.body && layerBody(boundary, checker);
488
+ }
489
+ function serviceMethod(node, boundary, checker) {
490
+ if (!layerBody(boundary, checker) || !boundary.body) return false;
491
+ const declaration = ts.findAncestor(node, ts.isVariableDeclaration);
492
+ let returned = false;
493
+ const visit = (child) => {
494
+ if (isFunction(child)) return;
495
+ if (ts.isReturnStatement(child) && child.expression && ts.isCallExpression(child.expression)) {
496
+ const call = child.expression;
497
+ const object = call.arguments[0];
498
+ if (ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === "of" && object && ts.isObjectLiteralExpression(object)) {
499
+ returned ||= object.properties.some((prop) => {
500
+ if (ts.isPropertyAssignment(prop) && (prop.initializer === functionValue(node, checker) || declaration && ts.isIdentifier(prop.initializer) && checker.getSymbolAtLocation(prop.initializer)?.valueDeclaration === declaration)) return true;
501
+ if (ts.isShorthandPropertyAssignment(prop)) return checker.getShorthandAssignmentValueSymbol(prop)?.valueDeclaration === declaration;
502
+ return false;
503
+ });
504
+ }
505
+ }
506
+ ts.forEachChild(child, visit);
507
+ };
508
+ visit(boundary.body);
509
+ return returned;
510
+ }
511
+ function exportedBinding(binding, checker) {
512
+ let declaration = binding;
513
+ let symbol = binding.name ? checker.getSymbolAtLocation(binding.name) : void 0;
514
+ let container = ts.findAncestor(binding, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
515
+ while (container) {
516
+ const module = ts.isSourceFile(container) ? checker.getSymbolAtLocation(container) : ts.isModuleBlock(container) && ts.isModuleDeclaration(container.parent) ? checker.getSymbolAtLocation(container.parent.name) : void 0;
517
+ if (!module || !checker.getExportsOfModule(module).some((item) => {
518
+ const target = item.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(item) : item;
519
+ return target === symbol || target.valueDeclaration === declaration;
520
+ })) return false;
521
+ if (ts.isSourceFile(container)) return true;
522
+ if (!ts.isModuleBlock(container) || !ts.isModuleDeclaration(container.parent)) return false;
523
+ declaration = container.parent;
524
+ symbol = module;
525
+ container = ts.findAncestor(container.parent, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
526
+ }
527
+ return false;
528
+ }
529
+ function publicOwner(node, checker, seen = /* @__PURE__ */ new Set()) {
530
+ if (seen.has(node)) return false;
531
+ seen.add(node);
532
+ let current = node;
533
+ let binding;
534
+ let value = isFunction(node) ? node : void 0;
535
+ let throughService = false;
536
+ while (!ts.isSourceFile(current)) {
537
+ if (current !== node && isFunction(current)) {
538
+ const method = value ? serviceMethod(value, current, checker) : serviceProperty(node, current, checker);
539
+ if (!(value && returnedBy(value, checker) === current) && !method && !(throughService && returnsLayer(current, checker))) return false;
540
+ throughService ||= method;
541
+ value = current;
542
+ }
543
+ if (ts.isVariableDeclaration(current) || ts.isFunctionDeclaration(current) || ts.isClassDeclaration(current)) binding = current;
544
+ current = current.parent;
545
+ }
546
+ if (!binding) return false;
547
+ if (exportedBinding(binding, checker)) return true;
548
+ let exposed = false;
549
+ const declaration = binding;
550
+ const visit = (child) => {
551
+ if (exposed) return;
552
+ const referenced = ts.isShorthandPropertyAssignment(child) ? checker.getShorthandAssignmentValueSymbol(child) : ts.isPropertyAssignment(child) && ts.isIdentifier(child.initializer) ? checker.getSymbolAtLocation(child.initializer) : ts.isExportAssignment(child) && ts.isIdentifier(child.expression) ? checker.getSymbolAtLocation(child.expression) : void 0;
553
+ if (referenced?.valueDeclaration === declaration) {
554
+ exposed = ts.isExportAssignment(child) || publicOwner(child, checker, seen);
555
+ }
556
+ ts.forEachChild(child, visit);
557
+ };
558
+ visit(current);
559
+ return exposed;
388
560
  }
389
561
  function skipped(node) {
562
+ return skippedNode(node);
563
+ }
564
+ function skippedNode(node) {
390
565
  let current = node;
391
566
  while (!ts.isSourceFile(current)) {
392
567
  if (ts.getJSDocTags(current).some((tag) => tag.tagName.text === "mutants-skip")) return true;
@@ -394,24 +569,23 @@ function skipped(node) {
394
569
  }
395
570
  return false;
396
571
  }
397
- function functionName(node) {
398
- if (ts.isFunctionExpression(node) && node.asteriskToken) {
399
- let enclosing = node.parent;
400
- while (!ts.isSourceFile(enclosing)) {
401
- if (ts.isVariableDeclaration(enclosing)) return enclosing.name.getText();
402
- enclosing = enclosing.parent;
403
- }
404
- }
405
- if (node.name) {
406
- if (ts.isMethodDeclaration(node) && ts.isClassLike(node.parent) && node.parent.name) return `${node.parent.name.text}.${node.name.getText()}`;
407
- return node.name.getText();
408
- }
572
+ function valuePath(node) {
573
+ const parts = [];
409
574
  let current = node;
410
575
  while (!ts.isSourceFile(current)) {
411
- if (ts.isVariableDeclaration(current)) return current.name.getText();
576
+ if ((ts.isVariableDeclaration(current) || ts.isPropertyAssignment(current) || ts.isPropertyDeclaration(current) || ts.isMethodDeclaration(current) || ts.isFunctionDeclaration(current) || ts.isClassDeclaration(current) || ts.isModuleDeclaration(current)) && current.name) parts.unshift(current.name.getText());
412
577
  current = current.parent;
413
578
  }
414
- return "default";
579
+ return parts.join(".") || "default";
580
+ }
581
+ function functionName(node, checker) {
582
+ let path = valuePath(node);
583
+ let parent = returnedBy(node, checker);
584
+ while (parent) {
585
+ path += ".<inner>";
586
+ parent = returnedBy(parent, checker);
587
+ }
588
+ return path;
415
589
  }
416
590
  function wrappedEffect(node, checker) {
417
591
  if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
@@ -422,6 +596,39 @@ function wrappedEffect(node, checker) {
422
596
  const returned = checker.getReturnTypeOfSignature(signature);
423
597
  return family(returned, checker)?.kind === "Effect" ? returned : void 0;
424
598
  }
599
+ function nameableContract(contract, checker, node) {
600
+ return contract.types.every((type) => !hasUnnameableType(type, checker, node));
601
+ }
602
+ function hasUnnameableType(type, checker, location) {
603
+ const printed = checker.typeToTypeNode(type, location, ts.NodeBuilderFlags.NoTruncation);
604
+ if (!printed) return true;
605
+ let missing = false;
606
+ const visit = (node) => {
607
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !checker.resolveName(node.typeName.text, location, ts.SymbolFlags.Type, false)) missing = true;
608
+ ts.forEachChild(node, visit);
609
+ };
610
+ visit(printed);
611
+ return missing;
612
+ }
613
+ function generatorContract(node, checker) {
614
+ const signature = checker.getSignatureFromDeclaration(node);
615
+ if (!signature || !node.body) return void 0;
616
+ const iterator = checker.getReturnTypeOfSignature(signature);
617
+ const args = checker.getTypeArguments(iterator);
618
+ const [yielded, success] = args;
619
+ if (!yielded || !success) return void 0;
620
+ const effects = (yielded.isUnion() ? yielded.types : [yielded]).flatMap((t) => {
621
+ const f = family(t, checker);
622
+ return f?.kind === "Effect" ? [f] : [];
623
+ });
624
+ const print = (t) => returnTypeText(t, checker, node);
625
+ const union = (index) => [...new Set(effects.flatMap((f) => f.args[index] ? [print(f.args[index])] : []))].join(" | ") || "never";
626
+ return {
627
+ types: [success, ...effects.flatMap((effect5) => effect5.args.slice(1))],
628
+ 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()] }
630
+ };
631
+ }
425
632
  function literalOfBody(body, checker) {
426
633
  const first = ts.isBlock(body) && body.statements.length === 1 ? body.statements[0] : void 0;
427
634
  const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
@@ -460,9 +667,28 @@ function imports(source) {
460
667
  }
461
668
  return (module, member) => {
462
669
  const namespace = namespaces.get(module);
463
- return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`);
670
+ return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`) ?? `${mutationNamespace(source, module)}.${member}`;
464
671
  };
465
672
  }
673
+ function importInsertionOffset(source) {
674
+ let offset = source.text.startsWith("#!") ? source.text.indexOf("\n") + 1 || source.text.length : 0;
675
+ for (const statement of source.statements) {
676
+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;
677
+ offset = statement.getEnd();
678
+ }
679
+ return offset;
680
+ }
681
+ function mutationNamespace(source, module) {
682
+ let name = `__mutantCafe${module}`;
683
+ while (source.text.includes(name)) name += "_";
684
+ return name;
685
+ }
686
+ function mutationImports(source) {
687
+ return ["Effect", "Option", "Stream", "Layer"].map((module) => {
688
+ const namespace = mutationNamespace(source, module);
689
+ return { namespace, statement: `import * as ${namespace} from "effect/${module}";` };
690
+ });
691
+ }
466
692
  function family(type, checker) {
467
693
  const symbol = type.aliasSymbol ?? type.getSymbol();
468
694
  const name = symbol?.getName();
@@ -500,40 +726,34 @@ function family(type, checker) {
500
726
  function shapeOf(type, checker, node, body) {
501
727
  if (type.isUnion() && type.types.every((member) => family(member, checker)?.kind === "Effect")) {
502
728
  const shapes = type.types.map((member) => shapeOf(member, checker, node, body));
503
- const values = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
729
+ const values2 = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
504
730
  const errors = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.errors : []);
505
731
  return {
506
732
  kind: "Effect",
507
- values: [...new Map(values.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
733
+ values: [...new Map(values2.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
508
734
  errors: [...new Map(errors.map((error2) => [error2.tag, error2])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
509
735
  };
510
736
  }
511
737
  const detected = family(type, checker);
512
738
  if (detected) {
513
739
  const [a, e] = detected.args;
514
- const values = a ? valuesOf(a, checker, node) : [];
515
- if (detected.kind === "Option") return { kind: "Option", values };
740
+ const values2 = a ? valuesOf(a, checker, node) : [];
741
+ if (detected.kind === "Option") return { kind: "Option", values: values2 };
516
742
  const errors = e ? taggedValues(e, checker, node) : [];
517
- if (detected.kind === "Layer") {
518
- let service;
519
- const find = (child) => {
520
- if (!service && ts.isCallExpression(child) && child.arguments[0]) {
521
- const arg = child.arguments[0];
522
- const argType = checker.getTypeAtLocation(arg);
523
- if (argType.getProperty("Identifier") && argType.getProperty("Service")) service = arg.getText();
524
- }
525
- ts.forEachChild(child, find);
526
- };
527
- find(body);
528
- return { kind: "Layer", errors, service };
529
- }
530
- return { kind: detected.kind, values, errors };
743
+ if (detected.kind === "Layer") return { kind: "Layer", errors };
744
+ return { kind: detected.kind, values: values2, errors };
531
745
  }
532
746
  if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
533
747
  const members = type.isUnion() ? type.types : [type];
534
748
  const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
535
749
  const literal = members.every((t) => t.isLiteral());
536
- return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values: valuesOf(type, checker, node) };
750
+ const values = valuesOf(type, checker, node);
751
+ if (isFunction(node)) for (const parameter of node.parameters) {
752
+ if (ts.isIdentifier(parameter.name) && !parameter.questionToken && !parameter.dotDotDotToken && checker.getTypeAtLocation(parameter) === type) {
753
+ values.push({ text: parameter.name.text, synthetic: false });
754
+ }
755
+ }
756
+ return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values };
537
757
  }
538
758
  function taggedValues(type, checker, location) {
539
759
  return (type.isUnion() ? type.types : [type]).flatMap((member) => {
@@ -616,6 +836,17 @@ function isEquivalentSuccess(text, values) {
616
836
  const value = literalData(statement.expression);
617
837
  return value !== void 0 && values.includes(JSON.stringify(value));
618
838
  }
839
+ function synthesisReason(type, checker, node) {
840
+ 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
+ }
847
+ }
848
+ return `opaque return: ${checker.typeToString(type, node)}`;
849
+ }
619
850
  function valuesOf(type, checker, location, depth = 0) {
620
851
  if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
621
852
  const value = (text) => ({ text, synthetic: false });
@@ -631,6 +862,15 @@ function valuesOf(type, checker, location, depth = 0) {
631
862
  ...wrap ? values.map((v) => ({ text: `${wrap}(${v.text})`, synthetic: v.synthetic })) : []
632
863
  ];
633
864
  }
865
+ if (type.isIntersection()) {
866
+ const primitive = type.types.find((member) => member.flags & (ts.TypeFlags.String | ts.TypeFlags.Number));
867
+ 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)})` }));
869
+ }
870
+ const symbol = type.getSymbol();
871
+ 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
+ return [value(symbol.name.endsWith("Set") ? "new Set()" : "new Map()")];
873
+ }
634
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));
635
875
  if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
636
876
  if (type.isNumberLiteral()) return [value(String(type.value))];
@@ -656,11 +896,21 @@ function valuesOf(type, checker, location, depth = 0) {
656
896
  for (const prop of type.getProperties()) {
657
897
  if (prop.flags & ts.SymbolFlags.Optional) continue;
658
898
  if (!/^[$\w]+$/.test(prop.name)) return [];
659
- const first = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1)[0];
660
- if (!first) return [];
661
- fields.push(`${JSON.stringify(prop.name)}: ${first.text}`);
899
+ const values = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1);
900
+ if (!values.length) return [];
901
+ fields.push({ name: prop.name, values });
662
902
  }
663
- return [value(`({ ${fields.join(", ")} } as const)`)];
903
+ const literalFields = fields.filter((field) => {
904
+ const prop = type.getProperty(field.name);
905
+ const t = checker.getTypeOfSymbolAtLocation(prop, location);
906
+ return (t.isUnion() ? t.types : [t]).every((member) => member.isLiteral() || !!(member.flags & ts.TypeFlags.BooleanLiteral));
907
+ });
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(", ")} })`);
912
+ 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))) : []];
664
914
  }
665
915
  return [];
666
916
  }
@@ -671,18 +921,23 @@ var MutantSourceLive = Layer.effect(
671
921
  Effect.sync(() => makeMutantSource(makeTypeScriptOracle()))
672
922
  );
673
923
  function makeMutantSource(oracle) {
924
+ const discover = (config) => Effect.try({
925
+ try: () => {
926
+ const discovered = oracle.discover(config);
927
+ const notMutated = [...discovered.notMutated];
928
+ 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}` });
932
+ mutants.push(...generated);
933
+ }
934
+ return { mutants, notMutated };
935
+ },
936
+ catch: (error2) => loadError(config.tsconfig, error2)
937
+ });
674
938
  return {
675
- generate: (config) => Stream.unwrap(Effect.try({
676
- try: () => Stream.fromIterable({
677
- *[Symbol.iterator]() {
678
- for (const fn7 of oracle.discover(config)) yield* generateFunction(fn7);
679
- }
680
- }),
681
- catch: (error2) => loadError(config.tsconfig, error2)
682
- })).pipe(
683
- // Iteration is synchronous compiler work; load it inside the typed error boundary.
684
- Stream.catchDefect((error2) => Stream.fail(loadError(config.tsconfig, error2)))
685
- ),
939
+ notMutated: (config) => discover(config).pipe(Effect.map((result2) => result2.notMutated)),
940
+ generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result2) => Stream.fromIterable(result2.mutants)))),
686
941
  checkViable: (mutant) => Effect.try({
687
942
  try: () => oracle.checkViable(mutant),
688
943
  catch: (error2) => loadError("", error2)
@@ -739,7 +994,23 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
739
994
  const src = path.join(from, entry);
740
995
  const dest = path.join(to, entry);
741
996
  if (entry === "node_modules") {
742
- yield* fs.symlink(path.resolve(src), dest);
997
+ const linkDependencies = (from2, to2) => Effect2.gen(function* () {
998
+ yield* fs.makeDirectory(to2, { recursive: true });
999
+ for (const name of yield* fs.readDirectory(from2)) {
1000
+ if ([".vite", ".vite-temp", ".vitest", ".cache"].includes(name)) continue;
1001
+ const dependency = path.join(from2, name);
1002
+ const destination = path.join(to2, name);
1003
+ if (name.startsWith("@")) {
1004
+ yield* linkDependencies(dependency, destination);
1005
+ continue;
1006
+ }
1007
+ const realDependency = yield* fs.realPath(dependency);
1008
+ const rel = path.relative(copyRoot, realDependency);
1009
+ const inside = rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) && !rel.split(path.sep).includes("node_modules");
1010
+ yield* fs.symlink(inside ? path.join(temp, rel) : realDependency, destination);
1011
+ }
1012
+ });
1013
+ yield* linkDependencies(src, dest);
743
1014
  } else {
744
1015
  yield* copy(src, dest, [...ancestors, real]);
745
1016
  }
@@ -796,30 +1067,204 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
796
1067
 
797
1068
  // packages/runner/src/TestRunner.ts
798
1069
  import * as Clock from "effect/Clock";
1070
+ import * as Console from "effect/Console";
1071
+
1072
+ // packages/runner/src/Preflight.ts
799
1073
  import * as Effect3 from "effect/Effect";
1074
+ import * as Schema5 from "effect/Schema";
1075
+ import * as ChildProcess from "effect/process/ChildProcess";
1076
+ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1077
+ var Issues = Schema5.Array(SelectionIssue);
1078
+ var probe = String.raw`
1079
+ import { readFile, readdir } from "node:fs/promises";
1080
+ import { resolve, relative, dirname, isAbsolute, sep } from "node:path";
1081
+ import { createRequire } from "node:module";
1082
+ import { fileURLToPath } from "node:url";
1083
+ const root = process.cwd();
1084
+ const issues = [];
1085
+ const pkg = JSON.parse(await readFile("package.json", "utf8").catch(error => { if (error.code === "ENOENT") return "{}"; throw error; }));
1086
+ const script = pkg.scripts?.test;
1087
+ const vitestScript = !script || /(?:^|[\s/])vitest(?=\s|$|[;&|])/.test(script);
1088
+ const delegated = script && /(?:\bturbo\s+(?:run\s+)?test\b|\bpnpm\s+(?:-r|--recursive|--filter\s+\S+)\s+(?:run\s+)?test\b)/.test(script);
1089
+ const otherRunner = script && /(?:^|&&\s*|;\s*)(?:(?:pnpm\s+exec|npx)\s+)?(?:node\s+(?:\S+\s+)*--test(?=\s|$)|(?:jest|mocha|ava|tap)(?=\s|$)|bun\s+test(?=\s|$))/.test(script);
1090
+ if (otherRunner) {
1091
+ issues.push({ kind: "runner", reason: 'package.json scripts.test = ' + JSON.stringify(script) + '; mutant.cafe only runs Vitest' });
1092
+ } else {
1093
+ if (!vitestScript) issues.push({ kind: "warning", reason: 'package.json scripts.test = ' + JSON.stringify(script) + (delegated ? '; delegated test runner: Vitest selection is unverified' : '; unknown test wrapper: Vitest selection is unverified') });
1094
+ let ctx;
1095
+ try {
1096
+ const { createVitest } = await import("vitest/node");
1097
+ ctx = await createVitest("test", { root, watch: false, cache: false, fsModuleCache: false });
1098
+ const selected = new Set((await ctx.globTestSpecifications()).map(spec => resolve(spec.moduleId)));
1099
+ const sources = new Map();
1100
+ async function walk(dir) {
1101
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
1102
+ if (["node_modules", ".git", ".brain", ".pi", ".agent_sources", "mutants.out", "dist"].includes(entry.name)) continue;
1103
+ const file = resolve(dir, entry.name);
1104
+ if (entry.isDirectory()) await walk(file);
1105
+ else if (/\.[cm]?[jt]sx?$/.test(file)) sources.set(file, await readFile(file, "utf8"));
1106
+ }
1107
+ }
1108
+ await walk(root);
1109
+ // Read only explicit rootDir/outDir evidence, including JSONC and extends.
1110
+ // Do not depend on a compiler API in the tested package or infer build layout.
1111
+ async function configOptions(file, seen = new Set()) {
1112
+ if (seen.has(file)) throw new Error('cyclic tsconfig extends');
1113
+ const text = await readFile(file, 'utf8');
1114
+ const json = text.replace(/"(?:\\.|[^"\\])*"|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, token => token.startsWith('"') ? token : token.replace(/[^\r\n]/g, ' '))
1115
+ .replace(/("(?:\\.|[^"\\])*")|,\s*(?=[}\]])/g, (token, string) => string ?? '');
1116
+ const config = JSON.parse(json);
1117
+ let options = {};
1118
+ for (const base of Array.isArray(config.extends) ? config.extends : typeof config.extends === 'string' ? [config.extends] : []) {
1119
+ const path = base.startsWith('.') || isAbsolute(base) ? resolve(dirname(file), base) : createRequire(file).resolve(base);
1120
+ const candidate = await readFile(path).then(() => path, () => path + '.json');
1121
+ options = { ...options, ...await configOptions(candidate, new Set([...seen, file])) };
1122
+ }
1123
+ for (const key of ['rootDir', 'outDir']) if (typeof config.compilerOptions?.[key] === 'string') options[key] = resolve(dirname(file), config.compilerOptions[key]);
1124
+ return options;
1125
+ }
1126
+ let options = {};
1127
+ try { options = await configOptions(resolve(root, process.argv[1])); }
1128
+ catch { /* No proven mapping: restrict by importing tests only. */ }
1129
+ function sourceFile(path) {
1130
+ return [path, path.replace(/\.[cm]?js$/, '.ts'), path.replace(/\.[cm]?js$/, '.mts'), path.replace(/\.[cm]?js$/, '.cts'), path + '.ts', path + '.tsx', path + '.mts', path + '.cts', resolve(path, 'index.ts')].find(p => sources.has(p) && !/\.d\.[cm]?ts$/.test(p));
1131
+ }
1132
+ function exportTypes(specifier) {
1133
+ const key = specifier === pkg.name ? '.' : './' + specifier.slice(pkg.name.length + 1);
1134
+ let entry = pkg.exports;
1135
+ let wildcard;
1136
+ if (entry && typeof entry === 'object' && Object.keys(entry).some(key => key.startsWith('.'))) {
1137
+ if (key in entry) entry = entry[key];
1138
+ else {
1139
+ const pattern = Object.keys(entry).find(pattern => pattern.includes('*') && key.startsWith(pattern.split('*')[0]) && key.endsWith(pattern.split('*')[1]));
1140
+ if (!pattern) return;
1141
+ const [before, after] = pattern.split('*');
1142
+ wildcard = key.slice(before.length, after.length ? -after.length : undefined);
1143
+ entry = entry[pattern];
1144
+ }
1145
+ } else if (key !== '.') return;
1146
+ function types(value) {
1147
+ if (!value || typeof value !== 'object') return;
1148
+ if (typeof value.types === 'string') return value.types;
1149
+ return types(value.types) ?? types(value.import) ?? types(value.default);
1150
+ }
1151
+ const path = types(entry) ?? (key === '.' ? pkg.types : undefined);
1152
+ return typeof path === 'string' ? resolve(root, wildcard === undefined ? path : path.replaceAll('*', wildcard)) : undefined;
1153
+ }
1154
+ function mappedSource(entry, types) {
1155
+ for (const path of [types, entry]) {
1156
+ if (!path) continue;
1157
+ if (/\.[cm]?tsx?$/.test(path) && !/\.d\.[cm]?ts$/.test(path)) {
1158
+ const direct = sourceFile(path);
1159
+ if (direct) return direct;
1160
+ }
1161
+ if (!options.rootDir || !options.outDir) continue;
1162
+ const inside = relative(options.outDir, path);
1163
+ if (inside === '..' || inside.startsWith('..' + sep) || isAbsolute(inside)) continue;
1164
+ const stem = inside.replace(/(?:\.d)?\.[cm]?[jt]sx?$/, '');
1165
+ const mapped = sourceFile(resolve(options.rootDir, stem));
1166
+ if (mapped) return mapped;
1167
+ }
1168
+ }
1169
+ const edges = new Map();
1170
+ const built = [];
1171
+ for (const [file, text] of sources) {
1172
+ const dependencies = new Set();
1173
+ edges.set(file, dependencies);
1174
+ for (const match of text.matchAll(/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)["']([^"']+)["']/g)) {
1175
+ let target;
1176
+ let source;
1177
+ const specifier = match[1];
1178
+ if (specifier.startsWith('.')) target = resolve(dirname(file), specifier);
1179
+ else {
1180
+ try {
1181
+ const self = pkg.name && (specifier === pkg.name || specifier.startsWith(pkg.name + '/'));
1182
+ target = self ? fileURLToPath(import.meta.resolve(specifier)) : createRequire(file).resolve(specifier);
1183
+ if (self && (!/\.[cm]?tsx?$/.test(target) || /\.d\.[cm]?ts$/.test(target))) {
1184
+ source = mappedSource(target, exportTypes(specifier));
1185
+ built.push({ importer: file, source, reason: relative(root, file) + ' imports ' + specifier + '; self entry resolves to built output ' + relative(root, target) + ', not mutated TypeScript source' + (source ? '; mapped source ' + relative(root, source) : '; source mapping unavailable') });
1186
+ }
1187
+ } catch { continue; }
1188
+ }
1189
+ const candidate = source ?? sourceFile(target);
1190
+ if (candidate) dependencies.add(candidate);
1191
+ }
1192
+ }
1193
+ function dependencies(file, seen = new Set()) {
1194
+ if (seen.has(file)) return seen;
1195
+ seen.add(file);
1196
+ for (const dependency of edges.get(file) ?? []) dependencies(dependency, seen);
1197
+ return seen;
1198
+ }
1199
+ const closures = new Map([...selected].map(file => [file, dependencies(file)]));
1200
+ for (const entry of built) {
1201
+ const testFiles = [...selected].filter(file => closures.get(file).has(entry.importer)).map(file => relative(root, file));
1202
+ if (testFiles.length) issues.push({ kind: 'built', ...(entry.source ? { files: [...dependencies(entry.source)].map(file => relative(root, file)) } : {}), testFiles, reason: entry.reason });
1203
+ }
1204
+ const reached = new Set([...closures.values()].flatMap(files => [...files]));
1205
+ for (const [file, text] of sources) {
1206
+ const testFile = /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file)
1207
+ || (/["'](?:node:test|vitest|@effect\/vitest)["']/.test(text) && /\b(?:it|test|describe)\s*(?:\.|\()/.test(text));
1208
+ if (reached.has(file) || !testFile) continue;
1209
+ for (const target of dependencies(file)) {
1210
+ if (target !== file) issues.push({ kind: 'target', file: relative(root, target), reason: relative(root, file) + ' imports this target but is absent from Vitest resolved test files' });
1211
+ }
1212
+ }
1213
+ } catch (error) {
1214
+ issues.push({ kind: 'warning', reason: 'Cannot verify Vitest resolved selection: ' + String(error) });
1215
+ } finally { await ctx?.close(); }
1216
+ }
1217
+ console.log('mutant-cafe-preflight:' + JSON.stringify([...new Map(issues.map(issue => [JSON.stringify(issue), issue])).values()]));
1218
+ `;
1219
+ var preflight = Effect3.fn("TestRunner.preflight")(function* (root, tsconfig = "tsconfig.json") {
1220
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1221
+ const output = yield* spawner.string(ChildProcess.make("node", ["--input-type=module", "--eval", probe, tsconfig], { cwd: root, stdin: "ignore" }));
1222
+ const encoded = output.split("\n").find((line) => line.startsWith("mutant-cafe-preflight:"))?.slice("mutant-cafe-preflight:".length);
1223
+ const issues = encoded === void 0 ? [{ kind: "warning", reason: "Vitest selection probe returned no evidence" }] : yield* Schema5.decodeEffect(Schema5.fromJsonString(Issues))(encoded);
1224
+ return issues;
1225
+ });
1226
+ function unreliableFor(baseline, file, testFiles) {
1227
+ return baseline.unreliable?.filter((issue) => {
1228
+ switch (issue.kind) {
1229
+ case "runner":
1230
+ return true;
1231
+ case "warning":
1232
+ return false;
1233
+ case "target":
1234
+ return issue.file === file;
1235
+ case "built":
1236
+ return (issue.files === void 0 || issue.files.includes(file)) && (testFiles?.some((test) => issue.testFiles.includes(test)) ?? false);
1237
+ }
1238
+ }) ?? [];
1239
+ }
1240
+
1241
+ // packages/runner/src/TestRunner.ts
1242
+ import * as Effect4 from "effect/Effect";
800
1243
  import * as Layer3 from "effect/Layer";
801
1244
  import * as FileSystem3 from "effect/FileSystem";
802
1245
  import * as Path3 from "effect/Path";
803
1246
  import * as Stream2 from "effect/Stream";
804
- import * as ChildProcess from "effect/process/ChildProcess";
805
- import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
806
- var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
807
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1247
+ import * as Schema6 from "effect/Schema";
1248
+ import * as ChildProcess2 from "effect/process/ChildProcess";
1249
+ import * as ChildProcessSpawner3 from "effect/process/ChildProcessSpawner";
1250
+ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
1251
+ const spawner = yield* ChildProcessSpawner3.ChildProcessSpawner;
808
1252
  const fs = yield* FileSystem3.FileSystem;
809
1253
  const path = yield* Path3.Path;
810
- const execute = Effect3.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
1254
+ const execute = Effect4.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
811
1255
  const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
812
- Effect3.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) }))
1256
+ Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) }))
813
1257
  );
814
1258
  const reporter = path.join(reporterDir, "reporter.mjs");
815
1259
  const marker = `mutant-cafe:${path.basename(reporterDir)}:`;
816
- yield* fs.writeFileString(reporter, `export default class {
1260
+ yield* fs.writeFileString(reporter, `import { relative } from "node:path";
1261
+ export default class {
817
1262
  files = 0;
818
- onTestRunStart(specifications) { this.files = specifications.length; }
1263
+ onTestRunStart(specifications) { this.files = specifications.length; console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(specifications.map(spec => relative(process.cwd(), spec.moduleId)))); }
819
1264
  onTestModuleCollected() { console.log(${JSON.stringify(marker + "collected")}); }
820
1265
  onTestCaseResult(test) { if (test.result().state === "failed") console.log(${JSON.stringify(marker + "failed")}); }
821
1266
  onTestRunEnd() { if (this.files === 0) console.log(${JSON.stringify(marker + "empty")}); }
822
- }`).pipe(Effect3.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) })));
1267
+ }`).pipe(Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) })));
823
1268
  const command = [
824
1269
  "npx",
825
1270
  "--no",
@@ -833,11 +1278,12 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
833
1278
  "--no-cache",
834
1279
  "--no-fsModuleCache"
835
1280
  ];
1281
+ if (timeoutMs === void 0) yield* Console.log(`Baseline command: ${command.join(" ")} (cwd: ${dir.path})`);
836
1282
  const started = yield* Clock.currentTimeMillis;
837
1283
  const chunks = [];
838
1284
  let exitCode = 1;
839
- const child = Effect3.scoped(Effect3.gen(function* () {
840
- const handle = yield* spawner.spawn(ChildProcess.make(command[0], command.slice(1), {
1285
+ const child = Effect4.scoped(Effect4.gen(function* () {
1286
+ const handle = yield* spawner.spawn(ChildProcess2.make(command[0], command.slice(1), {
841
1287
  cwd: dir.path,
842
1288
  // Node's scoped spawner kills the detached process group, not just pnpm.
843
1289
  detached: true,
@@ -845,44 +1291,57 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
845
1291
  forceKillAfter: "100 millis",
846
1292
  stdin: "ignore"
847
1293
  }));
848
- const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect3.sync(() => {
1294
+ const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect4.sync(() => {
849
1295
  chunks.push(chunk);
850
1296
  })));
851
- const [code] = yield* Effect3.all([handle.exitCode, collect], { concurrency: "unbounded" });
1297
+ const [code] = yield* Effect4.all([handle.exitCode, collect], { concurrency: "unbounded" });
852
1298
  exitCode = code;
853
1299
  return code === 0 ? "passed" : "failed";
854
1300
  }));
855
1301
  const status = yield* (timeoutMs === void 0 ? child : child.pipe(
856
- Effect3.timeout(timeoutMs),
857
- Effect3.catchTag("TimeoutError", () => Effect3.succeed("timedOut"))
858
- )).pipe(Effect3.mapError((error2) => new TestSpawnError({ command, message: error2.message })));
1302
+ Effect4.timeout(timeoutMs),
1303
+ Effect4.catchTag("TimeoutError", () => Effect4.succeed("timedOut"))
1304
+ )).pipe(Effect4.mapError((error2) => new TestSpawnError({ command, message: error2.message })));
859
1305
  const ended = yield* Clock.currentTimeMillis;
860
1306
  const output = chunks.join("");
861
1307
  const failed = output.includes(marker + "failed");
1308
+ const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
1309
+ 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)}` }))
1311
+ );
862
1312
  const run2 = {
863
1313
  status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
864
1314
  durationMs: ended - started,
865
1315
  command,
866
1316
  output,
867
- testsCollected: output.includes(marker + "collected")
1317
+ testsCollected: output.includes(marker + "collected"),
1318
+ testFiles: selected
868
1319
  };
869
1320
  return { ...run2, exitCode };
870
- }, Effect3.scoped);
1321
+ }, Effect4.scoped);
871
1322
  return TestRunner.of({
872
- baseline: Effect3.fn("TestRunner.baseline")(function* (dir) {
1323
+ 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)}` }])));
1325
+ for (const issue of unreliable) yield* Console.warn(`Warning (${issue.kind}): ${issue.reason}`);
1326
+ if (unreliable.some((issue) => issue.kind === "runner")) {
1327
+ const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
1328
+ yield* Console.warn(`Baseline command (not executed: unsupported runner): ${command.join(" ")}`);
1329
+ return { durationMs: 0, testCommand: command, unreliable };
1330
+ }
873
1331
  const run2 = yield* execute(dir, ["run", "--passWithNoTests"]);
874
1332
  if (run2.status !== "passed" && run2.status !== "untested") {
875
- return yield* Effect3.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output }));
1333
+ return yield* Effect4.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output, command: run2.command }));
876
1334
  }
877
- return { durationMs: run2.durationMs, testCommand: run2.command };
1335
+ return { durationMs: run2.durationMs, testCommand: run2.command, unreliable };
878
1336
  }),
879
- runRelated: Effect3.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs) {
1337
+ runRelated: Effect4.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs) {
880
1338
  const related = yield* execute(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs);
881
1339
  if (related.status !== "untested") return related;
882
1340
  const remaining = Math.max(1, timeoutMs - related.durationMs);
883
1341
  const full = yield* execute(dir, ["run", "--passWithNoTests"], remaining);
884
1342
  return {
885
1343
  ...full,
1344
+ status: full.status === "passed" ? "untested" : full.status,
886
1345
  durationMs: related.durationMs + full.durationMs,
887
1346
  output: related.output + "\nFull-suite fallback:\n" + full.output
888
1347
  };
@@ -893,11 +1352,11 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
893
1352
  // packages/runner/src/Run.ts
894
1353
  import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
895
1354
  import { types } from "xstate";
896
- import * as Effect4 from "effect/Effect";
1355
+ import * as Effect5 from "effect/Effect";
897
1356
  import * as Pool from "effect/Pool";
898
1357
  import * as Path5 from "effect/Path";
899
1358
  import * as Result from "effect/Result";
900
- import * as Schema5 from "effect/Schema";
1359
+ import * as Schema7 from "effect/Schema";
901
1360
  import * as Scope from "effect/Scope";
902
1361
  import * as Stream3 from "effect/Stream";
903
1362
  var ScratchPool = class {
@@ -906,7 +1365,7 @@ var ScratchPool = class {
906
1365
  this.value = value;
907
1366
  }
908
1367
  };
909
- var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
1368
+ var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
910
1369
  const scratch = yield* Scratch;
911
1370
  const tests = yield* TestRunner;
912
1371
  const source = yield* MutantSource;
@@ -915,47 +1374,49 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
915
1374
  const path = yield* Path5.Path;
916
1375
  const jobs = Math.max(1, Math.floor(config.jobs));
917
1376
  const report = (state2) => ({
918
- schemaVersion: 1,
1377
+ schemaVersion: 2,
919
1378
  tool: "mutant.cafe",
920
1379
  root: config.root,
921
1380
  baseline: state2.baseline,
922
1381
  timeoutMs: state2.timeoutMs,
923
- results: state2.results
1382
+ results: state2.results,
1383
+ ...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${state2.failure.command.join(" ")}
1384
+ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
924
1385
  });
925
- const capture = (effect5) => Effect4.result(effect5);
926
- const copying = createEffectLogic(() => capture(Effect4.gen(function* () {
1386
+ const capture = (effect5) => Effect5.result(effect5);
1387
+ const copying = createEffectLogic(() => capture(Effect5.gen(function* () {
927
1388
  const pool = yield* Pool.make({ acquire: scratch.acquire(config.root), size: jobs }).pipe(
928
- Effect4.provideService(Scope.Scope, scope)
1389
+ Effect5.provideService(Scope.Scope, scope)
929
1390
  );
930
- yield* Effect4.scoped(Pool.get(pool));
1391
+ yield* Effect5.scoped(Pool.get(pool));
931
1392
  return new ScratchPool(pool);
932
1393
  })));
933
- const baselining = createEffectLogic(({ input }) => capture(Effect4.gen(function* () {
934
- if (input === void 0) return yield* Effect4.die("Missing scratch pool");
935
- const baseline = yield* Effect4.scoped(Effect4.gen(function* () {
1394
+ const baselining = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
1395
+ if (input === void 0) return yield* Effect5.die("Missing scratch pool");
1396
+ const baseline = yield* Effect5.scoped(Effect5.gen(function* () {
936
1397
  const dir = yield* Pool.get(input.value);
937
- return yield* tests.baseline(dir);
1398
+ return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig);
938
1399
  }));
939
1400
  return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
940
1401
  })));
941
1402
  const generating = createEffectLogic(() => capture(Stream3.runCollect(mutants ?? source.generate(config))));
942
- const testing = createEffectLogic(({ input }) => capture(Effect4.gen(function* () {
1403
+ const testing = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
943
1404
  const dirs = input.state.pool?.value;
944
- if (dirs === void 0) return yield* Effect4.die("Missing scratch pool");
1405
+ if (dirs === void 0) return yield* Effect5.die("Missing scratch pool");
945
1406
  const neverBudgets = /* @__PURE__ */ new Map();
946
1407
  for (const mutant of input.state.pending) {
947
- if (mutant.genre !== "EffectNever" || neverBudgets.has(mutant.file)) continue;
948
- const measured = yield* Effect4.scoped(Effect4.gen(function* () {
1408
+ if (mutant.genre !== "EffectNever" || neverBudgets.has(mutant.file) || unreliableFor(input.state.baseline, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file).length > 0) continue;
1409
+ const measured = yield* Effect5.scoped(Effect5.gen(function* () {
949
1410
  const dir = yield* Pool.get(dirs);
950
1411
  return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs);
951
1412
  }));
952
1413
  if (measured.status === "failed" || measured.status === "timedOut") {
953
- return yield* new BaselineFailed({ exitCode: 1, output: measured.output });
1414
+ return yield* new BaselineFailed({ exitCode: 1, output: measured.output, command: measured.command });
954
1415
  }
955
1416
  neverBudgets.set(mutant.file, Math.max(config.neverTimeoutMs, Math.ceil(measured.durationMs * config.timeoutMultiplier)));
956
1417
  }
957
1418
  yield* Stream3.fromIterable(input.state.pending).pipe(
958
- Stream3.mapEffect((mutant) => Effect4.scoped(Effect4.gen(function* () {
1419
+ Stream3.mapEffect((mutant) => Effect5.scoped(Effect5.gen(function* () {
959
1420
  const viability = yield* source.checkViable(mutant);
960
1421
  if (!viability.viable) {
961
1422
  const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
@@ -963,20 +1424,29 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
963
1424
  yield* reporter.progress(result3);
964
1425
  return;
965
1426
  }
1427
+ const localFile = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
1428
+ const unreliable = unreliableFor(input.state.baseline, localFile);
1429
+ if (unreliable.length) {
1430
+ const result3 = { mutant, outcome: "unreliable", durationMs: 0, testCommand: input.state.baseline.testCommand, diagnostics: unreliable.map((issue) => issue.reason) };
1431
+ yield* input.record(result3);
1432
+ yield* reporter.progress(result3);
1433
+ return;
1434
+ }
966
1435
  const dir = yield* Pool.get(dirs);
967
- const run2 = yield* Effect4.acquireUseRelease(
1436
+ const run2 = yield* Effect5.acquireUseRelease(
968
1437
  dir.apply(mutant),
969
1438
  () => tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, mutant.genre === "EffectNever" ? neverBudgets.get(mutant.file) : input.state.timeoutMs),
970
1439
  // A dirty directory must never return to the pool, even on cancel.
971
- () => dir.revert(mutant).pipe(Effect4.orDie)
1440
+ () => dir.revert(mutant).pipe(Effect5.orDie)
972
1441
  );
1442
+ const selectedIssues = unreliableFor(input.state.baseline, localFile, run2.testFiles);
973
1443
  const result2 = {
974
1444
  mutant,
975
1445
  // A kill before collection proves nothing about whether tests noticed.
976
- outcome: run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
1446
+ outcome: selectedIssues.length ? "unreliable" : run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
977
1447
  durationMs: run2.durationMs,
978
1448
  testCommand: run2.command,
979
- diagnostics: [],
1449
+ diagnostics: selectedIssues.map((issue) => issue.reason),
980
1450
  ...run2.output === "" ? {} : { output: run2.output }
981
1451
  };
982
1452
  yield* input.record(result2);
@@ -986,12 +1456,12 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
986
1456
  );
987
1457
  })));
988
1458
  const reporting = createEffectLogic(({ input }) => capture(
989
- input.reported ? Effect4.void : reporter.write(report(input))
1459
+ input.reported ? Effect5.void : reporter.write(report(input))
990
1460
  ));
991
1461
  const machine = setupEffect({
992
1462
  schemas: {
993
1463
  context: types(),
994
- events: { CANCEL: Schema5.Struct({}), RESULT: Schema5.Struct({ result: MutantResult }) }
1464
+ events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }) }
995
1465
  },
996
1466
  actors: { copying, baselining, generating, testing, reporting }
997
1467
  }).createMachine({
@@ -1015,7 +1485,11 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
1015
1485
  baseline: { invoke: {
1016
1486
  src: "baselining",
1017
1487
  input: ({ context }) => context.pool,
1018
- onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: event.output.failure._tag === "BaselineFailed" ? "baselineFailed" : "failed", context: { ...context, failure: event.output.failure } }
1488
+ onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
1489
+ ...context,
1490
+ failure: event.output.failure,
1491
+ baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
1492
+ } }
1019
1493
  } },
1020
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 } } } },
1021
1495
  testing: { invoke: {
@@ -1049,54 +1523,53 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
1049
1523
  failure: Result.isFailure(event.output) ? event.output.failure : context.failure
1050
1524
  } })
1051
1525
  } },
1052
- baselineFailed: { type: "final" },
1053
1526
  failed: { type: "final" },
1054
1527
  done: { type: "final" }
1055
1528
  }
1056
1529
  });
1057
- const state = yield* Effect4.scoped(Effect4.gen(function* () {
1530
+ const state = yield* Effect5.scoped(Effect5.gen(function* () {
1058
1531
  const actor = yield* createEffectActor(machine);
1059
- return yield* join(actor).pipe(Effect4.orDie, Effect4.onInterrupt(() => Effect4.gen(function* () {
1532
+ return yield* join(actor).pipe(Effect5.orDie, Effect5.onInterrupt(() => Effect5.gen(function* () {
1060
1533
  yield* send(actor, { type: "CANCEL" });
1061
- yield* join(actor).pipe(Effect4.orDie);
1534
+ yield* join(actor).pipe(Effect5.orDie);
1062
1535
  })));
1063
1536
  }));
1064
1537
  if (state.failure !== void 0) return yield* state.failure;
1065
1538
  return report(state);
1066
- }, Effect4.scoped);
1539
+ }, Effect5.scoped);
1067
1540
 
1068
1541
  // packages/cli/src/bin.ts
1069
- import * as Effect8 from "effect/Effect";
1542
+ import * as Effect9 from "effect/Effect";
1070
1543
  import * as Layer5 from "effect/Layer";
1071
1544
  import * as Stream6 from "effect/Stream";
1072
1545
 
1073
1546
  // packages/cli/src/Command.ts
1074
- import * as Console2 from "effect/Console";
1075
- import * as Effect7 from "effect/Effect";
1547
+ import * as Console3 from "effect/Console";
1548
+ import * as Effect8 from "effect/Effect";
1076
1549
  import * as FileSystem9 from "effect/FileSystem";
1077
1550
  import * as Option from "effect/Option";
1078
1551
  import * as Path11 from "effect/Path";
1079
1552
  import * as Ref from "effect/Ref";
1080
- import * as Schema8 from "effect/Schema";
1553
+ import * as Schema10 from "effect/Schema";
1081
1554
  import * as Stream5 from "effect/Stream";
1082
1555
  import * as Command from "effect/cli/Command";
1083
1556
  import * as Flag from "effect/cli/Flag";
1084
1557
 
1085
1558
  // packages/cli/src/Diff.ts
1086
- import * as Effect5 from "effect/Effect";
1559
+ import * as Effect6 from "effect/Effect";
1087
1560
  import * as FileSystem5 from "effect/FileSystem";
1088
1561
  import * as Path7 from "effect/Path";
1089
- import * as Schema6 from "effect/Schema";
1562
+ import * as Schema8 from "effect/Schema";
1090
1563
  import * as Stream4 from "effect/Stream";
1091
- import * as ChildProcess2 from "effect/process/ChildProcess";
1092
- var DiffMismatch = class extends Schema6.TaggedError()("DiffMismatch", {
1093
- path: Schema6.String,
1094
- message: Schema6.String
1564
+ import * as ChildProcess3 from "effect/process/ChildProcess";
1565
+ var DiffMismatch = class extends Schema8.TaggedError()("DiffMismatch", {
1566
+ path: Schema8.String,
1567
+ message: Schema8.String
1095
1568
  }) {
1096
1569
  };
1097
- var parseDiff = (text, path) => Effect5.try({
1570
+ var parseDiff = (text, path) => Effect6.try({
1098
1571
  try: () => {
1099
- const fail4 = (message) => {
1572
+ const fail3 = (message) => {
1100
1573
  throw new DiffParseError({ path, message });
1101
1574
  };
1102
1575
  if (text === "") return [];
@@ -1108,12 +1581,12 @@ var parseDiff = (text, path) => Effect5.try({
1108
1581
  while (i < input.length) {
1109
1582
  const line = input[i++];
1110
1583
  if (line.startsWith("diff --git ") || /^(index |new file mode |deleted file mode |old mode |new mode |similarity index |rename from |rename to )/.test(line)) continue;
1111
- if (!line.startsWith("--- ")) fail4("Expected a unified diff file header");
1584
+ if (!line.startsWith("--- ")) fail3("Expected a unified diff file header");
1112
1585
  const next = input[i++];
1113
- if (!next?.startsWith("+++ ")) fail4("Missing new-side file header");
1586
+ if (!next?.startsWith("+++ ")) fail3("Missing new-side file header");
1114
1587
  const raw = next.slice(4).split(" ")[0];
1115
1588
  const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
1116
- if (typeof decoded !== "string") fail4("Invalid file path");
1589
+ if (typeof decoded !== "string") fail3("Invalid file path");
1117
1590
  const file = String(decoded).replace(/^b\//, "");
1118
1591
  const lines2 = [];
1119
1592
  let hunks = 0;
@@ -1121,22 +1594,22 @@ var parseDiff = (text, path) => Effect5.try({
1121
1594
  let previousOldEnd = 0;
1122
1595
  while (input[i]?.startsWith("@@")) {
1123
1596
  const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
1124
- if (!match2) fail4("Invalid hunk header");
1597
+ if (!match2) fail3("Invalid hunk header");
1125
1598
  let oldRemaining = Number(match2[2] ?? 1);
1126
1599
  let newRemaining = Number(match2[4] ?? 1);
1127
1600
  let newLine = Number(match2[3]);
1128
1601
  const oldStart = Number(match2[1]);
1129
1602
  const oldCount = oldRemaining;
1130
- if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail4("Hunk range is not a safe integer");
1131
- if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail4("Nonempty hunk cannot start at zero");
1132
- if (newLine < previousEnd || oldStart < previousOldEnd) fail4("Overlapping or unordered hunks");
1603
+ if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail3("Hunk range is not a safe integer");
1604
+ if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail3("Nonempty hunk cannot start at zero");
1605
+ if (newLine < previousEnd || oldStart < previousOldEnd) fail3("Overlapping or unordered hunks");
1133
1606
  let previousPrefix = "";
1134
1607
  const markNoNewline = () => {
1135
1608
  if (previousPrefix === "+" || previousPrefix === " ") {
1136
1609
  const last = lines2.at(-1);
1137
- if (last === void 0 || last.noNewline) fail4("Unexpected no-newline marker");
1610
+ if (last === void 0 || last.noNewline) fail3("Unexpected no-newline marker");
1138
1611
  lines2[lines2.length - 1] = { ...last, noNewline: true };
1139
- } else if (previousPrefix !== "-") fail4("Unexpected no-newline marker");
1612
+ } else if (previousPrefix !== "-") fail3("Unexpected no-newline marker");
1140
1613
  previousPrefix = "";
1141
1614
  };
1142
1615
  hunks++;
@@ -1146,15 +1619,15 @@ var parseDiff = (text, path) => Effect5.try({
1146
1619
  markNoNewline();
1147
1620
  continue;
1148
1621
  }
1149
- if (body === void 0) fail4("Truncated hunk");
1622
+ if (body === void 0) fail3("Truncated hunk");
1150
1623
  const prefix = body[0];
1151
1624
  if (prefix === " " || prefix === "-") oldRemaining--;
1152
1625
  if (prefix === " " || prefix === "+") {
1153
1626
  newRemaining--;
1154
1627
  lines2.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
1155
- } else if (prefix !== "-") fail4("Invalid hunk line");
1628
+ } else if (prefix !== "-") fail3("Invalid hunk line");
1156
1629
  previousPrefix = prefix;
1157
- if (oldRemaining < 0 || newRemaining < 0) fail4("Hunk count does not match its body");
1630
+ if (oldRemaining < 0 || newRemaining < 0) fail3("Hunk count does not match its body");
1158
1631
  }
1159
1632
  if (input[i] === "\") {
1160
1633
  markNoNewline();
@@ -1163,28 +1636,28 @@ var parseDiff = (text, path) => Effect5.try({
1163
1636
  previousEnd = newLine;
1164
1637
  previousOldEnd = oldStart + oldCount;
1165
1638
  }
1166
- if (hunks === 0) fail4("File has no hunks");
1639
+ if (hunks === 0) fail3("File has no hunks");
1167
1640
  sawFile = true;
1168
1641
  if (file !== "/dev/null") patches.push({ file, lines: lines2 });
1169
1642
  }
1170
- if (!sawFile) fail4("No unified diff found");
1643
+ if (!sawFile) fail3("No unified diff found");
1171
1644
  return patches;
1172
1645
  },
1173
- catch: (error2) => Schema6.is(DiffParseError)(error2) ? error2 : new DiffParseError({ path, message: String(error2) })
1646
+ catch: (error2) => Schema8.is(DiffParseError)(error2) ? error2 : new DiffParseError({ path, message: String(error2) })
1174
1647
  });
1175
- var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
1648
+ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
1176
1649
  const fs = yield* FileSystem5.FileSystem;
1177
1650
  const path = yield* Path7.Path;
1178
1651
  const diffPath = path.resolve(options.root, options.diffPath);
1179
- const text = yield* fs.readFileString(diffPath).pipe(Effect5.mapError((error2) => new DiffParseError({ path: diffPath, message: String(error2) })));
1652
+ const text = yield* fs.readFileString(diffPath).pipe(Effect6.mapError((error2) => new DiffParseError({ path: diffPath, message: String(error2) })));
1180
1653
  const patches = yield* parseDiff(text, diffPath);
1181
- const gitRoot = yield* Effect5.scoped(Effect5.gen(function* () {
1182
- const handle = yield* ChildProcess2.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
1183
- const [output, code] = yield* Effect5.all([Stream4.mkString(Stream4.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
1654
+ const gitRoot = yield* Effect6.scoped(Effect6.gen(function* () {
1655
+ const handle = yield* ChildProcess3.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
1656
+ const [output, code] = yield* Effect6.all([Stream4.mkString(Stream4.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
1184
1657
  if (Number(code) !== 0 || !output.trim()) return options.root;
1185
1658
  const physicalRoot = yield* fs.realPath(options.root);
1186
1659
  return path.resolve(options.root, path.relative(physicalRoot, output.trim()));
1187
- })).pipe(Effect5.catch(() => Effect5.succeed(options.root)));
1660
+ })).pipe(Effect6.catch(() => Effect6.succeed(options.root)));
1188
1661
  const changed = /* @__PURE__ */ new Map();
1189
1662
  for (const patch of patches) {
1190
1663
  const repositoryPath = path.resolve(gitRoot, patch.file);
@@ -1196,7 +1669,7 @@ var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
1196
1669
  return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
1197
1670
  }
1198
1671
  if (!(yield* fs.exists(candidate))) continue;
1199
- const current = yield* fs.readFileString(candidate).pipe(Effect5.mapError((error2) => new DiffMismatch({ path: patch.file, message: String(error2) })));
1672
+ const current = yield* fs.readFileString(candidate).pipe(Effect6.mapError((error2) => new DiffMismatch({ path: patch.file, message: String(error2) })));
1200
1673
  const lines2 = current.split("\n");
1201
1674
  const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
1202
1675
  if (patch.lines.every((line) => {
@@ -1212,15 +1685,18 @@ var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
1212
1685
  for (const line of patch.lines) if (line.added) added.add(line.number);
1213
1686
  changed.set(absolute, added);
1214
1687
  }
1215
- return options.mutants.filter((mutant) => {
1216
- const added = changed.get(path.resolve(options.root, mutant.file));
1217
- const end = mutant.span.end.line - (mutant.span.end.column === 1 ? 1 : 0);
1218
- return added !== void 0 && [...added].some((line) => line >= mutant.span.start.line && line <= end);
1219
- });
1688
+ return {
1689
+ mutants: options.mutants.filter((mutant) => {
1690
+ const added = changed.get(path.resolve(options.root, mutant.file));
1691
+ const end = mutant.span.end.line - (mutant.span.end.column === 1 ? 1 : 0);
1692
+ return added !== void 0 && [...added].some((line) => line >= mutant.span.start.line && line <= end);
1693
+ }),
1694
+ notMutated: options.notMutated.filter((item) => changed.has(path.resolve(options.root, item.file)))
1695
+ };
1220
1696
  });
1221
1697
 
1222
1698
  // packages/cli/src/ExitCode.ts
1223
- var reportExitCode = (report) => report.results.some((result2) => result2.outcome === "missed" || result2.outcome === "untested") ? 2 : report.results.some((result2) => result2.outcome === "timeout") ? 3 : 0;
1699
+ 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;
1224
1700
  var errorExitCode = (error2) => {
1225
1701
  switch (error2._tag) {
1226
1702
  case "BaselineFailed":
@@ -1229,6 +1705,7 @@ var errorExitCode = (error2) => {
1229
1705
  return 5;
1230
1706
  case "DiffParseError":
1231
1707
  return 6;
1708
+ case "ProgramLoadError":
1232
1709
  case "UsageError":
1233
1710
  case "ShowHelp":
1234
1711
  case "InvalidValue":
@@ -1242,12 +1719,12 @@ var errorExitCode = (error2) => {
1242
1719
 
1243
1720
  // packages/cli/src/Reporter.ts
1244
1721
  import * as Clock2 from "effect/Clock";
1245
- import * as Console from "effect/Console";
1246
- import * as Effect6 from "effect/Effect";
1722
+ import * as Console2 from "effect/Console";
1723
+ import * as Effect7 from "effect/Effect";
1247
1724
  import * as FileSystem7 from "effect/FileSystem";
1248
1725
  import * as Layer4 from "effect/Layer";
1249
1726
  import * as Path9 from "effect/Path";
1250
- import * as Schema7 from "effect/Schema";
1727
+ import * as Schema9 from "effect/Schema";
1251
1728
  import * as Semaphore from "effect/Semaphore";
1252
1729
 
1253
1730
  // packages/cli/src/UnifiedDiff.ts
@@ -1323,7 +1800,8 @@ var unifiedDiff = (original, modified, file) => {
1323
1800
  if (edit.sign !== "-") next++;
1324
1801
  }
1325
1802
  const changed = changes.flatMap((edit, index) => edit.sign === " " ? [] : [index]);
1326
- const output = [`--- ${JSON.stringify(`a/${file}`)}`, `+++ ${JSON.stringify(`b/${file}`)}`];
1803
+ const quotePath = (path) => /[\s"\\]/.test(path) ? JSON.stringify(path) : path;
1804
+ const output = [`--- ${quotePath(`a/${file}`)}`, `+++ ${quotePath(`b/${file}`)}`];
1327
1805
  for (let i = 0; i < changed.length; i++) {
1328
1806
  const start = Math.max(0, changed[i] - 3);
1329
1807
  let last = changed[i];
@@ -1343,13 +1821,13 @@ var shortType = (text) => {
1343
1821
  const line = text.replace(/\s+/g, " ");
1344
1822
  return line.length > 80 ? line.slice(0, 79) + "\u2026" : line;
1345
1823
  };
1346
- var outcomes = ["caught", "missed", "timeout", "unviable", "untested"];
1347
- var jsonReport = Schema7.encodeEffect(Schema7.fromJsonString(RunReport));
1824
+ var outcomes = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
1825
+ var jsonReport = Schema9.encodeEffect(Schema9.fromJsonString(RunReport));
1348
1826
  var logText = (result2) => [
1349
1827
  ..."output" in result2 && typeof result2.output === "string" ? [result2.output] : [],
1350
1828
  ...result2.diagnostics
1351
1829
  ].join("\n");
1352
- var makeReporter = Effect6.fn("makeReporter")(function* (options) {
1830
+ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1353
1831
  const fs = yield* FileSystem7.FileSystem;
1354
1832
  const path = yield* Path9.Path;
1355
1833
  const dir = path.resolve(options.root, options.outDir);
@@ -1364,7 +1842,7 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
1364
1842
  if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
1365
1843
  ids.add(mutant.id);
1366
1844
  }
1367
- yield* Effect6.gen(function* () {
1845
+ yield* Effect7.gen(function* () {
1368
1846
  const relative2 = path.relative(dir, path.resolve(options.root));
1369
1847
  if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
1370
1848
  return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
@@ -1379,81 +1857,86 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
1379
1857
  }
1380
1858
  yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
1381
1859
  yield* fs.makeDirectory(path.join(dir, "logs"), { recursive: true });
1382
- }).pipe(Effect6.mapError(writeError));
1383
- const encodedMutants = yield* Schema7.encodeEffect(Schema7.fromJsonString(Schema7.Array(Mutant)))(options.mutants).pipe(Effect6.mapError(writeError));
1384
- yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect6.mapError(writeError));
1385
- yield* Effect6.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect6.mapError(writeError));
1860
+ }).pipe(Effect7.mapError(writeError));
1861
+ const encodedMutants = yield* Schema9.encodeEffect(Schema9.fromJsonString(Schema9.Array(Mutant)))(options.mutants).pipe(Effect7.mapError(writeError));
1862
+ 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}
1864
+ `).join("")).pipe(Effect7.mapError(writeError));
1865
+ yield* Effect7.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect7.mapError(writeError));
1386
1866
  for (const mutant of options.mutants) {
1387
- const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect6.mapError(writeError));
1388
- yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(original, original.slice(0, mutant.replacement.startOffset) + mutant.replacement.text + original.slice(mutant.replacement.endOffset), path.relative(options.root, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))).pipe(Effect6.mapError(writeError));
1867
+ const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect7.mapError(writeError));
1868
+ yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(original, original.slice(0, mutant.replacement.startOffset) + mutant.replacement.text + original.slice(mutant.replacement.endOffset), path.relative(options.root, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))).pipe(Effect7.mapError(writeError));
1389
1869
  }
1390
- const writeLists = (items) => Effect6.forEach(outcomes, (outcome) => {
1870
+ const writeLists = (items) => Effect7.forEach(outcomes, (outcome) => {
1391
1871
  const lines2 = items.filter((result2) => result2.outcome === outcome).map((result2) => mutantLine(result2.mutant, options.root, path));
1392
1872
  return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines2.length === 0 ? "" : lines2.join("\n") + "\n");
1393
1873
  }, { discard: true });
1394
1874
  const service = Reporter.of({
1395
- progress: (result2) => semaphore.withPermit(Effect6.gen(function* () {
1875
+ progress: (result2) => semaphore.withPermit(Effect7.gen(function* () {
1396
1876
  results.push(result2);
1397
- yield* Console.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
1398
- yield* Effect6.gen(function* () {
1877
+ yield* Console2.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
1878
+ yield* Effect7.gen(function* () {
1399
1879
  if (!ids.has(result2.mutant.id)) return yield* writeError("Progress result does not belong to this report");
1400
1880
  yield* writeLists(results);
1401
1881
  yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2));
1402
- }).pipe(Effect6.catch((error2) => Effect6.gen(function* () {
1882
+ }).pipe(Effect7.catch((error2) => Effect7.gen(function* () {
1403
1883
  if (pendingError === void 0) {
1404
1884
  pendingError = writeError(error2);
1405
- yield* Console.warn(`Report write failed: ${pendingError.message}`);
1885
+ yield* Console2.warn(`Report write failed: ${pendingError.message}`);
1406
1886
  }
1407
1887
  })));
1408
1888
  })),
1409
- write: (report) => semaphore.withPermit(Effect6.gen(function* () {
1889
+ write: (report) => semaphore.withPermit(Effect7.gen(function* () {
1410
1890
  if (pendingError !== void 0) return yield* pendingError;
1411
- const encoded = yield* jsonReport(report).pipe(Effect6.mapError(writeError));
1412
- yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect6.mapError(writeError));
1413
- yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect6.mapError(writeError));
1414
- yield* writeLists(report.results).pipe(Effect6.mapError(writeError));
1891
+ const encoded = yield* jsonReport(report).pipe(Effect7.mapError(writeError));
1892
+ yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect7.mapError(writeError));
1893
+ yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect7.mapError(writeError));
1894
+ yield* writeLists(report.results).pipe(Effect7.mapError(writeError));
1415
1895
  for (const result2 of report.results) {
1416
1896
  if (!ids.has(result2.mutant.id)) return yield* writeError("Final result does not belong to this report");
1417
- yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect6.mapError(writeError));
1897
+ yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect7.mapError(writeError));
1418
1898
  }
1419
1899
  if (summarized) return;
1420
1900
  summarized = true;
1901
+ 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.");
1421
1902
  const elapsed = (yield* Clock2.currentTimeMillis) - started;
1422
- yield* Console.log(outcomes.map((outcome) => `${report.results.filter((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${(elapsed / 1e3).toFixed(2)}s`);
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`);
1423
1904
  }))
1424
1905
  });
1425
1906
  return service;
1426
1907
  });
1427
1908
 
1428
1909
  // packages/cli/src/Command.ts
1429
- var UsageError = class extends Schema8.TaggedError()("UsageError", { message: Schema8.String }) {
1910
+ var UsageError = class extends Schema10.TaggedError()("UsageError", { message: Schema10.String }) {
1430
1911
  };
1431
1912
  var flags = {
1432
- list: Flag.Boolean("list").pipe(Flag.withDefault(false)),
1433
- inDiff: Flag.String("in-diff").pipe(Flag.optional),
1434
- include: Flag.String("file").pipe(Flag.atLeast(0)),
1435
- exclude: Flag.String("exclude").pipe(Flag.atLeast(0)),
1436
- jobs: Flag.Int("jobs").pipe(Flag.optional),
1913
+ list: Flag.Boolean("list").pipe(Flag.withDefault(false), Flag.withDescription("List mutants and skipped function count without running tests")),
1914
+ inDiff: Flag.String("in-diff").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping this unified diff")),
1915
+ include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
1916
+ exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
1917
+ 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")),
1918
+ jobs: Flag.Int("jobs").pipe(Flag.optional, Flag.withDescription("Concurrent scratch/test workers; default 1")),
1437
1919
  timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds")),
1438
- timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional),
1920
+ timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional, Flag.withDescription("Baseline duration multiplier; default 5")),
1439
1921
  minimumTimeout: Flag.Finite("minimum-test-timeout").pipe(Flag.optional, Flag.withDescription("Minimum test timeout in seconds")),
1440
- output: Flag.String("output").pipe(Flag.withDefault("mutants.out")),
1441
- tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"))
1922
+ output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
1923
+ tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
1442
1924
  };
1443
- var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect7.gen(function* () {
1925
+ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect8.gen(function* () {
1444
1926
  const fs = yield* FileSystem9.FileSystem;
1445
1927
  const path = yield* Path11.Path;
1446
1928
  const root = path.resolve(options.root);
1447
1929
  const configPath = path.join(root, "mutants.config.json");
1448
1930
  const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
1449
- Effect7.flatMap(Schema8.decodeEffect(Schema8.fromJsonString(ConfigFile))),
1450
- Effect7.mapError((error2) => new UsageError({ message: `Invalid mutants.config.json: ${String(error2)}` }))
1931
+ Effect8.flatMap(Schema10.decodeEffect(Schema10.fromJsonString(ConfigFile))),
1932
+ Effect8.mapError((error2) => new UsageError({ message: `Invalid mutants.config.json: ${String(error2)}` }))
1451
1933
  ) : {};
1452
1934
  const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
1453
1935
  const inDiff = Option.getOrUndefined(input.inDiff);
1454
- const config = yield* Schema8.decodeEffect(RunConfig)({
1936
+ const config = yield* Schema10.decodeEffect(RunConfig)({
1455
1937
  root,
1456
1938
  tsconfig: input.tsconfig,
1939
+ exportedOnly: input.exportedOnly,
1457
1940
  include: input.include.length > 0 ? input.include : fileConfig.include ?? ["**/*.{ts,tsx}"],
1458
1941
  exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
1459
1942
  functionFilter: fileConfig.functionFilter ?? [],
@@ -1464,42 +1947,46 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
1464
1947
  minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
1465
1948
  neverTimeoutMs: 1e3,
1466
1949
  outDir: input.output
1467
- }).pipe(Effect7.mapError((error2) => new UsageError({ message: String(error2) })));
1950
+ }).pipe(Effect8.mapError((error2) => new UsageError({ message: String(error2) })));
1468
1951
  if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
1469
1952
  return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
1470
1953
  }
1471
1954
  const source = yield* MutantSource;
1472
1955
  const generated = yield* Stream5.runCollect(source.generate(config)).pipe(
1473
- Effect7.mapError((error2) => error2.reason === "selection" ? new UsageError({ message: error2.diagnostics.join("\n") }) : error2)
1956
+ Effect8.mapError((error2) => error2.reason === "selection" ? new UsageError({ message: error2.diagnostics.join("\n") }) : error2)
1474
1957
  );
1475
- const mutants = inDiff === void 0 ? generated : yield* selectInDiff({ root, diffPath: inDiff, mutants: generated });
1958
+ 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;
1476
1961
  if (input.list) {
1477
- for (const mutant of mutants) yield* Console2.log(mutantLine(mutant, config.root, path));
1962
+ for (const mutant of mutants) yield* Console3.log(mutantLine(mutant, config.root, path));
1478
1963
  const counts = /* @__PURE__ */ new Map();
1479
1964
  for (const mutant of mutants) {
1480
1965
  const file = path.relative(root, path.resolve(root, mutant.file));
1481
1966
  counts.set(file, (counts.get(file) ?? 0) + 1);
1482
1967
  }
1483
- for (const [file, count] of [...counts].sort(([a], [b]) => a.localeCompare(b))) yield* Console2.log(`${file}: ${count} mutants`);
1484
- yield* Console2.log(`${mutants.length} mutants total`);
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`);
1485
1970
  if (options.onExit !== void 0) yield* options.onExit(0);
1486
1971
  return;
1487
1972
  }
1488
- const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants });
1489
- const report = yield* options.run(config, mutants).pipe(Effect7.provideService(Reporter, reporter));
1973
+ const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated });
1974
+ const report = yield* options.run(config, mutants).pipe(Effect8.provideService(Reporter, reporter));
1490
1975
  yield* reporter.write(report);
1491
1976
  if (options.onExit !== void 0) yield* options.onExit(reportExitCode(report));
1492
1977
  }));
1493
- var runCli = Effect7.fn("runCli")(function* (options) {
1978
+ var runCli = Effect8.fn("runCli")(function* (options) {
1494
1979
  const code = yield* Ref.make(0);
1495
1980
  const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
1496
- yield* Command.runWith(command, { version: "0.1.2" })(options.args).pipe(
1497
- Effect7.catch((error2) => Effect7.gen(function* () {
1498
- yield* Console2.error(String(error2));
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));
1499
1986
  yield* Ref.set(code, errorExitCode(error2));
1500
1987
  })),
1501
- Effect7.catchDefect((defect) => Effect7.gen(function* () {
1502
- yield* Console2.error(`Internal error: ${String(defect)}`);
1988
+ Effect8.catchDefect((defect) => Effect8.gen(function* () {
1989
+ yield* Console3.error(`Internal error: ${String(defect)}`);
1503
1990
  yield* Ref.set(code, 70);
1504
1991
  }))
1505
1992
  );
@@ -1511,11 +1998,11 @@ var run = (config, mutants) => runMutants(config, Stream6.fromIterable(mutants))
1511
1998
  var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
1512
1999
  Layer5.provideMerge(NodeServices.layer)
1513
2000
  );
1514
- var main = Effect8.gen(function* () {
2001
+ var main = Effect9.gen(function* () {
1515
2002
  const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
1516
- yield* Effect8.sync(() => {
2003
+ yield* Effect9.sync(() => {
1517
2004
  process.exitCode = code;
1518
2005
  });
1519
- }).pipe(Effect8.provide(live));
2006
+ }).pipe(Effect9.provide(live));
1520
2007
  NodeRuntime.runMain(main);
1521
2008
  //# sourceMappingURL=bin.js.map