Merge remote-tracking branch 'origin/master' into fix-4071-merge

# Conflicts:
#	.gitattributes
This commit is contained in:
Apostolos Mantzaris committed 2026-10-07 16:33:35 +03:00
commit 412408365e
19 files changed
+9021 -1

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
---
section: Added
audience: internal
---
- Add a CI job failure-set diff tool for fixer evidence.
+6
View File
@@ -0,0 +1,6 @@
---
section: Added
audience: internal
---
- Add `scripts/mutate.mjs`, a mutation runner that journals the original and mutated sha256, restores its target only while the file still holds the mutated bytes (any other state is refused and reported, never overwritten), and reports RED, SURVIVED or ERROR.
+1
View File
@@ -12,3 +12,4 @@ tests/fixtures/ci-failure-logs/infra-net-windows-crlf-prefix.real.log -text
# Frozen #4054 hook bytes for the guard-bash probe differential (#4071): the
# test pins their git blob ids, so no end-of-line conversion is allowed.
tests/fixtures/guard-bash-probes/hooks/** -text
tests/fixtures/ci-test-diff/** -text
+3
View File
@@ -60,8 +60,11 @@ mechanics"; a brief supplies only `lane=<name>`, scope, and the grant.
## Evidence
- Use `scripts/mutate.mjs` for bounded hand mutations; it restores the target automatically, but only while the file still holds the mutated bytes. A leftover journal (`<file>.mutate-backup`) blocks the next run on that file; recover with `--restore`, which refuses and prints the three hashes when the file was edited since. If a crash left the file already at its original bytes, `--restore` also refuses; check the printed hashes and delete the journal by hand. `--restore` is crash recovery only: run against a live `mutate.mjs` run on the same file, it pulls that run's mutation, and that run then reports ERROR (exit 4).
- Witness rule (ADR 0007): #1605 owns the witness lanes, and their fixtures
live under `tests/fixtures/witness/<slice>/`.
- A PR claiming it "reduces failures" runs `node scripts/ci-test-diff.mjs <jobA> <jobB>`, quotes its summary, and explains any NEW failures before claiming a reduction.
- Red-first has one stated exception: when the only red-first path needs broad
harness setup, brittle mocks, or a test you would delete right after it
proves the fix (shape 7: #1114, #1759), state the exception in `Tests`, name
+33
View File
@@ -0,0 +1,33 @@
export declare function stripLogDecorations(log: string): string;
export declare function extractFailingTestIds(log: string): string[];
export declare function summarizeLog(
log: string,
side?: string,
): {
testsFailed: number;
suitesFailed: number;
unhandledErrors: number;
};
export declare function validateLog(
log: string,
side?: string,
): {
ids: string[];
testsFailed: number;
suitesFailed: number;
unhandledErrors: number;
};
export declare function compareFailureSets(
previous: string[],
current: string[],
): {
fixed: string[];
newFailures: string[];
unchanged: string[];
};
export declare function parseArgs(argv: string[]): {
jobA: string;
jobB: string;
repository: string;
};
export declare function main(argv?: string[]): number;
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import {
extractVitestFailureIds,
OVERALL_TESTS_FAILED,
stripAnsi,
stripLineTimestamps,
} from "./lib/ci-failure-classifier.mjs";
const DEFAULT_REPOSITORY = "apmantza/pi-lens";
export function stripLogDecorations(log) {
const withoutFallbackPrefix = log.replace(
/^[^\t\r\n]+\t[^\t\r\n]+\t(?=\d{4}-\d\d-\d\dT)/gm,
"",
);
return stripLineTimestamps(stripAnsi(withoutFallbackPrefix))
.replace(/^\uFEFF/, "")
.replace(/^[ \t]+(?=FAIL\b)/gm, "")
.replace(/\r\n?/g, "\n");
}
export function extractFailingTestIds(log) {
return extractVitestFailureIds(log);
}
export function summarizeLog(log, side = "job") {
const failedMatch = OVERALL_TESTS_FAILED.exec(log);
const passedMatch = log.match(/^\s*Tests\s+(\d+)\s+passed\b/m);
const skippedMatch = log.match(/^\s*Tests\s+(\d+)\s+skipped\b/m);
const testsFailed = Number(failedMatch?.[1] ?? 0);
const failedTestsHeader = Number(
log.match(/\bFailed Tests\s+(\d+)\b/i)?.[1] ?? NaN,
);
const suitesFailed = Number(
log.match(/\bFailed Suites\s+(\d+)\b/i)?.[1] ?? 0,
);
const unhandledErrors = Number(
log.match(/\bErrors\s+(\d+)\s+error(?:s)?\b/i)?.[1] ?? 0,
);
if (!failedMatch && !passedMatch && !skippedMatch) {
throw new Error(`${side} log incomplete (no Vitest Tests summary)`);
}
if (
Number.isInteger(failedTestsHeader) &&
failedTestsHeader !== testsFailed
) {
throw new Error(`${side} log has mismatched Vitest failure summaries`);
}
return { testsFailed, suitesFailed, unhandledErrors };
}
export function validateLog(log, side = "job") {
const summary = summarizeLog(log, side);
const ids = extractFailingTestIds(log);
const expected = summary.testsFailed + summary.suitesFailed;
if (ids.length !== expected) {
throw new Error(
`${side} log has ${ids.length} failure IDs; Vitest summary reports ${expected}`,
);
}
return { ids, ...summary };
}
export function compareFailureSets(previous, current) {
const oldSet = new Set(previous);
const newSet = new Set(current);
return {
fixed: [...oldSet].filter((id) => !newSet.has(id)).sort(),
newFailures: [...newSet].filter((id) => !oldSet.has(id)).sort(),
unchanged: [...oldSet].filter((id) => newSet.has(id)).sort(),
};
}
function fetchJobLog(repository, jobId) {
try {
return execFileSync(
"gh",
[
"api",
`repos/${repository}/actions/jobs/${jobId}/logs`,
"--allow-escape-sequences",
],
{ encoding: "utf8", maxBuffer: 32 * 1024 * 1024 },
);
} catch (error) {
try {
return execFileSync(
"gh",
["run", "view", "--job", jobId, "--log", "--repo", repository],
{ encoding: "utf8", maxBuffer: 32 * 1024 * 1024 },
);
} catch (fallbackError) {
const message =
fallbackError instanceof Error
? fallbackError.message
: String(fallbackError);
throw new Error(`could not fetch logs for job ${jobId}: ${message}`, {
cause: error,
});
}
}
}
function printSet(label, values) {
console.log(`${label} (${values.length})`);
for (const value of values) console.log(` ${value}`);
}
export function parseArgs(argv) {
if (argv.length < 2 || argv.length > 4) {
throw new Error(
"usage: ci-test-diff.mjs <jobA> <jobB> [--repo owner/name]",
);
}
const [jobA, jobB, option, repository] = argv;
if (!/^\d+$/.test(jobA) || !/^\d+$/.test(jobB)) {
throw new Error("job IDs must be numeric");
}
if (option && option !== "--repo") {
throw new Error(
"usage: ci-test-diff.mjs <jobA> <jobB> [--repo owner/name]",
);
}
if (option && (!repository || !/^[^/\s]+\/[^/\s]+$/.test(repository))) {
throw new Error("--repo requires owner/name");
}
return { jobA, jobB, repository: repository ?? DEFAULT_REPOSITORY };
}
export function main(argv = process.argv.slice(2)) {
const { jobA, jobB, repository } = parseArgs(argv);
const previousReport = validateLog(
stripLogDecorations(fetchJobLog(repository, jobA)),
`job ${jobA}`,
);
const currentReport = validateLog(
stripLogDecorations(fetchJobLog(repository, jobB)),
`job ${jobB}`,
);
const previous = previousReport.ids;
const current = currentReport.ids;
const diff = compareFailureSets(previous, current);
const newUnhandledErrors = Math.max(
currentReport.unhandledErrors - previousReport.unhandledErrors,
0,
);
for (let index = 1; index <= newUnhandledErrors; index += 1) {
diff.newFailures.push(`unhandled error ${index}`);
}
console.log(
`Input: ${jobA} tests=${previousReport.testsFailed} suites=${previousReport.suitesFailed} errors=${previousReport.unhandledErrors}; ${jobB} tests=${currentReport.testsFailed} suites=${currentReport.suitesFailed} errors=${currentReport.unhandledErrors}`,
);
printSet("FIXED", diff.fixed);
printSet("NEW", diff.newFailures);
printSet("UNCHANGED", diff.unchanged);
console.log(
`Summary: fixed=${diff.fixed.length} new=${diff.newFailures.length} unchanged=${diff.unchanged.length}`,
);
return diff.newFailures.length ? 1 : 0;
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
try {
process.exitCode = main();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 2;
}
}
+2
View File
@@ -39,8 +39,10 @@ export interface ClassifierDecision {
export declare const NET_PATTERN: RegExp;
export declare const BARE_FAIL_LINE: RegExp;
export declare const ASSERTION_LINE: RegExp;
export declare const OVERALL_TESTS_FAILED: RegExp;
export declare function stripAnsi(text: string): string;
export declare function stripLineTimestamps(text: string): string;
export declare function extractVitestFailureIds(log: string): string[];
export declare function classifyFailureLog(rawLog: string): Classification;
export declare function readCgroupOomKillCount(log: string): number | null;
export declare function describeKernelKillEvidence(log: string): string | null;
+27 -1
View File
@@ -84,6 +84,32 @@ const MAX_LOG_BYTES = 2 * 1024 * 1024;
// snapshot without rebuilding". The project label ("default") sits between
// FAIL and the file path.
const FAIL_LINE = /^\s*FAIL\s+\S+\s+(\S+\.test\.tsx?)\s*>\s*(.+)$/gm;
const VITEST_TEST_FILE = /\S+\.(?:test|spec)\.[cm]?[jt]sx?/;
/** Extract Vitest failure-banner identities from an already-normalized log. */
export function extractVitestFailureIds(log) {
const ids = new Set();
for (const rawLine of log.split("\n")) {
const line = rawLine.match(/^\s*FAIL\b\s+(.*)$/)?.[1];
if (!line) continue;
const fileMatch = line.match(VITEST_TEST_FILE);
if (!fileMatch) continue;
const file = fileMatch[0];
const prefix = line.slice(0, fileMatch.index).trim();
const project = prefix
? prefix
.split(/\s+/)
.at(-1)
.replace(/^\|+|\|+$/g, "")
: "";
const suffix = line.slice(fileMatch.index + file.length);
const testName = suffix.match(/^\s*>\s*(.+?)\s*$/)?.[1];
const id = `${project ? `${project}::` : ""}${file}${testName ? ` › ${testName.replace(/\s+/g, " ")}` : ""}`;
ids.add(id);
}
return [...ids].sort();
}
// A file-level FAIL with no "> testname" -- a collection/import error never
// reaches a single test, so vitest has no test name to print (review round
// 1, F2/P2). Deliberately looser than FAIL_LINE: only used when FAIL_LINE
@@ -135,7 +161,7 @@ const TYPESCRIPT_ERROR =
// The run's own final tally line (real log, same run): " Tests 1 failed |
// 9837 passed | 48 skipped (9886)". No file/test detail, but a nonzero
// failed count here is unambiguous.
const OVERALL_TESTS_FAILED = /^\s*Tests\s+(\d+)\s+failed\b/m;
export const OVERALL_TESTS_FAILED = /^\s*Tests\s+(\d+)\s+failed\b/m;
// #2839: vitest's timeout failure text (real log, run 34389495533 attempt 1,
// job 102594125043, PR #2834): "Error: Test timed out in 5000ms." Vitest's
// runner uses the same template for hooks: "Error: Hook timed out in 300ms."
+530
View File
@@ -0,0 +1,530 @@
#!/usr/bin/env node
/**
* Run one bounded, restorable hand mutation (#4048).
*
* The file is deliberately a small process boundary: callers can use it from
* a shell or a test without importing the test runner or the project build.
*/
import { createHash } from "node:crypto";
import { spawn, spawnSync } from "node:child_process";
import {
readFileSync,
readdirSync,
renameSync,
statSync,
writeFileSync,
unlinkSync,
} from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { stripVTControlCharacters } from "node:util";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
function usage(message) {
if (message) console.error(`mutate.mjs: ${message}`);
console.error(
"usage: scripts/mutate.mjs --file <path> --find <text|/regex/> --replace <text> --tests <files…> [--built] [--table] [--allow-comment]\n scripts/mutate.mjs --restore [--file <path>]\n" +
"exit codes: 0 or the test runner's code, 1 refused or failed, 2 usage, 4 the run could not restore its file (a journal remains)",
);
process.exitCode = 2;
}
function argsFrom(argv) {
const values = { tests: [] };
let fileSeen = false;
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (
arg === "--built" ||
arg === "--table" ||
arg === "--restore" ||
arg === "--allow-comment"
)
values[arg.slice(2)] = true;
else if (arg === "--tests") values.tests = argv.slice(++index);
else if (["--file", "--find", "--replace"].includes(arg)) {
if (arg === "--file" && fileSeen)
throw new Error(
"repeated --file is not supported; provide one file per run",
);
if (arg === "--file") fileSeen = true;
const value = argv[++index];
if (value === undefined) throw new Error(`${arg} needs a value`);
values[arg.slice(2)] = value;
} else throw new Error(`unknown argument ${arg}`);
}
if (values.restore) return values;
if (
!values.file ||
values.find === undefined ||
values.replace === undefined
) {
throw new Error("--file, --find, and --replace are required");
}
if (values.tests.length === 0)
throw new Error("--tests needs at least one file");
return values;
}
function digest(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
function gitClean(file) {
const result = spawnSync(
process.env.GIT ?? "git",
["status", "--porcelain=v1", "--", file],
{
cwd: root,
encoding: "utf8",
},
);
if (result.error) throw result.error;
return result.status === 0 && result.stdout.trim() === "";
}
function twinFor(source) {
if (source.endsWith(".ts") || source.endsWith(".tsx")) {
return source.replace(/\.tsx?$/, ".js");
}
return null;
}
function parseFind(value) {
if (value.startsWith("/") && value.lastIndexOf("/") > 0) {
const slash = value.lastIndexOf("/");
try {
return new RegExp(value.slice(1, slash), value.slice(slash + 1));
} catch (error) {
throw new Error(`invalid --find regex: ${error.message}`);
}
}
return value;
}
function mutationFor(original, searchable, find, replacement, allowComment) {
const needle = parseFind(find);
const codeIndex =
typeof needle === "string"
? searchable.indexOf(needle)
: (() => {
needle.lastIndex = 0;
return needle.exec(searchable)?.index ?? -1;
})();
if (codeIndex < 0 && !allowComment)
throw new Error(
"refusing no-op edit: --find matches only comments/strings/regex literals or is absent",
);
const originalIndex =
codeIndex >= 0
? codeIndex
: typeof needle === "string"
? original.indexOf(needle)
: original.search(needle);
const matchLength =
typeof needle === "string"
? needle.length
: (() => {
needle.lastIndex = 0;
return needle.exec(original.slice(originalIndex))?.[0].length;
})();
const mutated =
originalIndex >= 0 && matchLength !== undefined
? original.slice(0, originalIndex) +
replacement +
original.slice(originalIndex + matchLength)
: original.replace(needle, replacement);
if (mutated === original) {
throw new Error(
"refusing no-op edit: --find is absent or replacement is identical",
);
}
return mutated;
}
// The grammar @ast-grep/napi (a direct dependency) parses each JS/TS family
// file with; any other file type is matched raw, because a JS lexer would
// misread its comments and quotes.
const LEXER_LANGUAGES = {
".ts": "TypeScript",
".mts": "TypeScript",
".cts": "TypeScript",
".tsx": "Tsx",
".js": "JavaScript",
".mjs": "JavaScript",
".cjs": "JavaScript",
".jsx": "JavaScript",
};
const lexerLanguage = (file) => LEXER_LANGUAGES[path.extname(file)];
/** `source` with comments, strings, regex literals and a template's text blanked to spaces (newlines kept), so a needle can only match code. */
function blankNonCode(source, file, astGrep) {
const language = lexerLanguage(file);
if (!language) return source;
const units = source.split(""); // UTF-16 units, the unit ast-grep reports
const blank = (node) => {
const { start, end } = node.range();
for (let index = start.index; index < end.index; index += 1)
if (units[index] !== "\n" && units[index] !== "\r") units[index] = " ";
};
const nonCode = ["comment", "string", "regex", "template_string"].map(
(kind) => ({ kind }),
);
for (const node of astGrep
.parse(language, source)
.root()
.findAll({ rule: { any: nonCode } })) {
if (node.kind() !== "template_string") blank(node);
else
// A `${…}` substitution is code; the text around it is not.
for (const part of node.children())
if (part.kind() !== "template_substitution") blank(part);
}
return units.join("");
}
// The restore rule (#4048 round 3). A journal holds the original bytes and the
// sha256 of both the original and the mutated bytes. The file is written back
// only when its current sha256 equals the mutated sha256. Every other state
// writes nothing and reports the journal path and the three hashes.
const JOURNAL_SUFFIX = ".mutate-backup";
function journalFor(file) {
return `${file}${JOURNAL_SUFFIX}`;
}
function journalOf(file, original, mutated) {
return {
version: 1,
file: path.relative(root, file),
originalSha256: digest(original),
mutatedSha256: digest(mutated),
original: original.toString("base64"),
};
}
// `wx`: creating the journal is the lock that keeps a second run off this file.
function writeJournal(file, journal) {
writeFileSync(journalFor(file), JSON.stringify(journal), { flag: "wx" });
}
function replaceJournal(file, journal) {
const temporary = `${journalFor(file)}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(journal));
renameSync(temporary, journalFor(file));
}
function readJournal(file) {
const journal = JSON.parse(readFileSync(journalFor(file), "utf8"));
const original = Buffer.from(journal.original, "base64");
if (
journal.version !== 1 ||
typeof journal.originalSha256 !== "string" ||
typeof journal.mutatedSha256 !== "string" ||
digest(original) !== journal.originalSha256
)
throw new Error(
"unknown version or original bytes do not match their hash",
);
return { ...journal, original };
}
function journalReport(file) {
const current = statExists(file) ? digest(readFileSync(file)) : "absent";
try {
const journal = readJournal(file);
return {
journal,
current,
text: `original sha256 ${journal.originalSha256}; mutated sha256 ${journal.mutatedSha256}; current sha256 ${current}; journal ${journalFor(file)}`,
};
} catch (error) {
return {
journal: null,
current,
text: `journal ${journalFor(file)} is unreadable (${error.message}); current sha256 ${current}`,
};
}
}
/** Restores `file` from its journal under the rule above. Never throws and never writes on a refusal. */
function restoreJournal(file) {
if (!statExists(journalFor(file))) return { restored: false, refusal: null };
const { journal, current, text } = journalReport(file);
const name = path.relative(root, file);
if (!journal || current !== journal.mutatedSha256)
return { restored: false, refusal: `refusing to restore ${name}: ${text}` };
try {
writeFileSync(file, journal.original);
if (digest(readFileSync(file)) !== journal.originalSha256)
throw new Error("restored bytes do not match the original sha256");
unlinkSync(journalFor(file));
return { restored: true, refusal: null };
} catch (error) {
return {
restored: false,
refusal: `restore of ${name} failed (${error.message}): ${text}`,
};
}
}
function journalFiles(directory) {
const found = [];
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const full = path.join(directory, entry.name);
if (entry.isDirectory() && entry.name !== "node_modules")
found.push(...journalFiles(full));
else if (entry.isFile() && entry.name.endsWith(JOURNAL_SUFFIX))
found.push(full.slice(0, -JOURNAL_SUFFIX.length));
}
return found;
}
function failedTitles(output) {
return output
.split("\n")
.filter((line) => /FAIL|×|✗/.test(line))
.map((line) => line.trim())
.filter(Boolean)
.slice(0, 20);
}
function classifyTestRun(testRun) {
if (/(?:Tests\s+no tests|Tests\s+0 tests)/.test(testRun.output))
return "ERROR";
return testRun.code === 0 ? "SURVIVED" : "RED";
}
function runTests(files, onSignal) {
return new Promise((resolve) => {
const command = path.join(root, "node_modules", ".bin", "vitest");
const child = spawn(
command,
["run", ...files, "--configLoader", "runner"],
{
cwd: root,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
},
);
activeChild = child;
let output = "";
child.stdout.on("data", (chunk) => {
output += chunk;
process.stdout.write(chunk);
});
child.stderr.on("data", (chunk) => {
output += chunk;
process.stderr.write(chunk);
});
const stop = () => {
child.kill("SIGINT");
onSignal();
};
process.once("SIGINT", stop);
child.once("close", (code, signal) => {
activeChild = null;
process.removeListener("SIGINT", stop);
// Colour codes split "Tests" from "no tests" on CI; classify and
// report the plain text.
resolve({
code: code ?? 130,
signal,
output: stripVTControlCharacters(output),
});
});
});
}
let activeChild = null;
function build() {
const result = spawnSync(
process.execPath,
[
path.join(root, "node_modules", "typescript", "bin", "tsc"),
"--project",
"tsconfig.build.json",
],
{ cwd: root, env: process.env, encoding: "utf8", stdio: "inherit" },
);
if (result.error) throw result.error;
if (result.status !== 0)
throw new Error(`build failed with exit code ${result.status}`);
}
function appendTable(options, result) {
const row = `| ${options.file} | ${result.code} | ${result.status} | ${result.failed.length ? result.failed.join(" ") : "—"} |\n`;
const body = path.join(root, "PR_BODY.md");
if (options.table && statExists(body))
writeFileSync(body, `${readFileSync(body, "utf8")}${row}`);
console.log(`mutation-table: ${row.trimEnd()}`);
}
function statExists(file) {
try {
statSync(file);
return true;
} catch {
return false;
}
}
function restoreCommand(options) {
const source = options.file ? path.resolve(root, options.file) : null;
const twin = source && !options.built ? twinFor(source) : null;
const files = source ? [source, ...(twin ? [twin] : [])] : journalFiles(root);
let restored = 0;
let refused = 0;
for (const file of files) {
const outcome = restoreJournal(file);
if (outcome.restored) restored += 1;
if (outcome.refusal) {
refused += 1;
console.error(`mutate.mjs: ${outcome.refusal}`);
}
}
console.log(`restored ${restored} mutation journal(s)`);
return refused === 0 ? 0 : 1;
}
async function main() {
let options;
try {
options = argsFrom(process.argv.slice(2));
} catch (error) {
usage(error.message);
return 2;
}
if (options.restore) return restoreCommand(options);
const source = path.resolve(root, options.file);
const target = source;
const candidateTwin = options.built ? null : twinFor(source);
const twin =
candidateTwin && statExists(candidateTwin) ? candidateTwin : null;
const files = [target, ...(twin ? [twin] : [])];
try {
for (const file of files) {
const name = path.relative(root, file);
if (!statExists(file)) throw new Error(`file does not exist: ${name}`);
// A journal is a live run's lock or a dead run's evidence; this run
// cannot tell which, so only --restore ever consumes one.
if (statExists(journalFor(file)))
throw new Error(
`refusing to start on ${name}: a mutation journal exists (a live run, or a run that died; recover with --restore): ${journalReport(file).text}`,
);
if (!gitClean(name)) throw new Error(`refusing dirty file: ${name}`);
}
} catch (error) {
console.error(`mutate.mjs: ${error.message}`);
return 1;
}
// Files whose journal this run created, in creation order.
const owned = [];
let result = { code: 2, failed: [], status: "RED" };
let interrupted = false;
let handlingSignal = false;
const restoreOwned = () => {
const refusals = [];
for (const file of owned) {
const { refusal } = restoreJournal(file);
if (refusal) refusals.push(refusal);
}
return refusals;
};
const signalHandler = (signal) => {
if (handlingSignal) return;
handlingSignal = true;
interrupted = true;
try {
if (activeChild) activeChild.kill("SIGKILL");
for (const refusal of restoreOwned())
console.error(`mutate.mjs: ${refusal}`);
} finally {
process.removeAllListeners(signal);
process.kill(process.pid, signal);
}
};
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
process.once(signal, () => signalHandler(signal));
process.once("uncaughtException", (error) => {
try {
for (const refusal of restoreOwned())
console.error(`mutate.mjs: ${refusal}`);
} finally {
console.error(error.stack ?? error);
process.exit(1);
}
});
try {
const originals = new Map(files.map((file) => [file, readFileSync(file)]));
const original = originals.get(target);
const lexer = lexerLanguage(target) ? await import("@ast-grep/napi") : null;
const text = original.toString("utf8");
const mutated = Buffer.from(
mutationFor(
text,
lexer ? blankNonCode(text, target, lexer) : text,
options.find,
options.replace,
options["allow-comment"],
),
"utf8",
);
writeJournal(target, journalOf(target, original, mutated));
owned.push(target);
writeFileSync(target, mutated);
if (twin) {
// The build has not rewritten the twin yet, so "mutated" is what it
// is now; the real mutated hash is recorded the moment the build ends.
const twinBytes = originals.get(twin);
writeJournal(twin, journalOf(twin, twinBytes, twinBytes));
owned.push(twin);
try {
build();
} finally {
// Nothing else runs between the build and this record, so the
// twin's current bytes are the build's output, failed build included.
replaceJournal(twin, journalOf(twin, twinBytes, readFileSync(twin)));
}
}
if (interrupted)
result = { code: 130, failed: ["interrupted"], status: "RED" };
else {
const testRun = await runTests(options.tests, () => {
interrupted = true;
});
result = {
code: testRun.code,
failed: failedTitles(testRun.output),
status: classifyTestRun(testRun),
};
}
} catch (error) {
result = { code: 1, failed: [error.message], status: "RED" };
}
const refusals = restoreOwned();
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
process.removeAllListeners(signal);
if (refusals.length > 0) {
for (const refusal of refusals) console.error(`mutate.mjs: ${refusal}`);
result = { code: 4, failed: refusals, status: "ERROR" };
}
console.log("--- mutation transcript ---");
console.log(
`mutation: ${options.file} (${options.find} -> ${options.replace})`,
);
console.log(`exit code: ${result.code}`);
console.log(
`failed test titles: ${result.failed.length ? result.failed.join("; ") : "none"}`,
);
console.log(result.status);
appendTable(options, result);
return result.code;
}
main().then((code) => {
process.exitCode = code;
});
+17
View File
@@ -128,6 +128,11 @@ const ADMITTED_AFTER_BASELINE: Readonly<
reason:
"the defect is wall-clock only (2^N globstar backtracking); a fake clock measures nothing",
},
"never-settling-wait:scripts/mutate-fixture.test.ts": {
detector: "never-settling-wait",
reason:
"the interrupt witness must hold a real child open until SIGINT; replacing the wait with a settled promise would erase the lifecycle under test",
},
// 2026-09-07 (#2703 review r1): an unhandled derived-promise rejection is
// only observable through Node's `unhandledRejection` event, which fires
// on a real macrotask; the file drains one real `setImmediate` tick.
@@ -427,6 +432,13 @@ const ADMITTED_AFTER_BASELINE: Readonly<
reason:
"the exact local CLI, shallow checkout and `git check-ignore` (#2904) are the subjects; an in-process double cannot prove any of those command boundaries",
},
// 2026-10-07 (#4072 review F2): the executable CLI's exit status is the
// contract; an in-process main() call cannot prove the entry-point boundary.
"real-process-spawn:scripts/ci-test-diff.test.ts": {
detector: "real-process-spawn",
reason:
"the executable CLI exit status is the contract; an in-process main call cannot prove the entry-point boundary",
},
"real-process-spawn:scripts/ci-verdict.test.ts": {
detector: "real-process-spawn",
reason:
@@ -483,6 +495,11 @@ const ADMITTED_AFTER_BASELINE: Readonly<
// scripts/mutation-report.mjs's own argv parsing (--report/--out) and
// file I/O; an in-process call would just re-exercise the exported render
// function the other describe block already covers.
"real-process-spawn:scripts/mutate.test.ts": {
detector: "real-process-spawn",
reason:
"the mutation CLI's child Vitest process and signal path are the process boundary; an in-process call cannot prove restoration after SIGINT",
},
"real-process-spawn:scripts/mutation-report-render.test.ts": {
detector: "real-process-spawn",
reason:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
RUN v5.0.3 /home/runner/work/pi-lens/pi-lens
✓ tests/scripts/ci-test-diff.test.ts (1 test) 4ms
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 10:00:00
Duration 1.23s (transform 10ms, setup 20ms, collect 5ms, tests 4ms, environment 0ms, prepare 100ms)
+152
View File
@@ -0,0 +1,152 @@
// flake-shape: real-process-spawn — the CLI's real exit status is the contract; an in-process main() call cannot prove the executable entry point (#4072 review F2).
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
compareFailureSets,
extractFailingTestIds,
stripLogDecorations,
validateLog,
} from "../../scripts/ci-test-diff.mjs";
const fixture = (name: string) =>
fs.readFileSync(path.join("tests/fixtures/ci-test-diff", name), "utf8");
// The green fixture is hand-composed in Vitest 5.0.3's real summary shape.
describe("ci-test-diff failure extraction", () => {
// Recurrence: #4072's Windows logs contain ANSI, CRLF, and Actions timestamps;
// the tool must compare test identities rather than the aggregate failure count.
it("reproduces the 7 fixed / 7 new / 51 unchanged witness", () => {
const master = extractFailingTestIds(
stripLogDecorations(fixture("job-112724408671.log")),
);
const round2 = extractFailingTestIds(
stripLogDecorations(fixture("job-112734370876.log")),
);
const diff = compareFailureSets(master, round2);
expect(master).toHaveLength(58);
expect(round2).toHaveLength(58);
expect(diff.fixed).toHaveLength(7);
expect(diff.newFailures).toHaveLength(7);
expect(diff.unchanged).toHaveLength(51);
expect(diff.fixed).toContain(
"default::tests/clients/path-utils.test.ts › normalizeFilePath: dot segments fold into the canonical key (#3184) > an empty string is returned unchanged, not invented into the cwd",
);
expect(diff.newFailures).toContain(
"default::tests/clients/read-guard-path-normalization.test.ts › ReadGuard path-key normalization (zero_read false-block regression) > getReadHistory matches across separator forms",
);
});
it("normalizes Actions timestamps and terminal decoration", () => {
const raw =
"2026-10-07T00:00:00.000Z \u001b[41m\u001b[1m FAIL \u001b[22m\u001b[49m default tests/a.test.ts\r\n";
expect(stripLogDecorations(raw)).toBe("FAIL default tests/a.test.ts\n");
});
it("covers collection, unnamed-project, fallback, and non-tests-root FAIL shapes", () => {
const raw = [
"job\tstep\t2026-10-07T00:00:00.000Z FAIL tests/imp.test.ts [ tests/imp.test.ts ]",
"FAIL tests/single.test.ts > s > a > b",
"FAIL TS clients/other.spec.ts > labelled",
].join("\n");
expect(extractFailingTestIds(stripLogDecorations(raw))).toEqual([
"TS::clients/other.spec.ts › labelled",
"tests/imp.test.ts",
"tests/single.test.ts › s > a > b",
]);
});
it("rejects incomplete or mismatched Vitest summaries", () => {
expect(() =>
validateLog("FAIL default tests/a.test.ts > t", "job A"),
).toThrow("job A log incomplete");
expect(() =>
validateLog("Tests 1 failed\nFailed Tests 2", "job B"),
).toThrow("mismatched Vitest failure summaries");
});
it("keeps project names in identities", () => {
const log =
"Tests 2 failed\n" +
"Failed Tests 2\n" +
"FAIL web tests/same.test.ts > same\n" +
"FAIL node tests/same.test.ts > same\n";
expect(validateLog(log).ids).toEqual([
"node::tests/same.test.ts › same",
"web::tests/same.test.ts › same",
]);
});
it("normalizes Vitest's non-colour pipe project label", () => {
const log =
"Tests 1 failed\n" +
"Failed Tests 1\n" +
"FAIL |default| tests/same.test.ts > same\n";
expect(validateLog(log).ids).toEqual([
"default::tests/same.test.ts › same",
]);
});
it("accepts a green run and reconciles an unhandled error without a suite", () => {
expect(validateLog(fixture("job-green-vitest.log")).ids).toEqual([]);
expect(
validateLog(
"Tests 1 failed\nFailed Suites 0\nErrors 1 error\n" +
"FAIL default tests/late.test.ts > rejects late work",
),
).toMatchObject({ testsFailed: 1, suitesFailed: 0, unhandledErrors: 1 });
});
it("accepts a skipped-only run as a zero-failure side", () => {
expect(validateLog("Tests 2 skipped\n").ids).toEqual([]);
});
it("rejects a failure count with too few extracted IDs", () => {
expect(() =>
validateLog(
"Tests 2 failed\nFailed Tests 2\n" +
"FAIL default tests/only.test.ts > only failure",
),
).toThrow("has 1 failure IDs; Vitest summary reports 2");
});
it("returns 0 for unchanged, 1 for NEW, and 2 for invalid job logs", () => {
const scratch = fs.mkdtempSync(
path.join(process.env.TMPDIR ?? os.tmpdir(), "ci-test-diff-"),
);
const gh = path.join(scratch, "gh");
const fixtureDir = path.resolve("tests/fixtures/ci-test-diff");
const fixtureA = path.join(fixtureDir, "job-112724408671.log");
const fixtureB = path.join(fixtureDir, "job-112734370876.log");
fs.writeFileSync(
gh,
`#!/usr/bin/env node\nconst fs = require("node:fs");\nconst request = process.argv.find((value) => value.includes("/jobs/")) ?? "";\nconst id = request.match(/\\/jobs\\/(\\d+)\\//)?.[1];\nconst file = id === "0" ? null : id === "3" ? ${JSON.stringify(path.join(fixtureDir, "job-green-vitest.log"))} : id === "4" ? ${JSON.stringify(path.join(scratch, "job-unhandled.log"))} : id === "2" ? ${JSON.stringify(fixtureB)} : ${JSON.stringify(fixtureA)};\nif (file) process.stdout.write(fs.readFileSync(file, "utf8"));\n`,
);
fs.writeFileSync(
path.join(scratch, "job-unhandled.log"),
"Tests 1 passed\nErrors 1 error\n",
);
fs.chmodSync(gh, 0o755);
const env = { ...process.env, PATH: `${scratch}:${process.env.PATH}` };
const run = (a: string, b: string) =>
spawnSync(process.execPath, ["scripts/ci-test-diff.mjs", a, b], {
cwd: path.resolve("."),
encoding: "utf8",
env,
});
expect(run("1", "1").status).toBe(0);
expect(run("1", "2").status).toBe(1);
expect(run("0", "1").status).toBe(2);
// A→GREEN is clean, while GREEN→B is NEW; direction is the CLI contract.
expect(run("1", "3").status).toBe(0);
expect(run("3", "2").status).toBe(1);
const unhandled = run("3", "4");
expect(unhandled.status).toBe(1);
expect(unhandled.stdout).toContain("NEW (1)");
expect(unhandled.stdout).toContain("unhandled error 1");
fs.rmSync(scratch, { recursive: true, force: true });
});
});
+1
View File
@@ -0,0 +1 @@
mutation-built-marker
+48
View File
@@ -0,0 +1,48 @@
// flake-shape: never-settling-wait — the interrupt witness must keep a real child alive until the CLI sends SIGINT.
import { appendFileSync } from "node:fs";
import { expect, it } from "vitest";
const mutationSafeMarker = true;
// Lexer fixtures for the mutate.test.ts matcher cases (#4048 round 3): a needle
// inside a regex literal or a template's text is not code; the same text inside
// a template substitution, across a division, or after a regex literal holding
// a quote (last in this file) is.
const mutationRegexLiteral = /mutation-regex-only-marker\s+x/;
const mutationQuotient = 8 / 2 / 2;
const mutationTemplate = `mutation-template-only-marker ${mutationQuotient + 1}`;
it("mutation fixture remains original", () => {
// mutation-comment-only-marker
expect(mutationSafeMarker).toBe(true);
expect("original").toBe("original");
expect([mutationRegexLiteral, mutationTemplate]).toHaveLength(2);
});
it("mutation fixture has a failure marker", () => {
expect("mutation-fail-marker").toBe("mutation-fail-marker");
});
it("mutation fixture can hold an interrupting run", async () => {
// A legitimate edit made while a mutation run is live: the run's own
// cleanup must refuse to overwrite it (#4048 round 3, table row 12).
if (process.env.PI_LENS_MUTATION_EDIT) {
appendFileSync(process.env.PI_LENS_MUTATION_EDIT, "legitimate edit\n");
expect(true).toBe(true);
return;
}
if (!process.env.PI_LENS_MUTATION_RUN) {
expect(true).toBe(true);
return;
}
await new Promise(() => {});
});
// Kept last: a scanner that reads the quote inside this regex literal as a
// string start desyncs from here to the end of the file, and must not take the
// tests above with it (#4048 round 3).
const mutationQuoteRegex = /https?:\/\/x"/;
const mutationAfterRegex = true;
it("mutation fixture lexer constants remain original", () => {
expect([mutationQuoteRegex, mutationAfterRegex]).toHaveLength(2);
});
+858
View File
@@ -0,0 +1,858 @@
// flake-shape: real-process-spawn — the mutation CLI's child Vitest process and SIGINT restoration are the process boundary under test.
import { execFile, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { readFileSync, rmSync, writeFileSync } from "node:fs";
import { promisify } from "node:util";
import { expect, it, vi } from "vitest";
// Every case spawns a real Vitest child; a shared CI runner needs more than the
// 5 s default (the round-2 orphan-journal test timed out there).
vi.setConfig({ testTimeout: 60_000 });
const execFileAsync = promisify(execFile);
const root = process.cwd();
const cli = "scripts/mutate.mjs";
const target = "tests/scripts/mutate-fixture.test.ts";
const find = "true";
const replace = "Boolean(1)";
const digest = () =>
createHash("sha256").update(readFileSync(target)).digest("hex");
function invoke(testFile: string, ...extra: string[]) {
return execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
find,
"--replace",
replace,
"--tests",
testFile,
...extra,
],
{ cwd: root },
);
}
function invokeNoop() {
return execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
"missing",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root },
);
}
it("restores the source after a successful test run and reports SURVIVED", async () => {
const before = digest();
const { stdout } = await invoke(target);
expect(stdout).toContain("SURVIVED");
expect(digest()).toBe(before);
});
it("restores the source after a failing test run and reports RED with a title", async () => {
// Round 2 searched a string-only needle, which the matcher refuses with the
// same exit code 1, so this test never reached RED. A code needle does.
const before = digest();
await expect(
execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
"expect(mutationSafeMarker).toBe(true)",
"--replace",
"expect(mutationSafeMarker).toBe(false)",
"--tests",
target,
],
{ cwd: root },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringMatching(
/mutation fixture remains original[\s\S]*RED/,
),
});
expect(digest()).toBe(before);
});
it("restores after a mutation throw", async () => {
const before = digest();
await expect(
execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
"/[",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root },
),
).rejects.toMatchObject({ code: 1 });
expect(digest()).toBe(before);
});
it("refuses a no-op and leaves the source untouched", async () => {
const before = digest();
await expect(invokeNoop()).rejects.toMatchObject({ code: 1 });
expect(digest()).toBe(before);
});
it("restores on SIGINT", async () => {
const before = digest();
const child = spawn(
process.execPath,
[
cli,
"--file",
target,
"--find",
find,
"--replace",
replace,
"--tests",
target,
],
{
cwd: root,
env: { ...process.env, PI_LENS_MUTATION_RUN: "1" },
stdio: ["ignore", "pipe", "ignore"],
},
);
await new Promise((resolve) => child.stdout?.once("data", resolve));
child.kill("SIGINT");
const [code, signal] = await new Promise<
[number | null, NodeJS.Signals | null]
>((resolve) =>
child.once("close", (exitCode, closeSignal) =>
resolve([exitCode, closeSignal]),
),
);
expect(code).toBeNull();
expect(signal).toBe("SIGINT");
expect(digest()).toBe(before);
});
it("supports a surviving built-twin mutation", async () => {
const builtTarget = "tests/scripts/mutate-built.txt";
const before = createHash("sha256")
.update(readFileSync(builtTarget))
.digest("hex");
const { stdout } = await execFileAsync(
process.execPath,
[
cli,
"--built",
"--file",
builtTarget,
"--find",
"mutation-built-marker",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root },
);
expect(stdout).toContain("SURVIVED");
expect(
createHash("sha256").update(readFileSync(builtTarget)).digest("hex"),
).toBe(before);
});
it("refuses a comment-only match unless explicitly allowed", async () => {
const before = digest();
await expect(
execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
"mutation-comment-only-marker",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("comments/strings"),
});
const { stdout } = await execFileAsync(
process.execPath,
[
cli,
"--allow-comment",
"--file",
target,
"--find",
"mutation-comment-only-marker",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root },
);
expect(stdout).toContain("SURVIVED");
expect(digest()).toBe(before);
});
it("refuses repeated --file options", async () => {
await expect(
execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--file",
"tests/scripts/mutate-built.txt",
"--find",
find,
"--replace",
replace,
"--tests",
target,
],
{ cwd: root },
),
).rejects.toMatchObject({
code: 2,
stderr: expect.stringContaining("repeated --file"),
});
});
// CI colours Vitest's summary ("Tests" and "no tests" are split by escape
// codes), and a plain terminal does not; PR #4075's first CI run was red on the
// coloured form only.
it.each([
["plain", {}],
["coloured", { FORCE_COLOR: "1" }],
])(
"reports a test load failure as ERROR (%s output)",
async (_name, colour) => {
const before = digest();
await expect(
execFileAsync(
process.execPath,
[
cli,
"--file",
target,
"--find",
"const mutationSafeMarker =",
"--replace",
"const mutationSafeMarker = =",
"--tests",
target,
],
{ cwd: root, env: { ...process.env, NO_COLOR: undefined, ...colour } },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("\nERROR\n"),
});
expect(digest()).toBe(before);
},
60_000,
);
async function terminatesAndRestores(signal: "SIGTERM" | "SIGHUP") {
const before = digest();
const child = spawn(
process.execPath,
[
cli,
"--file",
target,
"--find",
find,
"--replace",
replace,
"--tests",
target,
],
{
cwd: root,
env: { ...process.env, PI_LENS_MUTATION_RUN: "1" },
stdio: ["ignore", "pipe", "ignore"],
},
);
await new Promise((resolve) => child.stdout?.once("data", resolve));
child.kill(signal);
const [code, closeSignal] = await new Promise<
[number | null, NodeJS.Signals | null]
>((resolve) =>
child.once("close", (exitCode, observedSignal) =>
resolve([exitCode, observedSignal]),
),
);
expect(code).toBeNull();
expect(closeSignal).toBe(signal);
expect(digest()).toBe(before);
}
it("restores on SIGTERM", () => terminatesAndRestores("SIGTERM"));
it("restores on SIGHUP", () => terminatesAndRestores("SIGHUP"));
it("restores when a real timeout sends SIGTERM", async () => {
const builtTarget = "tests/scripts/mutate-built.txt";
const before = createHash("sha256")
.update(readFileSync(builtTarget))
.digest("hex");
await expect(
execFileAsync(
"timeout",
[
"-s",
"TERM",
"2s",
process.execPath,
cli,
"--built",
"--file",
"tests/scripts/mutate-built.txt",
"--find",
"mutation-built-marker",
"--replace",
"changed",
"--tests",
target,
],
{ cwd: root, env: { ...process.env, PI_LENS_MUTATION_RUN: "1" } },
),
).rejects.toMatchObject({
code: 124,
});
expect(
createHash("sha256").update(readFileSync(builtTarget)).digest("hex"),
).toBe(before);
});
it("restores a SIGKILLed run on the next --restore invocation", async () => {
const before = digest();
const child = spawn(
process.execPath,
[
cli,
"--file",
target,
"--find",
find,
"--replace",
replace,
"--tests",
target,
],
{
cwd: root,
env: { ...process.env, PI_LENS_MUTATION_RUN: "1" },
stdio: ["ignore", "pipe", "ignore"],
},
);
await new Promise((resolve) => child.stdout?.once("data", resolve));
child.kill("SIGKILL");
await new Promise((resolve) => child.once("close", resolve));
expect(digest()).not.toBe(before);
await execFileAsync(process.execPath, [cli, "--restore"], { cwd: root });
expect(digest()).toBe(before);
});
// ---- #4048 round 3: conditional restore (state table rows in the PR body) ----
const builtTarget = "tests/scripts/mutate-built.txt";
const builtArgs = (file: string, ...extra: string[]) => [
cli,
"--built",
"--file",
file,
"--find",
file === builtTarget ? "mutation-built-marker" : find,
"--replace",
file === builtTarget ? "changed" : replace,
"--tests",
target,
...extra,
];
const shaOf = (file: string) =>
createHash("sha256").update(readFileSync(file)).digest("hex");
const journalOf = (file: string) => `${file}.mutate-backup`;
type Held = {
child: ReturnType<typeof spawn>;
stderr: () => string;
closed: Promise<[number | null, NodeJS.Signals | null]>;
};
// A live run: journal written, file mutated, the fixture test holding the child.
async function heldRun(file: string, env: Record<string, string> = {}) {
let stderr = "";
const child = spawn(process.execPath, builtArgs(file), {
cwd: root,
env: { ...process.env, PI_LENS_MUTATION_RUN: "1", ...env },
stdio: ["ignore", "pipe", "pipe"],
});
child.stderr?.on("data", (chunk) => {
stderr += chunk;
});
const closed = new Promise<[number | null, NodeJS.Signals | null]>(
(resolve) => child.once("close", (code, signal) => resolve([code, signal])),
);
await new Promise((resolve) => child.stdout?.once("data", resolve));
return { child, stderr: () => stderr, closed } satisfies Held;
}
async function crashedRun(file: string) {
const held = await heldRun(file);
held.child.kill("SIGKILL");
await held.closed;
}
// Whatever a test leaves behind is put back, so a red assertion cannot dirty
// the tree for the next case.
function forceRestore(file: string, original: Buffer) {
writeFileSync(file, original);
rmSync(journalOf(file), { force: true });
}
async function run(args: string[], env: Record<string, string> = {}) {
try {
const { stdout, stderr } = await execFileAsync(process.execPath, args, {
cwd: root,
env: { ...process.env, ...env },
});
return { code: 0, stdout, stderr };
} catch (error) {
const { code, stdout, stderr } = error as {
code: number;
stdout: string;
stderr: string;
};
return { code, stdout, stderr };
}
}
function expectReport(
output: string,
file: string,
hashes: { original: string; mutated: string; current: string },
) {
expect(output).toContain(journalOf(file));
expect(output).toContain(hashes.original);
expect(output).toContain(hashes.mutated);
expect(output).toContain(hashes.current);
}
it("a second run on the same file refuses while the first run's journal exists", async () => {
// Round-2 recurrence: a normal run restored whatever journal it found, so a
// second run on the same file pulled the live run's mutation out from under it.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
const live = await heldRun(builtTarget);
try {
const mutatedSha = shaOf(builtTarget);
expect(mutatedSha).not.toBe(originalSha);
const second = await run(builtArgs(builtTarget));
expect(second.code).toBe(1);
expectReport(second.stderr, builtTarget, {
original: originalSha,
mutated: mutatedSha,
current: mutatedSha,
});
expect(shaOf(builtTarget)).toBe(mutatedSha);
live.child.kill("SIGTERM");
await live.closed;
expect(shaOf(builtTarget)).toBe(originalSha);
} finally {
live.child.kill("SIGKILL");
await live.closed;
forceRestore(builtTarget, original);
}
}, 60_000);
it("two live runs on different files restore independently", async () => {
// Table row 14: journals are per file; neither run touches the other's file.
const builtOriginal = readFileSync(builtTarget);
const fixtureOriginal = readFileSync(target);
const a = await heldRun(builtTarget);
const b = await heldRun(target);
try {
expect(shaOf(builtTarget)).not.toBe(
createHash("sha256").update(builtOriginal).digest("hex"),
);
expect(shaOf(target)).not.toBe(
createHash("sha256").update(fixtureOriginal).digest("hex"),
);
a.child.kill("SIGTERM");
await a.closed;
expect(readFileSync(builtTarget).equals(builtOriginal)).toBe(true);
expect(shaOf(target)).not.toBe(
createHash("sha256").update(fixtureOriginal).digest("hex"),
);
b.child.kill("SIGTERM");
await b.closed;
expect(readFileSync(target).equals(fixtureOriginal)).toBe(true);
} finally {
a.child.kill("SIGKILL");
b.child.kill("SIGKILL");
await Promise.all([a.closed, b.closed]);
forceRestore(builtTarget, builtOriginal);
forceRestore(target, fixtureOriginal);
}
}, 60_000);
it("a normal run refuses after a crash and --restore restores", async () => {
// Table rows 5 and 8. Round 2 consumed the orphan journal in the next normal
// run, which cannot tell a dead journal from a live one.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
await crashedRun(builtTarget);
try {
const mutatedSha = shaOf(builtTarget);
const normal = await run(builtArgs(builtTarget));
expect(normal.code).toBe(1);
expectReport(normal.stderr, builtTarget, {
original: originalSha,
mutated: mutatedSha,
current: mutatedSha,
});
expect(shaOf(builtTarget)).toBe(mutatedSha);
const restore = await run([cli, "--restore"]);
expect(restore.code).toBe(0);
expect(restore.stdout).toContain("restored 1 mutation journal(s)");
expect(shaOf(builtTarget)).toBe(originalSha);
expect(await run([cli, "--restore", "--file", builtTarget])).toMatchObject({
code: 0,
stdout: expect.stringContaining("restored 0 mutation journal(s)"),
});
} finally {
forceRestore(builtTarget, original);
}
}, 60_000);
it.each([
[
"a normal run",
[
"--built",
"--file",
builtTarget,
"--find",
"mutation-built-marker",
"--replace",
"x",
"--tests",
target,
],
],
["--restore", ["--restore", "--file", builtTarget]],
])(
"%s refuses a journal whose file was legitimately edited afterwards",
async (_name, args) => {
// The round-2 HIGH (rows 7 and 10): the journal overwrote a later edit.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
await crashedRun(builtTarget);
try {
const mutatedSha = shaOf(builtTarget);
writeFileSync(builtTarget, "legitimate later edit\n");
const currentSha = shaOf(builtTarget);
const result = await run([cli, ...args]);
expect(result.code).toBe(1);
expectReport(result.stderr, builtTarget, {
original: originalSha,
mutated: mutatedSha,
current: currentSha,
});
expect(readFileSync(builtTarget, "utf8")).toBe("legitimate later edit\n");
expect(readFileSync(journalOf(builtTarget), "utf8")).toContain(
originalSha,
);
} finally {
forceRestore(builtTarget, original);
}
},
60_000,
);
it.each([
[
"a normal run",
[
"--built",
"--file",
builtTarget,
"--find",
"mutation-built-marker",
"--replace",
"x",
"--tests",
target,
],
],
["--restore", ["--restore", "--file", builtTarget]],
])(
"%s refuses a journal whose file already equals the original",
async (_name, args) => {
// Rows 6 and 9: the journal is stale. Nothing is written, the journal stays
// for explicit recovery, and the report names the hashes.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
await crashedRun(builtTarget);
try {
const mutatedSha = shaOf(builtTarget);
writeFileSync(builtTarget, original);
const result = await run([cli, ...args]);
expect(result.code).toBe(1);
expectReport(result.stderr, builtTarget, {
original: originalSha,
mutated: mutatedSha,
current: originalSha,
});
expect(readFileSync(journalOf(builtTarget), "utf8")).toContain(
mutatedSha,
);
} finally {
forceRestore(builtTarget, original);
}
},
60_000,
);
it("--restore with no journal is a no-op", async () => {
// Table row 3. Drift this prevents: treating an absent journal as a refusal
// would turn every clean --restore sweep into exit 1.
const before = shaOf(builtTarget);
const result = await run([cli, "--restore", "--file", builtTarget]);
expect(result.code).toBe(0);
expect(result.stdout).toContain("restored 0 mutation journal(s)");
expect(shaOf(builtTarget)).toBe(before);
});
it("an unreadable journal is refused and nothing is written", async () => {
// Row 13: a torn or hand-edited journal proves nothing about the file.
const original = readFileSync(builtTarget);
try {
writeFileSync(journalOf(builtTarget), "{ torn");
const before = shaOf(builtTarget);
for (const args of [
[cli, "--restore", "--file", builtTarget],
builtArgs(builtTarget),
]) {
const result = await run(args);
expect(result.code).toBe(1);
expect(result.stderr).toContain(journalOf(builtTarget));
expect(result.stderr).toContain(before);
expect(shaOf(builtTarget)).toBe(before);
}
} finally {
forceRestore(builtTarget, original);
}
}, 60_000);
it.each(["SIGTERM", "SIGINT", "SIGHUP"] as const)(
"a run's own %s cleanup refuses to overwrite a legitimate edit",
async (signal) => {
// Row 12 on the signal path: the in-memory copy in round 2 was written
// back over the edit.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
const live = await heldRun(builtTarget);
try {
const mutatedSha = shaOf(builtTarget);
writeFileSync(builtTarget, "legitimate edit during the run\n");
const currentSha = shaOf(builtTarget);
live.child.kill(signal);
const [, closeSignal] = await live.closed;
expect(closeSignal).toBe(signal);
expect(readFileSync(builtTarget, "utf8")).toBe(
"legitimate edit during the run\n",
);
expectReport(live.stderr(), builtTarget, {
original: originalSha,
mutated: mutatedSha,
current: currentSha,
});
} finally {
live.child.kill("SIGKILL");
await live.closed;
forceRestore(builtTarget, original);
}
},
60_000,
);
it("a finished run whose file was edited meanwhile reports ERROR, exits 4 and keeps the edit", async () => {
// Row 12 on the normal path: the fixture test edits the file mid-run.
const original = readFileSync(builtTarget);
const originalSha = shaOf(builtTarget);
try {
const result = await run(builtArgs(builtTarget), {
PI_LENS_MUTATION_EDIT: builtTarget,
});
expect(result.code).toBe(4);
expect(result.stdout).toContain("ERROR");
expect(result.stdout).toContain(journalOf(builtTarget));
expect(readFileSync(builtTarget, "utf8")).toMatch(/legitimate edit\n$/);
expect(readFileSync(journalOf(builtTarget), "utf8")).toContain(originalSha);
} finally {
forceRestore(builtTarget, original);
}
}, 60_000);
it.each([
["a regex literal", "mutation-regex-only-marker"],
["a template literal's text", "mutation-template-only-marker"],
])(
"refuses a needle that only %s contains, unless --allow-comment",
async (_name, needle) => {
// Round-2 MEDIUM: a regex-literal needle was accepted and reported SURVIVED.
const before = digest();
const refused = await run([
cli,
"--built",
"--file",
target,
"--find",
needle,
"--replace",
"changed",
"--tests",
target,
]);
expect(refused.code).toBe(1);
expect(refused.stdout).toContain("comments/strings/regex literals");
expect(digest()).toBe(before);
const allowed = await run([
cli,
"--allow-comment",
"--built",
"--file",
target,
"--find",
needle,
"--replace",
"changed",
"--tests",
target,
]);
expect(allowed.stdout).toContain("SURVIVED");
expect(digest()).toBe(before);
},
60_000,
);
it.each([
[
"code after a regex literal holding a quote",
"mutationAfterRegex = true",
"mutationAfterRegex = false",
],
["code across a division", "8 / 2", "9 / 3"],
[
"code inside a template substitution",
"mutationQuotient + 1",
"mutationQuotient + 2",
],
])(
"accepts a needle in %s",
async (_name, needle, replacement) => {
// A scanner that treats a slash as a regex start, or a quote in a regex as a
// string start, blanks real code and refuses a valid mutation.
const before = digest();
const result = await run([
cli,
"--built",
"--file",
target,
"--find",
needle,
"--replace",
replacement,
"--tests",
target,
]);
expect(result.code).toBe(0);
expect(result.stdout).toContain("SURVIVED");
expect(digest()).toBe(before);
},
60_000,
);
it("--restore --file restores the compiled twin along with the source", async () => {
// The twin carries its own journal, created before the build and completed
// after it. Round 2 restored only the named file and left the twin's journal
// to block the next run. A leaf client stands in for any built source: the
// serialized lane runs nothing else against it.
const source = "clients/freshness-cadence.ts";
const twin = "clients/freshness-cadence.js";
const sourceOriginal = readFileSync(source);
const twinOriginal = readFileSync(twin);
const child = spawn(
process.execPath,
[
cli,
"--file",
source,
"--find",
"2_000",
"--replace",
"2_001",
"--tests",
target,
],
{
cwd: root,
env: { ...process.env, PI_LENS_MUTATION_RUN: "1" },
stdio: ["ignore", "pipe", "ignore"],
},
);
const stdoutSeen = new Promise((resolve) =>
child.stdout?.once("data", resolve),
);
const closed = new Promise((resolve) => child.once("close", resolve));
try {
await stdoutSeen;
child.kill("SIGKILL");
await closed;
expect(readFileSync(source).equals(sourceOriginal)).toBe(false);
expect(readFileSync(twin).equals(twinOriginal)).toBe(false);
const restore = await run([cli, "--restore", "--file", source]);
expect(restore.code).toBe(0);
expect(restore.stdout).toContain("restored 2 mutation journal(s)");
expect(readFileSync(source).equals(sourceOriginal)).toBe(true);
expect(readFileSync(twin).equals(twinOriginal)).toBe(true);
} finally {
child.kill("SIGKILL");
await closed;
forceRestore(source, sourceOriginal);
forceRestore(twin, twinOriginal);
}
}, 60_000);
+3
View File
@@ -69,6 +69,7 @@
"scripts/check-allow-scripts.test.ts": 3,
"scripts/check-lockfile-sync.test.ts": 2,
"scripts/check-pr-body.test.ts": 9,
"scripts/ci-test-diff.test.ts": 2,
"scripts/ci-verdict.test.ts": 4,
"scripts/classify-ci-failure-cli.test.ts": 2,
"scripts/download-grammars.test.ts": 2,
@@ -79,6 +80,7 @@
"scripts/knip-sibling-purge.test.ts": 1,
"scripts/lint-js.test.ts": 6,
"scripts/lockfile-completeness.test.ts": 1,
"scripts/mutate.test.ts": 1,
"scripts/mutation-report-render.test.ts": 3,
"scripts/notify-install-smoke-drift.test.ts": 5,
"scripts/notify-tool-smoke-red.test.ts": 5,
@@ -337,6 +339,7 @@
"clients/runtime-session-sequence-read-budget.test.ts": 1,
"index-2939-read-path-witness.test.ts": 1,
"index-2939-tool-result-budget-witness.test.ts": 1,
"scripts/mutate-fixture.test.ts": 1,
"tools/lsp-diagnostics-silent-clean-flow.test.ts": 1,
"tools/lsp-diagnostics.test.ts": 1
}
+8
View File
@@ -499,6 +499,9 @@ export const wallClockBudgetInclude = [
// subject; an in-process call of the pure policy cannot prove that boundary.
"tests/scripts/check-allow-scripts.test.ts",
"tests/scripts/check-pr-body.test.ts",
// #4072 review F2: the CLI's real exit status is the contract; an
// in-process main() call cannot prove the executable entry point.
"tests/scripts/ci-test-diff.test.ts",
// #3883 F3: the final `ci-verdict: exit` line is emitted by the real
// `main()` process; the spawn is the only faithful proof of that boundary.
"tests/scripts/ci-verdict.test.ts",
@@ -532,6 +535,11 @@ export const wallClockBudgetInclude = [
// admission).
"tests/scripts/lint-js.test.ts",
"tests/scripts/lockfile-completeness.test.ts",
// #4048: the mutation helper's real child and SIGINT restoration witness
// require a quiet serialized phase; its bounded timer and never-settling
// fixture are the process boundary under test (flake-shape admission).
"tests/scripts/mutate-fixture.test.ts",
"tests/scripts/mutate.test.ts",
// #3531: the mutation-report CLI smoke test spawns a real node child to
// prove its own argv parsing (--report/--out), not just the exported
// render function (flake-shape admission).