lie-detector 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,159 @@
1
+ import { parse } from "@babel/parser";
2
+ import traverseImport from "@babel/traverse";
3
+ const traverseModule = traverseImport;
4
+ const traverse = (traverseModule.default ?? traverseModule);
5
+ const PARSER_PLUGINS = [
6
+ "typescript",
7
+ "jsx",
8
+ "decorators-legacy",
9
+ "classProperties",
10
+ "topLevelAwait",
11
+ ];
12
+ const MESSAGES = {
13
+ "no-assertion": "Test has no expect() or assert() call.",
14
+ tautology: "Assertion compares a literal to itself.",
15
+ "self-comparison": "Assertion compares a value to itself.",
16
+ "snapshot-only": "Test only asserts a snapshot.",
17
+ "mock-only": "Test only asserts that a mock was called.",
18
+ "weak-assertion": "Test only asserts existence or truthiness.",
19
+ "empty-test": "Test body is empty.",
20
+ };
21
+ const SEVERITY = {
22
+ "no-assertion": "high",
23
+ tautology: "high",
24
+ "self-comparison": "high",
25
+ "snapshot-only": "medium",
26
+ "mock-only": "medium",
27
+ "weak-assertion": "medium",
28
+ "empty-test": "high",
29
+ };
30
+ function testNameFromCall(node) {
31
+ const first = node.arguments?.[0];
32
+ if (!first)
33
+ return "(anonymous)";
34
+ if (first.type === "StringLiteral")
35
+ return first.value;
36
+ if (first.type === "TemplateLiteral") {
37
+ return first.quasis.map((quasi) => quasi.value.cooked ?? "").join("#{}");
38
+ }
39
+ return "(anonymous)";
40
+ }
41
+ function isTestCall(node) {
42
+ if (node.type !== "CallExpression")
43
+ return false;
44
+ const callee = node.callee;
45
+ if (callee?.type === "Identifier") {
46
+ return callee.name === "test" || callee.name === "it";
47
+ }
48
+ if (callee?.type === "MemberExpression" && callee.object?.type === "Identifier") {
49
+ const base = callee.object.name;
50
+ const member = callee.property?.name;
51
+ return ((base === "test" || base === "it") &&
52
+ ["only", "skip", "todo", "concurrent", "failing"].includes(member));
53
+ }
54
+ return false;
55
+ }
56
+ function skipWhitespace(text, index) {
57
+ let i = index;
58
+ while (i < text.length && /\s/.test(text[i]))
59
+ i += 1;
60
+ return i;
61
+ }
62
+ function extractMatchers(text) {
63
+ const matchers = [];
64
+ let searchFrom = 0;
65
+ for (;;) {
66
+ const expectIndex = text.indexOf("expect", searchFrom);
67
+ if (expectIndex === -1)
68
+ break;
69
+ let cursor = skipWhitespace(text, expectIndex + "expect".length);
70
+ if (text[cursor] !== "(") {
71
+ searchFrom = expectIndex + "expect".length;
72
+ continue;
73
+ }
74
+ let depth = 0;
75
+ let end = cursor;
76
+ for (; end < text.length; end += 1) {
77
+ if (text[end] === "(")
78
+ depth += 1;
79
+ else if (text[end] === ")") {
80
+ depth -= 1;
81
+ if (depth === 0) {
82
+ end += 1;
83
+ break;
84
+ }
85
+ }
86
+ }
87
+ let matcherStart = skipWhitespace(text, end);
88
+ if (text.startsWith(".not", matcherStart)) {
89
+ matcherStart = skipWhitespace(text, matcherStart + ".not".length);
90
+ }
91
+ if (text[matcherStart] === ".") {
92
+ matcherStart = skipWhitespace(text, matcherStart + 1);
93
+ const match = /^[A-Za-z_$][\w$]*/.exec(text.slice(matcherStart));
94
+ if (match) {
95
+ const name = match[0];
96
+ const afterName = skipWhitespace(text, matcherStart + name.length);
97
+ if (text[afterName] === "(")
98
+ matchers.push(name);
99
+ }
100
+ }
101
+ searchFrom = end;
102
+ }
103
+ return matchers;
104
+ }
105
+ function analyzeBlock(blockText) {
106
+ const assertionCount = (blockText.match(/\b(?:expect|assert)\s*\(/g) ?? []).length;
107
+ if (assertionCount === 0)
108
+ return "no-assertion";
109
+ const matchers = extractMatchers(blockText);
110
+ if (/expect\s*\(\s*(true|false|-?\d+|["'][^"']*["'])\s*\)\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(\s*\1\s*\)/.test(blockText)) {
111
+ return "tautology";
112
+ }
113
+ if (/expect\s*\(\s*([A-Za-z_$][\w$]*)\s*\)\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(\s*\1\s*\)/.test(blockText)) {
114
+ return "self-comparison";
115
+ }
116
+ if (matchers.length > 0 &&
117
+ matchers.every((name) => name === "toMatchSnapshot" || name === "toMatchInlineSnapshot")) {
118
+ return "snapshot-only";
119
+ }
120
+ if (matchers.length > 0 && matchers.every((name) => name.startsWith("toHaveBeenCalled"))) {
121
+ return "mock-only";
122
+ }
123
+ if (matchers.length > 0 &&
124
+ matchers.every((name) => ["toBeDefined", "toBeTruthy", "toBeFalsy", "toBeNull"].includes(name))) {
125
+ return "weak-assertion";
126
+ }
127
+ return null;
128
+ }
129
+ export function quickScanTs(source, file = "input.test.ts") {
130
+ const ast = parse(source, {
131
+ sourceType: "unambiguous",
132
+ errorRecovery: true,
133
+ plugins: PARSER_PLUGINS,
134
+ });
135
+ const findings = [];
136
+ traverse(ast, {
137
+ CallExpression(path) {
138
+ if (!isTestCall(path.node))
139
+ return;
140
+ const callback = path.node.arguments?.[1];
141
+ if (!callback || (callback.type !== "FunctionExpression" && callback.type !== "ArrowFunctionExpression")) {
142
+ return;
143
+ }
144
+ const blockText = source.slice(callback.start ?? 0, callback.end ?? 0);
145
+ const pattern = analyzeBlock(blockText);
146
+ if (!pattern)
147
+ return;
148
+ findings.push({
149
+ file,
150
+ line: path.node.loc?.start.line ?? 1,
151
+ testName: testNameFromCall(path.node),
152
+ pattern,
153
+ message: MESSAGES[pattern],
154
+ severity: SEVERITY[pattern],
155
+ });
156
+ },
157
+ });
158
+ return findings;
159
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ function percentage(value) {
4
+ if (typeof value === "number" && Number.isFinite(value))
5
+ return value;
6
+ if (typeof value === "string") {
7
+ const parsed = Number.parseFloat(value);
8
+ return Number.isFinite(parsed) ? parsed : null;
9
+ }
10
+ return null;
11
+ }
12
+ function readJson(filePath) {
13
+ try {
14
+ return JSON.parse(readFileSync(filePath, "utf8"));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export function readCoverage(root) {
21
+ const candidates = [
22
+ "coverage/coverage-summary.json",
23
+ "coverage-summary.json",
24
+ "coverage.json",
25
+ "coverage/coverage.json",
26
+ ];
27
+ for (const relativePath of candidates) {
28
+ const filePath = join(root, relativePath);
29
+ if (!existsSync(filePath))
30
+ continue;
31
+ const data = readJson(filePath);
32
+ if (!data || typeof data !== "object")
33
+ continue;
34
+ const record = data;
35
+ const istanbulTotal = record.total;
36
+ if (istanbulTotal && typeof istanbulTotal === "object") {
37
+ const percent = percentage(istanbulTotal.lines?.pct) ??
38
+ percentage(istanbulTotal.statements?.pct) ??
39
+ percentage(istanbulTotal.branches?.pct) ??
40
+ percentage(istanbulTotal.functions?.pct);
41
+ if (percent !== null)
42
+ return { percent, source: relativePath };
43
+ }
44
+ const pythonTotal = record.totals;
45
+ if (pythonTotal && typeof pythonTotal === "object") {
46
+ const percent = percentage(pythonTotal.percent_covered) ??
47
+ percentage(pythonTotal.percent_covered_display);
48
+ if (percent !== null)
49
+ return { percent, source: relativePath };
50
+ }
51
+ }
52
+ return { percent: null, source: null };
53
+ }
@@ -0,0 +1,72 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { renderJson } from "./json.js";
4
+ import { renderMarkdown } from "./markdown.js";
5
+ export { readCoverage } from "./coverage.js";
6
+ export { renderJson } from "./json.js";
7
+ export { renderMarkdown } from "./markdown.js";
8
+ export { renderTerminal } from "./terminal.js";
9
+ const VERSION = "0.1.0";
10
+ function round(value) {
11
+ return Math.round(value * 10) / 10;
12
+ }
13
+ function buildWeakestTests(input) {
14
+ const groups = new Map();
15
+ for (const finding of input.quickFindings) {
16
+ const key = `${finding.file}:${finding.testName}`;
17
+ const current = groups.get(key);
18
+ if (current) {
19
+ current.findings += 1;
20
+ if (!current.patterns.includes(finding.pattern))
21
+ current.patterns.push(finding.pattern);
22
+ }
23
+ else {
24
+ groups.set(key, {
25
+ file: finding.file,
26
+ line: finding.line,
27
+ testName: finding.testName,
28
+ findings: 1,
29
+ patterns: [finding.pattern],
30
+ });
31
+ }
32
+ }
33
+ return [...groups.values()]
34
+ .sort((a, b) => b.findings - a.findings || a.file.localeCompare(b.file))
35
+ .slice(0, 10);
36
+ }
37
+ export function buildReport(input) {
38
+ const killed = input.mutants.filter((result) => result.status === "killed" || result.status === "timeout").length;
39
+ const survived = input.mutants.filter((result) => result.status === "survived").length;
40
+ const timeout = input.mutants.filter((result) => result.status === "timeout").length;
41
+ const error = input.mutants.filter((result) => result.status === "error").length;
42
+ const total = input.mutants.length;
43
+ return {
44
+ ...input,
45
+ version: VERSION,
46
+ generatedAt: new Date().toISOString(),
47
+ totals: {
48
+ total,
49
+ killed,
50
+ survived,
51
+ timeout,
52
+ error,
53
+ mutationScore: total > 0 ? round((killed / total) * 100) : null,
54
+ coveragePercent: input.coverage.percent,
55
+ quickFindings: input.quickFindings.length,
56
+ },
57
+ weakestTests: buildWeakestTests(input),
58
+ };
59
+ }
60
+ export function writeReport(report, outputDir) {
61
+ mkdirSync(outputDir, { recursive: true });
62
+ const markdownPath = join(outputDir, "report.md");
63
+ const jsonPath = join(outputDir, "report.json");
64
+ writeFileSync(markdownPath, renderMarkdown(report), "utf8");
65
+ writeFileSync(jsonPath, renderJson(report), "utf8");
66
+ return { markdown: markdownPath, json: jsonPath };
67
+ }
68
+ export function buildAndWrite(input, outputDir) {
69
+ const report = buildReport(input);
70
+ const paths = writeReport(report, outputDir);
71
+ return { report, ...paths };
72
+ }
@@ -0,0 +1,3 @@
1
+ export function renderJson(report) {
2
+ return `${JSON.stringify(report, null, 2)}\n`;
3
+ }
@@ -0,0 +1,128 @@
1
+ function formatPercent(value) {
2
+ if (value === null)
3
+ return "n/a";
4
+ return Number.isInteger(value) ? `${value}%` : `${value.toFixed(1)}%`;
5
+ }
6
+ function escapeCell(value) {
7
+ return value.replaceAll("|", "\\|").replaceAll("\n", " ");
8
+ }
9
+ function suggestedSkeleton(report, survivor) {
10
+ const location = survivor ? `${survivor.mutant.file}:${survivor.mutant.line}` : "the changed behavior";
11
+ if (report.language === "py") {
12
+ return [
13
+ "```python",
14
+ "def test_covers_changed_behavior():",
15
+ " # Arrange: build the smallest input that reaches the changed branch.",
16
+ " result = call_the_function(...)",
17
+ "",
18
+ " # Assert the actual value, not just that the call happened.",
19
+ " assert result == expected",
20
+ "```",
21
+ `Replace the placeholder with a real assertion for \`${location}\`.`,
22
+ ].join("\n");
23
+ }
24
+ return [
25
+ "```ts",
26
+ 'it("covers changed behavior", () => {',
27
+ " // Arrange: build the smallest input that reaches the changed branch.",
28
+ " const result = callTheFunction(...);",
29
+ "",
30
+ " // Assert the actual value, not just that the call happened.",
31
+ " expect(result).toBe(expected);",
32
+ "});",
33
+ "```",
34
+ `Replace the placeholder with a real assertion for \`${location}\`.`,
35
+ ].join("\n");
36
+ }
37
+ export function renderMarkdown(report) {
38
+ const survivors = report.mutants.filter((result) => result.status === "survived");
39
+ const lines = [];
40
+ lines.push("# Lie Detector Report");
41
+ lines.push("");
42
+ lines.push(`**Mode:** ${report.mode} · **Language:** ${report.language} · **Base:** ${report.base ?? (report.usedAll ? "all files" : "working tree")}`);
43
+ lines.push(`**Generated:** ${report.generatedAt}`);
44
+ lines.push(`**Duration:** ${(report.durationMs / 1000).toFixed(2)}s`);
45
+ if (report.testCommand)
46
+ lines.push(`**Test command:** \`${report.testCommand}\``);
47
+ lines.push("");
48
+ lines.push("## Summary");
49
+ lines.push("");
50
+ lines.push("| Metric | Value |");
51
+ lines.push("| --- | --- |");
52
+ lines.push(`| Coverage | ${formatPercent(report.totals.coveragePercent)} |`);
53
+ lines.push(`| Mutation score | ${formatPercent(report.totals.mutationScore)} (${report.totals.killed}/${report.totals.total} killed) |`);
54
+ lines.push(`| Mutants | ${report.totals.total} total · ${report.totals.killed} killed · ${report.totals.survived} survived · ${report.totals.timeout} timeout · ${report.totals.error} error |`);
55
+ lines.push(`| Quick findings | ${report.totals.quickFindings} |`);
56
+ lines.push(`| Files analyzed | ${report.files.length} |`);
57
+ lines.push("");
58
+ if (report.totals.coveragePercent !== null &&
59
+ report.totals.mutationScore !== null &&
60
+ report.totals.coveragePercent - report.totals.mutationScore >= 30) {
61
+ lines.push(`> Coverage says ${formatPercent(report.totals.coveragePercent)}, but mutation score is ${formatPercent(report.totals.mutationScore)}. The tests execute code without verifying enough of its behavior.`);
62
+ lines.push("");
63
+ }
64
+ lines.push("## Survived mutants");
65
+ lines.push("");
66
+ if (survivors.length === 0) {
67
+ lines.push("No survived mutants. Either the tests are strong or no mutants were generated.");
68
+ lines.push("");
69
+ }
70
+ else {
71
+ for (const result of survivors) {
72
+ const mutant = result.mutant;
73
+ lines.push(`### \`${mutant.file}:${mutant.line}\``);
74
+ lines.push("");
75
+ lines.push(`- Operator: \`${mutant.operator}\``);
76
+ lines.push(`- Status: ${result.status}`);
77
+ lines.push("");
78
+ lines.push("```diff");
79
+ lines.push(`- ${mutant.original}`);
80
+ lines.push(`+ ${mutant.replacement}`);
81
+ lines.push("```");
82
+ lines.push("");
83
+ }
84
+ }
85
+ lines.push("## Quick findings");
86
+ lines.push("");
87
+ if (report.quickFindings.length === 0) {
88
+ lines.push("No static test-quality findings.");
89
+ lines.push("");
90
+ }
91
+ else {
92
+ lines.push("| File | Line | Test | Pattern | Severity |");
93
+ lines.push("| --- | ---: | --- | --- | --- |");
94
+ for (const finding of report.quickFindings.slice(0, 50)) {
95
+ lines.push(`| ${escapeCell(finding.file)} | ${finding.line} | ${escapeCell(finding.testName)} | ${finding.pattern} | ${finding.severity} |`);
96
+ }
97
+ if (report.quickFindings.length > 50) {
98
+ lines.push(`| … | | ${report.quickFindings.length - 50} more | | |`);
99
+ }
100
+ lines.push("");
101
+ }
102
+ lines.push("## Weakest tests");
103
+ lines.push("");
104
+ if (report.weakestTests.length === 0) {
105
+ lines.push("No test-level findings to rank.");
106
+ lines.push("");
107
+ }
108
+ else {
109
+ lines.push("| Test | File | Findings | Patterns |");
110
+ lines.push("| --- | --- | ---: | --- |");
111
+ for (const test of report.weakestTests) {
112
+ lines.push(`| ${escapeCell(test.testName)} | ${escapeCell(test.file)}:${test.line} | ${test.findings} | ${test.patterns.join(", ")} |`);
113
+ }
114
+ lines.push("");
115
+ }
116
+ lines.push("## Suggested test skeleton");
117
+ lines.push("");
118
+ lines.push(suggestedSkeleton(report, survivors[0]));
119
+ lines.push("");
120
+ lines.push("## Files");
121
+ lines.push("");
122
+ for (const file of report.files)
123
+ lines.push(`- \`${file}\``);
124
+ lines.push("");
125
+ lines.push(`Generated by lie-detector v${report.version}. Local-first; no source code left the machine.`);
126
+ lines.push("");
127
+ return lines.join("\n");
128
+ }
@@ -0,0 +1,35 @@
1
+ const colors = {
2
+ bold: (value) => `\u001b[1m${value}\u001b[0m`,
3
+ dim: (value) => `\u001b[2m${value}\u001b[0m`,
4
+ green: (value) => `\u001b[32m${value}\u001b[0m`,
5
+ yellow: (value) => `\u001b[33m${value}\u001b[0m`,
6
+ red: (value) => `\u001b[31m${value}\u001b[0m`,
7
+ cyan: (value) => `\u001b[36m${value}\u001b[0m`,
8
+ };
9
+ function pct(value) {
10
+ if (value === null)
11
+ return "n/a";
12
+ return Number.isInteger(value) ? `${value}%` : `${value.toFixed(1)}%`;
13
+ }
14
+ function scoreColor(score) {
15
+ if (score === null)
16
+ return colors.dim;
17
+ if (score >= 70)
18
+ return colors.green;
19
+ if (score >= 40)
20
+ return colors.yellow;
21
+ return colors.red;
22
+ }
23
+ export function renderTerminal(report) {
24
+ const color = scoreColor(report.totals.mutationScore);
25
+ const lines = [];
26
+ lines.push("");
27
+ lines.push(colors.bold("Lie Detector") + colors.dim(` — ${report.mode} · ${report.language}`));
28
+ lines.push(`${colors.cyan("Coverage")} ${pct(report.totals.coveragePercent)} ${colors.cyan("Mutation")} ${color(pct(report.totals.mutationScore))} ${colors.dim(`(${report.totals.killed}/${report.totals.total} killed)`)}`);
29
+ lines.push(`${colors.dim("Survived")} ${report.totals.survived} ${colors.dim("Timeout")} ${report.totals.timeout} ${colors.dim("Quick findings")} ${report.totals.quickFindings}`);
30
+ lines.push(colors.dim(`Duration ${(report.durationMs / 1000).toFixed(2)}s`));
31
+ lines.push("");
32
+ lines.push(colors.dim("Reports: .lie-detector/report.md, .lie-detector/report.json"));
33
+ lines.push("");
34
+ return lines.join("\n");
35
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { basename, join, resolve } from "node:path";
4
+ export class RestoreManager {
5
+ backupDir;
6
+ entries = new Map();
7
+ handlersInstalled = false;
8
+ constructor(backupDir) {
9
+ this.backupDir = backupDir;
10
+ }
11
+ handleSignal = () => {
12
+ this.restoreAll();
13
+ this.removeSignalHandlers();
14
+ process.exit(130);
15
+ };
16
+ backup(filePath) {
17
+ const absolute = resolve(filePath);
18
+ if (this.entries.has(absolute))
19
+ return;
20
+ const original = readFileSync(absolute, "utf8");
21
+ mkdirSync(this.backupDir, { recursive: true });
22
+ let backupPath = join(this.backupDir, `${basename(absolute)}.bak`);
23
+ if (existsSync(backupPath) && readFileSync(backupPath, "utf8") !== original) {
24
+ const hash = createHash("sha1").update(absolute).digest("hex").slice(0, 8);
25
+ backupPath = join(this.backupDir, `${basename(absolute)}.${hash}.bak`);
26
+ }
27
+ writeFileSync(backupPath, original, "utf8");
28
+ this.entries.set(absolute, { filePath: absolute, original, backupPath });
29
+ }
30
+ restore(filePath) {
31
+ const entry = this.entries.get(resolve(filePath));
32
+ if (!entry)
33
+ return;
34
+ writeFileSync(entry.filePath, entry.original, "utf8");
35
+ }
36
+ restoreAll() {
37
+ for (const entry of this.entries.values()) {
38
+ writeFileSync(entry.filePath, entry.original, "utf8");
39
+ }
40
+ }
41
+ installSignalHandlers() {
42
+ if (this.handlersInstalled)
43
+ return;
44
+ process.once("SIGINT", this.handleSignal);
45
+ process.once("SIGTERM", this.handleSignal);
46
+ this.handlersInstalled = true;
47
+ }
48
+ removeSignalHandlers() {
49
+ if (!this.handlersInstalled)
50
+ return;
51
+ process.removeListener("SIGINT", this.handleSignal);
52
+ process.removeListener("SIGTERM", this.handleSignal);
53
+ this.handlersInstalled = false;
54
+ }
55
+ dispose() {
56
+ this.restoreAll();
57
+ this.removeSignalHandlers();
58
+ this.entries.clear();
59
+ }
60
+ get backups() {
61
+ return [...this.entries.values()];
62
+ }
63
+ }
package/dist/runner.js ADDED
@@ -0,0 +1,133 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { RestoreManager } from "./restore.js";
5
+ function truncate(value, limit = 4_000) {
6
+ if (!value)
7
+ return "";
8
+ const trimmed = value.trim();
9
+ return trimmed.length <= limit ? trimmed : `${trimmed.slice(0, limit)}\n…`;
10
+ }
11
+ function findUp(start, name) {
12
+ let current = resolve(start);
13
+ for (;;) {
14
+ const candidate = join(current, name);
15
+ if (existsSync(candidate))
16
+ return candidate;
17
+ const parent = dirname(current);
18
+ if (parent === current)
19
+ return null;
20
+ current = parent;
21
+ }
22
+ }
23
+ function testEnv(cwd, extraBin) {
24
+ const bins = [
25
+ extraBin,
26
+ findUp(cwd, "node_modules/.bin"),
27
+ join(cwd, "node_modules", ".bin"),
28
+ ].filter((value) => Boolean(value));
29
+ return {
30
+ ...process.env,
31
+ PATH: [...bins, process.env.PATH ?? ""].filter(Boolean).join(delimiter),
32
+ };
33
+ }
34
+ export function detectTestCommand(cwd, lang) {
35
+ if (lang === "py") {
36
+ return "python3 -m pytest -q";
37
+ }
38
+ const packageJsonPath = findUp(cwd, "package.json");
39
+ if (packageJsonPath) {
40
+ try {
41
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
42
+ if (packageJson.scripts?.test)
43
+ return "npm test";
44
+ }
45
+ catch {
46
+ // Fall through to config detection.
47
+ }
48
+ }
49
+ for (const config of ["vitest.config.ts", "vitest.config.js", "vitest.config.mjs"]) {
50
+ if (findUp(cwd, config)) {
51
+ const bin = findUp(cwd, "node_modules/.bin/vitest");
52
+ return bin ? `"${bin}" run` : "npx --no-install vitest run";
53
+ }
54
+ }
55
+ for (const config of ["jest.config.js", "jest.config.ts", "jest.config.cjs"]) {
56
+ if (findUp(cwd, config)) {
57
+ const bin = findUp(cwd, "node_modules/.bin/jest");
58
+ return bin ? `"${bin}" --runInBand` : "npx --no-install jest --runInBand";
59
+ }
60
+ }
61
+ throw new Error("Could not detect a test command. Add a package.json test script or pass --test-cmd.");
62
+ }
63
+ function resolveMutantPath(cwd, file) {
64
+ return isAbsolute(file) ? file : join(cwd, file);
65
+ }
66
+ export function runMutants(mutants, options) {
67
+ const cwd = resolve(options.cwd);
68
+ const manager = options.restoreManager ?? new RestoreManager(join(cwd, ".lie-detector", "backup"));
69
+ const timeoutMs = options.timeoutMs ?? 30_000;
70
+ const selected = options.maxMutants && options.maxMutants > 0
71
+ ? mutants.slice(0, options.maxMutants)
72
+ : mutants;
73
+ const results = [];
74
+ const env = testEnv(cwd);
75
+ for (const [index, mutant] of selected.entries()) {
76
+ const filePath = resolveMutantPath(cwd, mutant.file);
77
+ const started = Date.now();
78
+ try {
79
+ manager.backup(filePath);
80
+ writeFileSync(filePath, mutant.mutatedSource, "utf8");
81
+ const child = spawnSync(options.testCommand, {
82
+ cwd,
83
+ shell: true,
84
+ timeout: timeoutMs,
85
+ encoding: "utf8",
86
+ env,
87
+ maxBuffer: 10 * 1024 * 1024,
88
+ });
89
+ const timedOut = child.error?.code === "ETIMEDOUT" ||
90
+ (child.status === null && child.signal === "SIGTERM");
91
+ let status;
92
+ if (timedOut)
93
+ status = "timeout";
94
+ else if (child.status === 0)
95
+ status = "survived";
96
+ else
97
+ status = "killed";
98
+ const result = {
99
+ mutant,
100
+ status,
101
+ durationMs: Date.now() - started,
102
+ exitCode: child.status,
103
+ signal: child.signal,
104
+ stdout: truncate(child.stdout),
105
+ stderr: truncate(child.stderr),
106
+ error: child.error?.message,
107
+ };
108
+ results.push(result);
109
+ options.onProgress?.(result, index, selected.length);
110
+ }
111
+ catch (error) {
112
+ const result = {
113
+ mutant,
114
+ status: "error",
115
+ durationMs: Date.now() - started,
116
+ exitCode: null,
117
+ signal: null,
118
+ stdout: "",
119
+ stderr: "",
120
+ error: error instanceof Error ? error.message : String(error),
121
+ };
122
+ results.push(result);
123
+ options.onProgress?.(result, index, selected.length);
124
+ }
125
+ finally {
126
+ manager.restore(filePath);
127
+ }
128
+ }
129
+ // A final safety net: never leave a mutated file behind, even if the loop
130
+ // was interrupted between backup and restore.
131
+ manager.restoreAll();
132
+ return results;
133
+ }