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.
package/dist/diff.js ADDED
@@ -0,0 +1,250 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { join, relative, sep } from "node:path";
4
+ const NOISE_DIRS = new Set([
5
+ "node_modules",
6
+ ".git",
7
+ "dist",
8
+ "coverage",
9
+ ".lie-detector",
10
+ ".superpowers",
11
+ "__pycache__",
12
+ ".pytest_cache",
13
+ ".venv",
14
+ "venv",
15
+ "build",
16
+ ".mypy_cache",
17
+ ".ruff_cache",
18
+ ]);
19
+ function git(cwd, args) {
20
+ try {
21
+ return execFileSync("git", args, {
22
+ cwd,
23
+ encoding: "utf8",
24
+ stdio: ["ignore", "pipe", "ignore"],
25
+ }).trim();
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ function hasHead(cwd) {
32
+ return git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"]) !== null;
33
+ }
34
+ export function resolveBase(cwd, explicit) {
35
+ if (explicit)
36
+ return explicit;
37
+ for (const candidate of ["origin/main", "origin/master"]) {
38
+ const base = git(cwd, ["merge-base", candidate, "HEAD"]);
39
+ if (base)
40
+ return base;
41
+ }
42
+ if (git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD~1"])) {
43
+ return "HEAD~1";
44
+ }
45
+ // A repository with a single commit has no HEAD~1. Diffing against HEAD
46
+ // still isolates uncommitted work, which is the useful default.
47
+ if (git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"])) {
48
+ return "HEAD";
49
+ }
50
+ return null;
51
+ }
52
+ export function isTestFile(filePath) {
53
+ const p = filePath.replaceAll("\\", "/");
54
+ if (/(^|\/)(__tests__|tests?)\//.test(p))
55
+ return true;
56
+ if (/\.(test|spec)\.[cm]?[jt]sx?$/.test(p))
57
+ return true;
58
+ if (/(^|\/)test_.*\.py$/.test(p))
59
+ return true;
60
+ if (/_test\.py$/.test(p))
61
+ return true;
62
+ return false;
63
+ }
64
+ function normalizeDiffPath(raw) {
65
+ let p = raw.trim();
66
+ if (p === "/dev/null")
67
+ return null;
68
+ if (p.startsWith('"') && p.endsWith('"'))
69
+ p = p.slice(1, -1);
70
+ p = p.replace(/^[ab]\//, "");
71
+ p = p.replace(/^\.\//, "");
72
+ return p || null;
73
+ }
74
+ export function parseUnifiedDiff(diffText) {
75
+ const files = new Map();
76
+ let current = null;
77
+ let newLine = 0;
78
+ for (const line of diffText.split(/\r?\n/)) {
79
+ if (line.startsWith("+++ ")) {
80
+ const path = normalizeDiffPath(line.slice(4));
81
+ if (!path) {
82
+ current = null;
83
+ continue;
84
+ }
85
+ current = files.get(path) ?? {
86
+ path,
87
+ lines: new Set(),
88
+ isTest: isTestFile(path),
89
+ };
90
+ files.set(path, current);
91
+ continue;
92
+ }
93
+ if (line.startsWith("@@ ")) {
94
+ const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
95
+ if (match)
96
+ newLine = Number.parseInt(match[1], 10);
97
+ continue;
98
+ }
99
+ if (!current)
100
+ continue;
101
+ if (line.startsWith("+") && !line.startsWith("+++")) {
102
+ current.lines.add(newLine);
103
+ newLine += 1;
104
+ }
105
+ else if (line.startsWith("-") && !line.startsWith("---")) {
106
+ // Deleted line: does not advance the new-file line counter.
107
+ }
108
+ else if (line.startsWith(" ")) {
109
+ newLine += 1;
110
+ }
111
+ }
112
+ return [...files.values()].filter((file) => file.lines.size > 0);
113
+ }
114
+ function readAllLines(filePath) {
115
+ const content = readFileSync(filePath, "utf8");
116
+ const parts = content.split(/\r?\n/);
117
+ if (parts.length > 0 && parts[parts.length - 1] === "")
118
+ parts.pop();
119
+ const lines = new Set();
120
+ for (let i = 1; i <= parts.length; i += 1)
121
+ lines.add(i);
122
+ return lines;
123
+ }
124
+ function listUntracked(cwd) {
125
+ const out = git(cwd, ["ls-files", "--others", "--exclude-standard", "--", "."]);
126
+ if (!out)
127
+ return [];
128
+ return out
129
+ .split(/\r?\n/)
130
+ .map((line) => line.trim())
131
+ .filter(Boolean)
132
+ .map((p) => p.replace(/^\.\//, ""));
133
+ }
134
+ export function getChangedFiles(cwd, base) {
135
+ const files = new Map();
136
+ const diffBase = base ?? (hasHead(cwd) ? "HEAD" : null);
137
+ if (diffBase) {
138
+ const diff = git(cwd, ["diff", "--relative", "--unified=0", "--no-color", diffBase, "--", "."]);
139
+ if (diff) {
140
+ for (const file of parseUnifiedDiff(diff))
141
+ files.set(file.path, file);
142
+ }
143
+ }
144
+ for (const path of listUntracked(cwd)) {
145
+ const fullPath = join(cwd, path);
146
+ if (!existsSync(fullPath) || !statSync(fullPath).isFile())
147
+ continue;
148
+ const existing = files.get(path);
149
+ if (existing) {
150
+ for (const line of readAllLines(fullPath))
151
+ existing.lines.add(line);
152
+ }
153
+ else {
154
+ files.set(path, {
155
+ path,
156
+ lines: readAllLines(fullPath),
157
+ isTest: isTestFile(path),
158
+ });
159
+ }
160
+ }
161
+ return [...files.values()].sort((a, b) => a.path.localeCompare(b.path));
162
+ }
163
+ function hasSupportedExtension(filePath, lang) {
164
+ if (lang === "py")
165
+ return filePath.endsWith(".py");
166
+ if (filePath.endsWith(".d.ts"))
167
+ return false;
168
+ if (/^(vitest|vite|jest|webpack|rollup|tsup|eslint|prettier|playwright)\.config\./.test(filePath)) {
169
+ return false;
170
+ }
171
+ if (lang === "ts") {
172
+ return /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(filePath);
173
+ }
174
+ return filePath.endsWith(".py") || /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(filePath);
175
+ }
176
+ function walk(cwd, dir, lang, out) {
177
+ let entries;
178
+ try {
179
+ entries = readdirSync(dir, { withFileTypes: true });
180
+ }
181
+ catch {
182
+ return;
183
+ }
184
+ for (const entry of entries) {
185
+ if (entry.name.startsWith(".") && entry.name !== ".claude") {
186
+ if (NOISE_DIRS.has(entry.name))
187
+ continue;
188
+ }
189
+ if (NOISE_DIRS.has(entry.name))
190
+ continue;
191
+ const full = join(dir, entry.name);
192
+ if (entry.isDirectory()) {
193
+ walk(cwd, full, lang, out);
194
+ }
195
+ else if (entry.isFile() && hasSupportedExtension(entry.name, lang)) {
196
+ out.push(relative(cwd, full).split(sep).join("/"));
197
+ }
198
+ }
199
+ }
200
+ export function collectAllFiles(cwd, lang) {
201
+ const paths = [];
202
+ walk(cwd, cwd, lang, paths);
203
+ return paths.sort().map((path) => {
204
+ const fullPath = join(cwd, path);
205
+ return {
206
+ path,
207
+ lines: readAllLines(fullPath),
208
+ isTest: isTestFile(path),
209
+ };
210
+ });
211
+ }
212
+ function detectLanguage(files) {
213
+ let ts = 0;
214
+ let py = 0;
215
+ for (const file of files) {
216
+ if (file.path.endsWith(".py"))
217
+ py += 1;
218
+ else
219
+ ts += 1;
220
+ }
221
+ return py > 0 && ts === 0 ? "py" : "ts";
222
+ }
223
+ export function resolveDiff(cwd, options = {}) {
224
+ const lang = options.lang ?? "auto";
225
+ const base = options.all ? null : resolveBase(cwd, options.base);
226
+ const noHistory = !hasHead(cwd);
227
+ if (options.all || (base === null && noHistory)) {
228
+ const files = collectAllFiles(cwd, lang);
229
+ return {
230
+ base: null,
231
+ usedAll: true,
232
+ files,
233
+ sourceFiles: files.filter((file) => !file.isTest),
234
+ testFiles: files.filter((file) => file.isTest),
235
+ };
236
+ }
237
+ const files = getChangedFiles(cwd, base);
238
+ return {
239
+ base,
240
+ usedAll: false,
241
+ files,
242
+ sourceFiles: files.filter((file) => !file.isTest),
243
+ testFiles: files.filter((file) => file.isTest),
244
+ };
245
+ }
246
+ export function resolveLanguage(files, requested = "auto") {
247
+ if (requested !== "auto")
248
+ return requested;
249
+ return detectLanguage(files);
250
+ }
@@ -0,0 +1,35 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ export function pythonMutatorPath() {
5
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../../scripts/py/mutate.py");
6
+ }
7
+ export function mutatePy(filePath, options = {}) {
8
+ const cwd = options.cwd ?? process.cwd();
9
+ const absolutePath = isAbsolute(filePath) ? filePath : join(cwd, filePath);
10
+ const args = [pythonMutatorPath(), "--file", absolutePath];
11
+ if (options.lines && options.lines.size > 0) {
12
+ args.push("--lines", [...options.lines].sort((a, b) => a - b).join(","));
13
+ }
14
+ if (options.maxMutants && options.maxMutants > 0) {
15
+ args.push("--max", String(options.maxMutants));
16
+ }
17
+ const output = execFileSync("python3", args, {
18
+ cwd,
19
+ encoding: "utf8",
20
+ stdio: ["ignore", "pipe", "pipe"],
21
+ maxBuffer: 10 * 1024 * 1024,
22
+ });
23
+ const raw = JSON.parse(output);
24
+ const displayPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
25
+ return raw.map((mutant) => ({
26
+ id: mutant.id,
27
+ file: displayPath,
28
+ line: mutant.line,
29
+ column: mutant.column,
30
+ operator: mutant.operator,
31
+ original: mutant.original,
32
+ replacement: mutant.replacement,
33
+ mutatedSource: mutant.mutatedSource,
34
+ }));
35
+ }
@@ -0,0 +1,288 @@
1
+ import { parse, parseExpression } from "@babel/parser";
2
+ import generateImport from "@babel/generator";
3
+ import traverseImport from "@babel/traverse";
4
+ import * as t from "@babel/types";
5
+ // Babel ships CJS packages. Depending on the loader, the callable is either
6
+ // the default import or a `default` property on the namespace. Resolve both.
7
+ const generateModule = generateImport;
8
+ const generate = (generateModule.default ?? generateModule);
9
+ const traverseModule = traverseImport;
10
+ const traverse = (traverseModule.default ?? traverseModule);
11
+ const PARSER_PLUGINS = [
12
+ "typescript",
13
+ "jsx",
14
+ "decorators-legacy",
15
+ "classProperties",
16
+ "classPrivateProperties",
17
+ "classPrivateMethods",
18
+ "dynamicImport",
19
+ "importMeta",
20
+ "topLevelAwait",
21
+ ];
22
+ const OPERATOR_MAP = {
23
+ "<": "<=",
24
+ ">": ">=",
25
+ "<=": "<",
26
+ ">=": ">",
27
+ "===": "!==",
28
+ "!==": "===",
29
+ "==": "!=",
30
+ "!=": "==",
31
+ "+": "-",
32
+ "-": "+",
33
+ "*": "/",
34
+ "/": "*",
35
+ "%": "*",
36
+ "&&": "||",
37
+ "||": "&&",
38
+ };
39
+ function isIgnored(source, line) {
40
+ const lines = source.split(/\r?\n/);
41
+ return ((lines[line - 1] ?? "").includes("lie-detector-ignore") ||
42
+ (lines[line - 2] ?? "").includes("lie-detector-ignore"));
43
+ }
44
+ function lineOf(node) {
45
+ return node.loc?.start.line ?? 0;
46
+ }
47
+ function columnOf(node) {
48
+ return (node.loc?.start.column ?? 0) + 1;
49
+ }
50
+ function applyMutation(node, candidate) {
51
+ switch (candidate.kind) {
52
+ case "operator":
53
+ node.operator = candidate.replacement;
54
+ break;
55
+ case "return":
56
+ node.argument = t.identifier("undefined");
57
+ break;
58
+ case "negate":
59
+ node.test = parseExpression(`!(${candidate.testSource ?? ""})`, {
60
+ plugins: PARSER_PLUGINS,
61
+ });
62
+ break;
63
+ case "string":
64
+ node.value = candidate.replacement;
65
+ node.extra = undefined;
66
+ break;
67
+ case "boolean":
68
+ node.value = candidate.replacement === "true";
69
+ node.extra = undefined;
70
+ break;
71
+ case "number":
72
+ node.value = Number(candidate.replacement);
73
+ node.extra = undefined;
74
+ break;
75
+ }
76
+ }
77
+ function findNode(root, start, end, type) {
78
+ let found = null;
79
+ const visit = (node) => {
80
+ if (found || !node || typeof node !== "object")
81
+ return;
82
+ if (node.start === start && node.end === end && node.type === type) {
83
+ found = node;
84
+ return;
85
+ }
86
+ const keys = t.VISITOR_KEYS[node.type] ?? [];
87
+ for (const key of keys) {
88
+ const child = node[key];
89
+ if (Array.isArray(child)) {
90
+ for (const item of child)
91
+ visit(item);
92
+ }
93
+ else {
94
+ visit(child);
95
+ }
96
+ if (found)
97
+ return;
98
+ }
99
+ };
100
+ visit(root);
101
+ return found;
102
+ }
103
+ function isImportLike(parent) {
104
+ if (!parent)
105
+ return false;
106
+ return (parent.type === "ImportDeclaration" ||
107
+ parent.type === "ExportAllDeclaration" ||
108
+ parent.type === "ExportNamedDeclaration" ||
109
+ parent.type === "TSImportType" ||
110
+ parent.type === "TSExternalModuleReference" ||
111
+ parent.type === "TSLiteralType" ||
112
+ parent.type === "JSXAttribute");
113
+ }
114
+ export function mutateTs(source, options = {}) {
115
+ const file = options.file ?? "input.ts";
116
+ const allowedLines = options.lines;
117
+ const ast = parse(source, {
118
+ sourceType: "unambiguous",
119
+ errorRecovery: true,
120
+ plugins: PARSER_PLUGINS,
121
+ });
122
+ const candidates = [];
123
+ const add = (candidate) => {
124
+ if (candidate.line <= 0)
125
+ return;
126
+ if (allowedLines && !allowedLines.has(candidate.line))
127
+ return;
128
+ if (isIgnored(source, candidate.line))
129
+ return;
130
+ if (candidate.original === candidate.replacement)
131
+ return;
132
+ candidates.push(candidate);
133
+ };
134
+ const addOperator = (node) => {
135
+ const replacement = OPERATOR_MAP[node.operator];
136
+ if (!replacement)
137
+ return;
138
+ add({
139
+ kind: "operator",
140
+ nodeType: node.type,
141
+ start: node.start,
142
+ end: node.end,
143
+ line: lineOf(node),
144
+ column: columnOf(node),
145
+ operator: `${node.operator} -> ${replacement}`,
146
+ original: node.operator,
147
+ replacement,
148
+ });
149
+ };
150
+ traverse(ast, {
151
+ BinaryExpression(path) {
152
+ addOperator(path.node);
153
+ },
154
+ LogicalExpression(path) {
155
+ addOperator(path.node);
156
+ },
157
+ ReturnStatement(path) {
158
+ const argument = path.node.argument;
159
+ if (!argument)
160
+ return;
161
+ if (argument.type === "Identifier" && argument.name === "undefined")
162
+ return;
163
+ add({
164
+ kind: "return",
165
+ nodeType: path.node.type,
166
+ start: path.node.start ?? 0,
167
+ end: path.node.end ?? 0,
168
+ line: lineOf(path.node),
169
+ column: columnOf(path.node),
170
+ operator: "return -> undefined",
171
+ original: source.slice(argument.start ?? 0, argument.end ?? 0),
172
+ replacement: "undefined",
173
+ });
174
+ },
175
+ IfStatement(path) {
176
+ const test = path.node.test;
177
+ add({
178
+ kind: "negate",
179
+ nodeType: path.node.type,
180
+ start: path.node.start ?? 0,
181
+ end: path.node.end ?? 0,
182
+ line: lineOf(test),
183
+ column: columnOf(test),
184
+ operator: "condition -> negated",
185
+ original: source.slice(test.start ?? 0, test.end ?? 0),
186
+ replacement: `!(${source.slice(test.start ?? 0, test.end ?? 0)})`,
187
+ testSource: source.slice(test.start ?? 0, test.end ?? 0),
188
+ });
189
+ },
190
+ ConditionalExpression(path) {
191
+ const test = path.node.test;
192
+ add({
193
+ kind: "negate",
194
+ nodeType: path.node.type,
195
+ start: path.node.start ?? 0,
196
+ end: path.node.end ?? 0,
197
+ line: lineOf(test),
198
+ column: columnOf(test),
199
+ operator: "condition -> negated",
200
+ original: source.slice(test.start ?? 0, test.end ?? 0),
201
+ replacement: `!(${source.slice(test.start ?? 0, test.end ?? 0)})`,
202
+ testSource: source.slice(test.start ?? 0, test.end ?? 0),
203
+ });
204
+ },
205
+ StringLiteral(path) {
206
+ if (isImportLike(path.parent))
207
+ return;
208
+ const value = path.node.value;
209
+ const replacement = value === "" ? "lie-detector" : "";
210
+ add({
211
+ kind: "string",
212
+ nodeType: path.node.type,
213
+ start: path.node.start ?? 0,
214
+ end: path.node.end ?? 0,
215
+ line: lineOf(path.node),
216
+ column: columnOf(path.node),
217
+ operator: `string "${value}" -> "${replacement}"`,
218
+ original: value,
219
+ replacement,
220
+ });
221
+ },
222
+ BooleanLiteral(path) {
223
+ const value = path.node.value;
224
+ const replacement = !value;
225
+ add({
226
+ kind: "boolean",
227
+ nodeType: path.node.type,
228
+ start: path.node.start ?? 0,
229
+ end: path.node.end ?? 0,
230
+ line: lineOf(path.node),
231
+ column: columnOf(path.node),
232
+ operator: `${value} -> ${replacement}`,
233
+ original: String(value),
234
+ replacement: String(replacement),
235
+ });
236
+ },
237
+ NumericLiteral(path) {
238
+ const value = path.node.value;
239
+ const replacement = value === 0 ? 1 : 0;
240
+ add({
241
+ kind: "number",
242
+ nodeType: path.node.type,
243
+ start: path.node.start ?? 0,
244
+ end: path.node.end ?? 0,
245
+ line: lineOf(path.node),
246
+ column: columnOf(path.node),
247
+ operator: `${value} -> ${replacement}`,
248
+ original: String(value),
249
+ replacement: String(replacement),
250
+ });
251
+ },
252
+ });
253
+ const mutants = [];
254
+ const seen = new Set();
255
+ for (const candidate of candidates) {
256
+ const key = `${candidate.start}:${candidate.end}:${candidate.operator}`;
257
+ if (seen.has(key))
258
+ continue;
259
+ seen.add(key);
260
+ const clone = JSON.parse(JSON.stringify(ast));
261
+ const target = findNode(clone, candidate.start, candidate.end, candidate.nodeType);
262
+ if (!target)
263
+ continue;
264
+ applyMutation(target, candidate);
265
+ let mutatedSource;
266
+ try {
267
+ mutatedSource = generate(clone, { retainLines: true, comments: true, compact: false }, source).code;
268
+ }
269
+ catch {
270
+ continue;
271
+ }
272
+ if (mutatedSource === source)
273
+ continue;
274
+ mutants.push({
275
+ id: `${file}:${candidate.line}:${candidate.column}:${mutants.length + 1}`,
276
+ file,
277
+ line: candidate.line,
278
+ column: candidate.column,
279
+ operator: candidate.operator,
280
+ original: candidate.original,
281
+ replacement: candidate.replacement,
282
+ mutatedSource,
283
+ start: candidate.start,
284
+ end: candidate.end,
285
+ });
286
+ }
287
+ return mutants;
288
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ export function pythonQuickPath() {
5
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../../scripts/py/quick.py");
6
+ }
7
+ export function quickScanPy(filePath, cwd = process.cwd()) {
8
+ const absolutePath = isAbsolute(filePath) ? filePath : join(cwd, filePath);
9
+ const output = execFileSync("python3", [pythonQuickPath(), "--file", absolutePath], {
10
+ cwd,
11
+ encoding: "utf8",
12
+ stdio: ["ignore", "pipe", "pipe"],
13
+ maxBuffer: 10 * 1024 * 1024,
14
+ });
15
+ const findings = JSON.parse(output);
16
+ const displayPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
17
+ return findings.map((finding) => ({ ...finding, file: displayPath }));
18
+ }