From cadb3d37717042ce5692a56530270b3c5ec918a9 Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:53:17 -0700 Subject: [PATCH 1/6] Add --timeout and keep sandbox writes out of the real node_modules --timeout sets the limit for the baseline run and each mutant run (1000..86400000 ms). A baseline timeout now reports the limit and names the option instead of a generic baseline failure. Sandboxes used to link the whole node_modules directory. In a pnpm workspace, pnpm's pre-run install inside the sandbox rewrote the real tree through that link: workspace links were re-pointed into the sandbox, which killdiff then deleted, leaving the clone's links dangling. pnpm 12 also refuses to run under a linked node_modules, and workspace links kept pointing at the unmutated original packages. Each sandbox now rebuilds node_modules (and .pnpm, scopes and nested node_modules) as its own directories, links package contents, copies pnpm state directories, and re-points links that target the repository at the sandbox copy. Cleanup unlinks every link before removing the sandbox, so it never follows a link. Reproduced on a disposable pnpm 12.21 workspace: before, the clone's packages/app/node_modules/@fx/core pointed into a deleted sandbox and its tests failed; after, node_modules is unchanged and the workspace mutant is killed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + README.md | 7 +- src/cli.ts | 16 ++++ src/runner/sandbox.ts | 119 +++++++++++++++++++++-- tests/timeout-and-deps.test.ts | 169 +++++++++++++++++++++++++++++++++ 5 files changed, 307 insertions(+), 9 deletions(-) create mode 100644 tests/timeout-and-deps.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f17524..3d3a716 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,13 @@ All notable changes to killdiff are recorded here. The format follows [Keep a Ch ## [Unreleased] ### Added +- `--timeout ` sets the time limit for the baseline run and each mutant run (1000 to 86400000 ms). A baseline timeout now reports the limit and names the option. - `killdiff --version` and `-v` print the package version. Help and the MCP server read the same constant, and a test keeps it equal to `package.json`. +### Fixed +- Sandboxes no longer link the whole `node_modules` directory. A pnpm workspace run could rewrite the real tree through the link (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each sandbox now rebuilds the directory, links package contents, copies pnpm state, and re-points links that target the repository at the sandbox copy, so workspace-package mutants are actually exercised. +- Sandbox cleanup unlinks every link before removing the directory. + ### Changed - README now leads with the problem, a 30-second quick start with recorded output, and install options. diff --git a/README.md b/README.md index 3c8c272..f03d10f 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,9 @@ npx killdiff main...HEAD --sarif > killdiff.sarif # Override the test runner explicitly npx killdiff main...HEAD --cmd "pytest -q" + +# Allow a slow suite (80 s baseline) up to 3 minutes per run +npx killdiff main...HEAD --cmd "go test ./..." --timeout 180000 ``` --- @@ -111,8 +114,8 @@ npx killdiff main...HEAD --cmd "pytest -q" - **Diff-only scope:** Parses `git diff --unified=0` so only executable code on changed lines is mutated (skips test files, comments, strings, imports, and type declarations). - **Polyglot on Day 1:** Mutates TypeScript/JavaScript, Python, Go, and Rust across boundary (`>=`/`>`, `<=`/`<`), equality (`===`/`!==`, `==`/`!=`), logical (`&&`/`||`, `and`/`or`), boolean (`true`/`false`, `True`/`False`), and arithmetic (`+`/`-`) operators. -- **Isolated parallel sandboxes:** Never edits your real working tree. Creates ephemeral temp workspaces symlinking/junctioning `node_modules`/`.venv`/`target` for fast setup and cleans up automatically. -- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). +- **Isolated parallel sandboxes:** Never edits your real working tree. Creates ephemeral temp workspaces and cleans up automatically. Each sandbox rebuilds `node_modules` as its own directory, linking package contents and re-pointing workspace links at the sandbox copy, so pnpm or npm workspace writes stay in the sandbox and mutants in workspace packages are tested. `.venv` and `target` are linked. Cleanup removes links without following them. +- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). The baseline limit defaults to 60 s and each mutant gets 2.5x the baseline time; `--timeout ` sets both. --- diff --git a/src/cli.ts b/src/cli.ts index 43c1583..1b6b802 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -18,6 +18,7 @@ export interface ParsedCliArgs { maxMutants: number; concurrency: number; failUnder?: number; + timeoutMs?: number; format: "terminal" | "json" | "markdown" | "sarif"; } @@ -34,6 +35,8 @@ Options: --max Maximum mutants to run (default: 25) --concurrency Parallel worker sandboxes (default: 4) --fail-under Exit code 1 if mutation score is below (0-100) + --timeout Time limit for the baseline run and each mutant run + (default: 60000 baseline, 2.5x baseline per mutant) --json Output JSON report --markdown Output Markdown PR summary table --sarif Output SARIF 2.1.0 report @@ -41,6 +44,9 @@ Options: -v, --version Show version`); } +const MIN_TIMEOUT_MS = 1_000; +const MAX_TIMEOUT_MS = 86_400_000; + function requireVal(argv: string[], i: number, flag: string): string { const v = argv[i + 1]; if (!v || v.trim().startsWith("-")) throw new Error(`Missing value for ${flag}`); @@ -101,6 +107,15 @@ export function parseCliArgs(argv: string[]): ParsedCliArgs { parsed.concurrency = n; explicitRunOption = true; i++; + } else if (arg === "--timeout") { + const raw = requireVal(argv, i, "--timeout"); + const n = Number(raw); + if (!/^[0-9]+$/.test(raw.trim()) || !Number.isSafeInteger(n) || n < MIN_TIMEOUT_MS || n > MAX_TIMEOUT_MS) { + throw new Error(`--timeout must be an integer number of milliseconds ${MIN_TIMEOUT_MS}..${MAX_TIMEOUT_MS}`); + } + parsed.timeoutMs = n; + explicitRunOption = true; + i++; } else if (arg === "--fail-under") { const n = Number(requireVal(argv, i, "--fail-under")); if (!Number.isFinite(n) || n < 0 || n > 100) throw new Error("--fail-under must be 0..100"); @@ -161,6 +176,7 @@ async function main(): Promise { range: args.range ?? "working-tree", concurrency: args.concurrency, maxMutants: args.maxMutants, + timeoutMs: args.timeoutMs, }); })(); diff --git a/src/runner/sandbox.ts b/src/runner/sandbox.ts index 4ba99f8..2cccf40 100644 --- a/src/runner/sandbox.ts +++ b/src/runner/sandbox.ts @@ -2,21 +2,28 @@ import { spawn, spawnSync } from "node:child_process"; import { cpSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, + statSync, symlinkSync, + unlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { isAbsolute, join, relative } from "node:path"; import { resolveContainedPath } from "../git/diff.js"; import type { Mutant, MutantRunResult, MutantStatus, MutationReport } from "../types.js"; const HEAVY_DEPENDENCY_DIRS = new Set(["node_modules", ".venv", "venv", "target"]); +const DEFAULT_BASELINE_TIMEOUT_MS = 60_000; +// Directories inside node_modules that are rebuilt per sandbox instead of linked, so that +// package-manager writes (pnpm's pre-run install, state files, relinks) stay in the sandbox. +const MAX_MIRROR_DEPTH = 4; const SKIP_COPY_DIRS = new Set([".git", ".next", ".nuxt", "coverage", ".superpowers"]); export interface RunMutationSuiteOptions { @@ -90,7 +97,70 @@ function execShellCommand( }); } -function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { +interface SandboxContext { + repoReal: string; + sandboxDir: string; +} + +function linkDirectory(target: string, dst: string): void { + symlinkSync(target, dst, process.platform === "win32" ? "junction" : "dir"); +} + +/** A link target inside the repository is re-pointed at the same path in the sandbox. */ +function sandboxTarget(target: string, ctx: SandboxContext): string { + const rel = relative(ctx.repoReal, target); + if (rel === "") return ctx.sandboxDir; + if (!rel.startsWith("..") && !isAbsolute(rel)) return join(ctx.sandboxDir, rel); + return target; +} + +/** + * Rebuild a node_modules directory in the sandbox. Package contents are linked, but the + * directory structure, links and state files are the sandbox's own. Linking the whole + * node_modules let a sandboxed pnpm install rewrite the real tree (its workspace links then + * pointed into a sandbox that was deleted), and kept workspace links aimed at the unmutated + * original packages. + */ +function mirrorNodeModules(srcDir: string, dstDir: string, ctx: SandboxContext, depth = 0): void { + mkdirSync(dstDir, { recursive: true }); + for (const entry of readdirSync(srcDir, { withFileTypes: true })) { + const src = join(srcDir, entry.name); + const dst = join(dstDir, entry.name); + if (entry.isSymbolicLink()) { + let target: string; + try { + target = realpathSync(src); + } catch { + continue; // dangling link: nothing to expose + } + const mapped = sandboxTarget(target, ctx); + if (statSync(target).isDirectory()) { + linkDirectory(mapped, dst); + } else { + try { + symlinkSync(mapped, dst, "file"); + } catch { + cpSync(target, dst); + } + } + continue; + } + if (entry.isDirectory()) { + const structural = entry.name === "node_modules" || entry.name === ".pnpm" || entry.name.startsWith("@"); + if (structural && depth < MAX_MIRROR_DEPTH) { + mirrorNodeModules(src, dst, ctx, depth + 1); + } else if (entry.name.startsWith(".pnpm-")) { + cpSync(src, dst, { recursive: true }); // small pnpm state directories, written during runs + } else { + linkDirectory(realpathSync(src), dst); + } + continue; + } + cpSync(src, dst); + } +} + +function copyTreeLinkingDeps(srcDir: string, dstDir: string, ctx: SandboxContext, depth = 0): void { for (const entry of readdirSync(srcDir, { withFileTypes: true })) { if (depth === 0 && SKIP_COPY_DIRS.has(entry.name)) continue; if (entry.name === ".git") continue; @@ -98,6 +168,11 @@ function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { const src = join(srcDir, entry.name); const dst = join(dstDir, entry.name); + if (entry.name === "node_modules" && (entry.isDirectory() || entry.isSymbolicLink())) { + mirrorNodeModules(realpathSync(src), dst, ctx); + continue; + } + if (HEAVY_DEPENDENCY_DIRS.has(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())) { try { const target = realpathSync(src); @@ -110,7 +185,7 @@ function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { if (entry.isDirectory() && depth < 3) { mkdirSync(dst, { recursive: true }); - copyTreeLinkingDeps(src, dst, depth + 1); + copyTreeLinkingDeps(src, dst, ctx, depth + 1); continue; } @@ -121,10 +196,11 @@ function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { function createIsolatedWorkspace(repoDir: string): string { const sandboxDir = mkdtempSync(join(tmpdir(), "killdiff-box-")); try { - copyTreeLinkingDeps(repoDir, sandboxDir, 0); + copyTreeLinkingDeps(repoDir, sandboxDir, { repoReal: realpathSync(repoDir), sandboxDir }, 0); return sandboxDir; } catch (err) { try { + detachLinks(sandboxDir); rmSync(sandboxDir, { recursive: true, force: true }); } catch { // best effort cleanup @@ -153,9 +229,32 @@ export function applyMutantToWorkspace(sandboxDir: string, mutant: Mutant): void writeFileSync(target, lines.join(eol), "utf8"); } +/** Remove every link in the sandbox without following it, so cleanup never reaches link targets. */ +function detachLinks(dir: string): void { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const path = join(dir, entry.name); + if (entry.isSymbolicLink() || lstatSync(path).isSymbolicLink()) { + try { + unlinkSync(path); + } catch { + // retried by removeDirSafe + } + } else if (entry.isDirectory()) { + detachLinks(path); + } + } +} + async function removeDirSafe(dir: string): Promise { for (let i = 0; i < 10; i++) { try { + detachLinks(dir); rmSync(dir, { recursive: true, force: true }); if (!existsSync(dir)) return; } catch { @@ -191,11 +290,17 @@ export async function runMutationSuite(opts: RunMutationSuiteOptions): Promise for slow suites.` + ); + } + if (baseRun.exitCode !== 0) { throw new Error( - `Baseline test command failed (exit ${baseRun.exitCode}${baseRun.timedOut ? ", timed out" : ""}): "${opts.testCmd}". Fix baseline tests before running killdiff.` + `Baseline test command failed (exit ${baseRun.exitCode}): "${opts.testCmd}". Fix baseline tests before running killdiff.` ); } } finally { diff --git a/tests/timeout-and-deps.test.ts b/tests/timeout-and-deps.test.ts new file mode 100644 index 0000000..1472248 --- /dev/null +++ b/tests/timeout-and-deps.test.ts @@ -0,0 +1,169 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { execFileSync } from "node:child_process"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + readlinkSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { parseCliArgs } from "../src/cli.js"; +import { runMutationSuite } from "../src/runner/sandbox.js"; +import { generateMutantsForFile } from "../src/mutate/operators.js"; + +const linkType = process.platform === "win32" ? "junction" : "dir"; + +function removeTemp(dir: string): void { + // Unlink links first so test cleanup never walks through them. + const walk = (d: string) => { + for (const name of readdirSync(d)) { + const p = join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) rmSync(p, { force: true }); + else if (st.isDirectory()) walk(p); + } + }; + if (existsSync(dir)) walk(dir); + rmSync(dir, { recursive: true, force: true }); +} + +describe("--timeout option", () => { + it("parses a millisecond timeout and rejects invalid values", () => { + expect(parseCliArgs(["--timeout", "90000"]).timeoutMs).toBe(90_000); + expect(parseCliArgs(["main...HEAD", "--timeout", "1000"]).timeoutMs).toBe(1_000); + expect(parseCliArgs(["--timeout", "86400000"]).timeoutMs).toBe(86_400_000); + expect(parseCliArgs([]).timeoutMs).toBeUndefined(); + for (const bad of ["0", "999", "abc", "1.5", "-5", "86400001", "1e4", "0x1388"]) { + expect(() => parseCliArgs(["--timeout", bad])).toThrow(/--timeout/); + } + expect(() => parseCliArgs(["--timeout"])).toThrow(/--timeout/); + expect(() => parseCliArgs(["mcp", "--timeout", "5000"])).toThrow(); + }); + + it("documents --timeout in the built CLI help", () => { + const out = execFileSync(process.execPath, [resolve(process.cwd(), "dist/cli.js"), "--help"], { encoding: "utf8" }); + expect(out).toMatch(/--timeout /); + }); + + const tempDirs: string[] = []; + afterEach(() => { + while (tempDirs.length > 0) removeTemp(tempDirs.pop()!); + }); + + it("applies the timeout to the baseline run and names the option on failure", async () => { + const repo = mkdtempSync(join(tmpdir(), "kd-timeout-")); + tempDirs.push(repo); + const src = "export const limit = 1 + 1;\n"; + writeFileSync(join(repo, "lib.mjs"), src); + writeFileSync(join(repo, "slow.mjs"), "setTimeout(() => process.exit(0), 1500);\n"); + const mutants = generateMutantsForFile("lib.mjs", src, new Set([1])); + expect(mutants.length).toBeGreaterThan(0); + const testCmd = `"${process.execPath}" slow.mjs`; + + await expect( + runMutationSuite({ repoDir: repo, mutants, testCmd, maxMutants: 1, concurrency: 1, timeoutMs: 1_000 }) + ).rejects.toThrow(/timed out after 1000 ms.*--timeout/); + + const report = await runMutationSuite({ repoDir: repo, mutants, testCmd, maxMutants: 1, concurrency: 1, timeoutMs: 20_000 }); + expect(report.baselineMs).toBeGreaterThanOrEqual(1_000); + expect(report.totalMutants).toBe(1); + }, 60_000); +}); + +describe("dependency directories in sandboxes", () => { + const tempDirs: string[] = []; + afterEach(() => { + while (tempDirs.length > 0) removeTemp(tempDirs.pop()!); + }); + + it("keeps package-manager writes out of the real node_modules and sees mutants in linked workspace packages", async () => { + // The repository sits deeper than the sandbox so a wrongly re-pointed outside link breaks. + const holder = realpathSync(mkdtempSync(join(tmpdir(), "kd-ws-"))); + const repo = join(holder, "nested", "repo"); + mkdirSync(repo, { recursive: true }); + const outside = realpathSync(mkdtempSync(join(tmpdir(), "kd-store-"))); + tempDirs.push(holder, outside); + + // Workspace package linked from node_modules by absolute path, as pnpm and npm workspaces do. + mkdirSync(join(repo, "packages", "core"), { recursive: true }); + const coreSrc = "export function add(a, b) {\n return a + b;\n}\n"; + writeFileSync(join(repo, "packages", "core", "index.mjs"), coreSrc); + writeFileSync(join(repo, "packages", "core", "package.json"), JSON.stringify({ name: "@fx/core", type: "module", main: "index.mjs" })); + // An external store package, linked from outside the repo. + mkdirSync(join(outside, "ext"), { recursive: true }); + writeFileSync(join(outside, "ext", "package.json"), JSON.stringify({ name: "ext", main: "index.js" })); + writeFileSync(join(outside, "ext", "index.js"), "module.exports = 7;\n"); + + const nm = join(repo, "node_modules"); + mkdirSync(join(nm, "@fx"), { recursive: true }); + symlinkSync(join(repo, "packages", "core"), join(nm, "@fx", "core"), linkType); + symlinkSync(join(outside, "ext"), join(nm, "ext"), linkType); + writeFileSync(join(nm, ".state.json"), "original\n"); + // pnpm layout: .pnpm holds a lock file and its own node_modules with a workspace link. + mkdirSync(join(nm, ".pnpm", "node_modules", "@fx"), { recursive: true }); + writeFileSync(join(nm, ".pnpm", "lock.yaml"), "lock\n"); + symlinkSync(join(repo, "packages", "core"), join(nm, ".pnpm", "node_modules", "@fx", "core"), linkType); + mkdirSync(join(nm, ".pnpm-task-run-state-v1")); + writeFileSync(join(nm, ".pnpm-task-run-state-v1", "latest.json"), "{}\n"); + + // The test behaves like pnpm's pre-run install: it rewrites state, relinks the workspace + // package to the current directory and adds a file, all under ./node_modules. + writeFileSync( + join(repo, "test.mjs"), + [ + 'import assert from "node:assert/strict";', + 'import { existsSync, lstatSync, rmSync, symlinkSync, writeFileSync } from "node:fs";', + 'import { createRequire } from "node:module";', + 'import { join } from "node:path";', + 'writeFileSync("node_modules/.state.json", "rewritten by sandbox\\n");', + 'writeFileSync("node_modules/added-by-sandbox.txt", "x");', + 'writeFileSync("node_modules/.pnpm/lock.yaml", "rewritten\\n");', + 'writeFileSync("node_modules/.pnpm/node_modules/hoisted-by-sandbox.txt", "x");', + 'if (!existsSync("node_modules/.pnpm/node_modules/@fx/core/index.mjs")) process.exit(5);', + 'writeFileSync("node_modules/.pnpm-task-run-state-v1/latest.json", "{\\"sandbox\\":true}\\n");', + 'if (!lstatSync("node_modules/.pnpm-task-run-state-v1").isDirectory() || lstatSync("node_modules").isSymbolicLink()) process.exit(3);', + 'rmSync("node_modules/@fx/core", { force: true });', + `symlinkSync(join(process.cwd(), "packages", "core"), "node_modules/@fx/core", ${JSON.stringify(linkType)});`, + 'assert.equal(createRequire(import.meta.url)("ext"), 7);', + 'const { add } = await import("@fx/core");', + "assert.equal(add(2, 3), 5);", + 'if (!existsSync("packages/core/index.mjs")) process.exit(4);', + ].join("\n") + ); + + const mutants = generateMutantsForFile("packages/core/index.mjs", coreSrc, new Set([2])); + expect(mutants.some((m) => m.original === "+")).toBe(true); + const report = await runMutationSuite({ + repoDir: repo, + mutants, + testCmd: `"${process.execPath}" test.mjs`, + concurrency: 2, + maxMutants: 5, + }); + + // The mutated workspace package is the one the test imports, so `+` -> `-` is killed. + const plus = report.results.find((r) => r.mutant.original === "+"); + expect(plus?.status).toBe("KILLED"); + + // The real repository's dependency tree is unchanged. + expect(realpathSync(join(nm, "@fx", "core"))).toBe(join(repo, "packages", "core")); + expect(readlinkSync(join(nm, "@fx", "core")).replace(/[\\/]+$/, "")).toBe(join(repo, "packages", "core")); + expect(readFileSync(join(nm, ".state.json"), "utf8")).toBe("original\n"); + expect(readFileSync(join(nm, ".pnpm-task-run-state-v1", "latest.json"), "utf8")).toBe("{}\n"); + expect(existsSync(join(nm, "added-by-sandbox.txt"))).toBe(false); + expect(readFileSync(join(nm, ".pnpm", "lock.yaml"), "utf8")).toBe("lock\n"); + expect(existsSync(join(nm, ".pnpm", "node_modules", "hoisted-by-sandbox.txt"))).toBe(false); + expect(realpathSync(join(nm, ".pnpm", "node_modules", "@fx", "core"))).toBe(join(repo, "packages", "core")); + expect(readFileSync(join(repo, "packages", "core", "index.mjs"), "utf8")).toBe(coreSrc); + // Sandbox cleanup removed links only; the linked external package is intact. + expect(readFileSync(join(outside, "ext", "index.js"), "utf8")).toBe("module.exports = 7;\n"); + }, 60_000); +}); From 8e66b493717b8dcafc178cfa62b8aa4f59ce380f Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:25:46 -0700 Subject: [PATCH 2/6] Release 0.1.1: accept timeoutMs in the MCP tool verify_diff_tests takes timeoutMs with the same 1000..86400000 bounds as --timeout, shared from the runner. Version 0.1.1 and changelog. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++- README.md | 2 +- package-lock.json | 4 +-- package.json | 2 +- src/cli.ts | 5 +--- src/mcp/server.ts | 30 ++++++++++++++++++-- src/runner/sandbox.ts | 2 ++ src/version.ts | 2 +- tests/timeout-and-deps.test.ts | 50 ++++++++++++++++++++++++++++++++++ 9 files changed, 90 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3a716..c7196b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,11 @@ All notable changes to killdiff are recorded here. The format follows [Keep a Ch ## [Unreleased] +## [0.1.1] - 2026-11-29 + ### Added - `--timeout ` sets the time limit for the baseline run and each mutant run (1000 to 86400000 ms). A baseline timeout now reports the limit and names the option. +- The MCP tool `verify_diff_tests` accepts `timeoutMs` with the same bounds. - `killdiff --version` and `-v` print the package version. Help and the MCP server read the same constant, and a test keeps it equal to `package.json`. ### Fixed @@ -32,5 +35,6 @@ First public release. - A reusable composite GitHub Action (`action.yml`). - `killdiff --demo`: a self-contained demo on a temporary repo. -[Unreleased]: https://github.com/flipcyde101/killdiff/compare/v0.1.0...HEAD +[Unreleased]: https://github.com/flipcyde101/killdiff/compare/v0.1.1...HEAD +[0.1.1]: https://github.com/flipcyde101/killdiff/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/flipcyde101/killdiff/releases/tag/v0.1.0 diff --git a/README.md b/README.md index f03d10f..0c0410d 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ npx killdiff main...HEAD --cmd "go test ./..." --timeout 180000 ## Connect to Your Coding Agent (Stdio MCP) -`killdiff mcp` exposes `verify_diff_tests` so **Antigravity**, Claude Code, Codex, Cursor, and OpenCode can verify their own newly written tests actually kill logic mutations before handing a PR back to you. +`killdiff mcp` exposes `verify_diff_tests` so **Antigravity**, Claude Code, Codex, Cursor, and OpenCode can verify their own newly written tests actually kill logic mutations before handing a PR back to you. Arguments: `range`, `testCmd`, `maxMutants` and `timeoutMs`. ```json { diff --git a/package-lock.json b/package-lock.json index 8aab54a..00e7dc3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "killdiff", - "version": "0.1.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "killdiff", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "bin": { "killdiff": "dist/cli.js" diff --git a/package.json b/package.json index da07bc0..88acede 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "killdiff", - "version": "0.1.0", + "version": "0.1.1", "description": "Zero-config polyglot diff-only mutation tester that catches hollow AI-generated tests in seconds (CLI, stdio MCP server, and GitHub Action).", "license": "MIT", "type": "module", diff --git a/src/cli.ts b/src/cli.ts index 1b6b802..c8f1159 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; import { getGitDiffHunks, resolveContainedPath, validateGitRange } from "./git/diff.js"; import { generateMutantsForFile } from "./mutate/operators.js"; import { detectTestCommand } from "./runner/detect.js"; -import { runMutationSuite } from "./runner/sandbox.js"; +import { MAX_TIMEOUT_MS, MIN_TIMEOUT_MS, runMutationSuite } from "./runner/sandbox.js"; import { formatMarkdownReport, formatSarifReport, formatTerminalReport } from "./report/format.js"; import { startMcpStdioServer } from "./mcp/server.js"; import { runDemoMutationCheck } from "./demo/fixture.js"; @@ -44,9 +44,6 @@ Options: -v, --version Show version`); } -const MIN_TIMEOUT_MS = 1_000; -const MAX_TIMEOUT_MS = 86_400_000; - function requireVal(argv: string[], i: number, flag: string): string { const v = argv[i + 1]; if (!v || v.trim().startsWith("-")) throw new Error(`Missing value for ${flag}`); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 39d3f3e..a2c2465 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -5,7 +5,7 @@ import { resolve } from "node:path"; import { getGitDiffHunks, resolveContainedPath } from "../git/diff.js"; import { generateMutantsForFile } from "../mutate/operators.js"; import { detectTestCommand } from "../runner/detect.js"; -import { runMutationSuite } from "../runner/sandbox.js"; +import { MAX_TIMEOUT_MS, MIN_TIMEOUT_MS, runMutationSuite } from "../runner/sandbox.js"; import type { Mutant, MutationReport } from "../types.js"; import { KILLDIFF_VERSION } from "../version.js"; @@ -13,7 +13,7 @@ export interface McpServerOptions { input?: Readable; output?: Writable; workspaceDir: string; - verifyFn?: (args: { range?: string; testCmd?: string; maxMutants?: number; cwd?: string }) => Promise; + verifyFn?: (args: { range?: string; testCmd?: string; maxMutants?: number; timeoutMs?: number; cwd?: string }) => Promise; } interface JsonRpcRequest { @@ -34,6 +34,10 @@ const TOOL_DEFINITIONS = [ range: { type: "string", description: "Git diff range (e.g. main...HEAD or HEAD~1...HEAD). Omit for unstaged working tree diff." }, testCmd: { type: "string", description: "Optional test command override (auto-detected if omitted)." }, maxMutants: { type: "number", description: "Max mutants to test (default: 25)." }, + timeoutMs: { + type: "number", + description: "Time limit in ms for the baseline run and each mutant run (1000..86400000). Default: 60000 baseline, 2.5x baseline per mutant.", + }, }, }, }, @@ -52,7 +56,7 @@ function isValidJsonRpcId(v: unknown): v is string | number | null { async function defaultVerifyDiffTests( defaultCwd: string, - args: { range?: string; testCmd?: string; maxMutants?: number; cwd?: string } + args: { range?: string; testCmd?: string; maxMutants?: number; timeoutMs?: number; cwd?: string } ): Promise { const repoDir = args.cwd ? resolve(args.cwd) : defaultCwd; const hunks = getGitDiffHunks(repoDir, args.range); @@ -72,6 +76,7 @@ async function defaultVerifyDiffTests( testCmd, range: args.range ?? "working-tree", maxMutants: args.maxMutants ?? 25, + timeoutMs: args.timeoutMs, }); } @@ -184,6 +189,24 @@ export function startMcpStdioServer(opts: McpServerOptions): () => void { maxMutants = args.maxMutants; } + let timeoutMs: number | undefined; + if (args.timeoutMs !== undefined) { + if ( + typeof args.timeoutMs !== "number" || + !Number.isInteger(args.timeoutMs) || + args.timeoutMs < MIN_TIMEOUT_MS || + args.timeoutMs > MAX_TIMEOUT_MS + ) { + send({ + jsonrpc: "2.0", + id: req.id, + error: { code: -32602, message: `Invalid params: timeoutMs must be an integer ${MIN_TIMEOUT_MS}..${MAX_TIMEOUT_MS}` }, + }); + return; + } + timeoutMs = args.timeoutMs; + } + try { if (toolName !== "verify_diff_tests") { throw new Error(`Unknown MCP tool: ${toolName}`); @@ -192,6 +215,7 @@ export function startMcpStdioServer(opts: McpServerOptions): () => void { range: args.range as string | undefined, testCmd: args.testCmd as string | undefined, maxMutants, + timeoutMs, }); const compact = { range: report.range, diff --git a/src/runner/sandbox.ts b/src/runner/sandbox.ts index 2cccf40..6e081b3 100644 --- a/src/runner/sandbox.ts +++ b/src/runner/sandbox.ts @@ -21,6 +21,8 @@ import type { Mutant, MutantRunResult, MutantStatus, MutationReport } from "../t const HEAVY_DEPENDENCY_DIRS = new Set(["node_modules", ".venv", "venv", "target"]); const DEFAULT_BASELINE_TIMEOUT_MS = 60_000; +export const MIN_TIMEOUT_MS = 1_000; +export const MAX_TIMEOUT_MS = 86_400_000; // Directories inside node_modules that are rebuilt per sandbox instead of linked, so that // package-manager writes (pnpm's pre-run install, state files, relinks) stay in the sandbox. const MAX_MIRROR_DEPTH = 4; diff --git a/src/version.ts b/src/version.ts index 2b6f80e..40170e5 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ /** Package version, kept in step with package.json by tests/version.test.ts. */ -export const KILLDIFF_VERSION = "0.1.0"; +export const KILLDIFF_VERSION = "0.1.1"; diff --git a/tests/timeout-and-deps.test.ts b/tests/timeout-and-deps.test.ts index 1472248..c9fa328 100644 --- a/tests/timeout-and-deps.test.ts +++ b/tests/timeout-and-deps.test.ts @@ -15,7 +15,9 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { PassThrough } from "node:stream"; import { parseCliArgs } from "../src/cli.js"; +import { startMcpStdioServer } from "../src/mcp/server.js"; import { runMutationSuite } from "../src/runner/sandbox.js"; import { generateMutantsForFile } from "../src/mutate/operators.js"; @@ -78,6 +80,54 @@ describe("--timeout option", () => { }, 60_000); }); +describe("MCP verify_diff_tests timeoutMs", () => { + it("passes a valid timeoutMs to the runner and rejects invalid values", async () => { + const input = new PassThrough(); + const output = new PassThrough(); + const lines: Record[] = []; + output.on("data", (chunk: Buffer) => { + for (const l of chunk.toString("utf8").split("\n").filter(Boolean)) lines.push(JSON.parse(l)); + }); + const seen: Array = []; + const stop = startMcpStdioServer({ + input, + output, + workspaceDir: process.cwd(), + verifyFn: async (args) => { + seen.push(args.timeoutMs); + return { range: "working-tree", testCmd: "x", baselineMs: 1, durationMs: 1, totalMutants: 0, killed: 0, survived: 0, timedOut: 0, mutationScore: 100, results: [] }; + }, + }); + const call = (id: number, extra: string) => + input.write(`{"jsonrpc":"2.0","id":${id},"method":"tools/call","params":{"name":"verify_diff_tests","arguments":{${extra}}}}\n`); + try { + call(1, '"timeoutMs":120000'); + call(2, ""); + call(3, '"timeoutMs":999'); + call(4, '"timeoutMs":86400001'); + call(5, '"timeoutMs":"5000"'); + call(6, '"timeoutMs":1500.5'); + call(7, '"timeoutMs":86400000'); + call(8, '"timeoutMs":1000'); + await new Promise((r) => setTimeout(r, 150)); + expect(seen).toEqual([120_000, undefined, 86_400_000, 1_000]); + for (const id of [3, 4, 5, 6]) { + const msg = lines.find((m) => m.id === id); + expect((msg?.error as { code?: number; message?: string } | undefined)?.message).toMatch(/timeoutMs must be an integer 1000\.\.86400000/); + } + const list = TOOL_LIST_REQUEST; + input.write(list); + await new Promise((r) => setTimeout(r, 50)); + const tools = (lines.find((m) => m.id === 99)?.result as { tools: Array<{ inputSchema: { properties: Record } }> }).tools; + expect(tools[0].inputSchema.properties).toHaveProperty("timeoutMs"); + } finally { + stop(); + } + }); +}); + +const TOOL_LIST_REQUEST = '{"jsonrpc":"2.0","id":99,"method":"tools/list","params":{}}\n'; + describe("dependency directories in sandboxes", () => { const tempDirs: string[] = []; afterEach(() => { From 3e080e2bdcc412b08d45c5726344f99c1be8ab8e Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:47:54 -0700 Subject: [PATCH 3/6] Isolate build output, limit sandbox mirroring to pnpm, build asynchronously From independent review of the 0.1.1 candidate: - Rust and Maven target directories are no longer linked into sandboxes, so binaries built from a mutant cannot stay in the real target/. A CARGO_TARGET_DIR from the environment is redirected into the sandbox. - Only pnpm projects get a rebuilt node_modules (one link per .pnpm store entry, empty tool caches). npm and Yarn layouts link node_modules as before. - pnpm's install-before-run check is off for sandbox runs. - Sandbox creation and removal are asynchronous, so one worker's setup cannot push another worker into a false timeout. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 +- README.md | 9 +- src/runner/sandbox.ts | 215 +++++++++++++++++------------ tests/sandbox-isolation.test.ts | 231 ++++++++++++++++++++++++++++++++ 4 files changed, 367 insertions(+), 92 deletions(-) create mode 100644 tests/sandbox-isolation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c7196b4..765804c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,9 @@ All notable changes to killdiff are recorded here. The format follows [Keep a Ch - `killdiff --version` and `-v` print the package version. Help and the MCP server read the same constant, and a test keeps it equal to `package.json`. ### Fixed -- Sandboxes no longer link the whole `node_modules` directory. A pnpm workspace run could rewrite the real tree through the link (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each sandbox now rebuilds the directory, links package contents, copies pnpm state, and re-points links that target the repository at the sandbox copy, so workspace-package mutants are actually exercised. +- pnpm projects: a run could rewrite the real tree through the linked `node_modules` (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each pnpm sandbox now rebuilds that structure, links package contents, copies pnpm state, starts tool caches empty, turns off pnpm's install-before-run check and re-points in-repo links at the sandbox copy, so workspace-package mutants are exercised. +- Rust and Maven `target` directories are no longer linked into sandboxes. Before, binaries built from a mutant could stay in the real `target/` and be reused by the next build. A `CARGO_TARGET_DIR` set in the environment is redirected into the sandbox. First builds are slower, so large projects may need `--timeout`. +- Sandboxes are built and removed asynchronously, so one worker's setup cannot push another worker's run into a false timeout. - Sandbox cleanup unlinks every link before removing the directory. ### Changed diff --git a/README.md b/README.md index 0c0410d..f45145b 100644 --- a/README.md +++ b/README.md @@ -75,8 +75,8 @@ npx killdiff main...HEAD --sarif > killdiff.sarif # Override the test runner explicitly npx killdiff main...HEAD --cmd "pytest -q" -# Allow a slow suite (80 s baseline) up to 3 minutes per run -npx killdiff main...HEAD --cmd "go test ./..." --timeout 180000 +# Allow a slow suite (80 s baseline) up to 5 minutes per run +npx killdiff main...HEAD --cmd "go test ./..." --timeout 300000 ``` --- @@ -114,8 +114,9 @@ npx killdiff main...HEAD --cmd "go test ./..." --timeout 180000 - **Diff-only scope:** Parses `git diff --unified=0` so only executable code on changed lines is mutated (skips test files, comments, strings, imports, and type declarations). - **Polyglot on Day 1:** Mutates TypeScript/JavaScript, Python, Go, and Rust across boundary (`>=`/`>`, `<=`/`<`), equality (`===`/`!==`, `==`/`!=`), logical (`&&`/`||`, `and`/`or`), boolean (`true`/`false`, `True`/`False`), and arithmetic (`+`/`-`) operators. -- **Isolated parallel sandboxes:** Never edits your real working tree. Creates ephemeral temp workspaces and cleans up automatically. Each sandbox rebuilds `node_modules` as its own directory, linking package contents and re-pointing workspace links at the sandbox copy, so pnpm or npm workspace writes stay in the sandbox and mutants in workspace packages are tested. `.venv` and `target` are linked. Cleanup removes links without following them. -- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). The baseline limit defaults to 60 s and each mutant gets 2.5x the baseline time; `--timeout ` sets both. +- **Isolated parallel sandboxes:** Never edits your source files. Each run uses temporary workspaces and removes them afterwards, unlinking links without following them. `node_modules` and `.venv` are linked. In pnpm projects each sandbox gets its own `node_modules` structure and pnpm's install-before-run check is turned off, so state files and workspace links stay in the sandbox. Install dependencies before running killdiff. Rust and Maven `target` directories are not shared: each sandbox builds its own. +- **Shared by design:** package contents (and, outside pnpm projects, tool caches such as `node_modules/.vite`) are links to your real install, so a test that writes there writes the real files. npm and Yarn workspace packages imported through `node_modules` resolve to the unmutated originals. +- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). The baseline limit defaults to 60 s and each mutant gets 2.5x the baseline time; `--timeout ` replaces both limits, so set it comfortably above your slowest run. A first Rust or Maven build in a fresh sandbox can need it. --- diff --git a/src/runner/sandbox.ts b/src/runner/sandbox.ts index 6e081b3..7440f49 100644 --- a/src/runner/sandbox.ts +++ b/src/runner/sandbox.ts @@ -1,32 +1,22 @@ import { spawn, spawnSync } from "node:child_process"; -import { - cpSync, - existsSync, - lstatSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - realpathSync, - rmSync, - statSync, - symlinkSync, - unlinkSync, - writeFileSync, -} from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { copyFile, cp, lstat, mkdir, mkdtemp, readdir, realpath, rm, stat, symlink, unlink } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { isAbsolute, join, relative } from "node:path"; +import { dirname, isAbsolute, join, relative } from "node:path"; import { resolveContainedPath } from "../git/diff.js"; import type { Mutant, MutantRunResult, MutantStatus, MutationReport } from "../types.js"; -const HEAVY_DEPENDENCY_DIRS = new Set(["node_modules", ".venv", "venv", "target"]); +const HEAVY_DEPENDENCY_DIRS = new Set(["node_modules", ".venv", "venv"]); const DEFAULT_BASELINE_TIMEOUT_MS = 60_000; export const MIN_TIMEOUT_MS = 1_000; export const MAX_TIMEOUT_MS = 86_400_000; -// Directories inside node_modules that are rebuilt per sandbox instead of linked, so that -// package-manager writes (pnpm's pre-run install, state files, relinks) stay in the sandbox. -const MAX_MIRROR_DEPTH = 4; const SKIP_COPY_DIRS = new Set([".git", ".next", ".nuxt", "coverage", ".superpowers"]); +// A `target` directory next to one of these is build output. Sharing it would leave binaries +// built from a mutant in the real project, so each sandbox builds its own. +const BUILD_MANIFESTS = ["Cargo.toml", "pom.xml"]; +// Tool caches inside node_modules that a pnpm sandbox starts empty. +const CACHE_DIRS = new Set([".cache", ".vite", ".vite-temp", ".vitest", ".tmp"]); +const FS_BATCH = 32; export interface RunMutationSuiteOptions { repoDir: string; @@ -59,15 +49,37 @@ function killTreeSync(pid: number | undefined): void { } } +/** + * Environment for a sandbox run. pnpm would otherwise install into the sandbox before running a + * script, and a Cargo target directory set in the environment would bypass the sandbox. + */ +function sandboxEnv(sandboxDir: string, pnpm: boolean): NodeJS.ProcessEnv { + const env = { ...process.env }; + if (pnpm) { + // pnpm 10 reads the npm_config_ form, newer releases the pnpm_config_ form. + env.npm_config_verify_deps_before_run = "false"; + env.pnpm_config_verify_deps_before_run = "false"; + } + const keys = Object.keys(env).filter((k) => /^CARGO_(BUILD_)?TARGET_DIR$/i.test(k)); + if (keys.length > 0) { + for (const key of keys) delete env[key]; + env.CARGO_TARGET_DIR = join(sandboxDir, "target"); + } + return env; +} + function execShellCommand( cmd: string, cwd: string, - timeoutMs: number + timeoutMs: number, + pnpm: boolean ): Promise<{ exitCode: number; timedOut: boolean; durationMs: number }> { + const env = sandboxEnv(cwd, pnpm); const started = Date.now(); return new Promise((resolveRun) => { const child = spawn(cmd, { cwd, + env, shell: true, stdio: "ignore", windowsHide: true, @@ -102,10 +114,30 @@ function execShellCommand( interface SandboxContext { repoReal: string; sandboxDir: string; + pnpm: boolean; +} + +async function inBatches(items: T[], run: (item: T) => Promise): Promise { + for (let i = 0; i < items.length; i += FS_BATCH) { + const settled = await Promise.allSettled(items.slice(i, i + FS_BATCH).map(run)); + const failed = settled.find((r): r is PromiseRejectedResult => r.status === "rejected"); + if (failed) throw failed.reason; + } } -function linkDirectory(target: string, dst: string): void { - symlinkSync(target, dst, process.platform === "win32" ? "junction" : "dir"); +async function linkDirectory(target: string, dst: string): Promise { + await symlink(target, dst, process.platform === "win32" ? "junction" : "dir"); +} + +/** pnpm projects (including a subdirectory of a pnpm workspace) need a sandbox-owned node_modules. */ +function usesPnpm(repoReal: string): boolean { + if (existsSync(join(repoReal, "node_modules", ".pnpm")) || existsSync(join(repoReal, "node_modules", ".modules.yaml"))) { + return true; + } + for (let dir = repoReal; ; dir = dirname(dir)) { + if (existsSync(join(dir, "pnpm-lock.yaml")) || existsSync(join(dir, "pnpm-workspace.yaml"))) return true; + if (dirname(dir) === dir) return false; + } } /** A link target inside the repository is re-pointed at the same path in the sandbox. */ @@ -117,68 +149,78 @@ function sandboxTarget(target: string, ctx: SandboxContext): string { } /** - * Rebuild a node_modules directory in the sandbox. Package contents are linked, but the + * Rebuild a pnpm node_modules directory in the sandbox. Package contents are linked, but the * directory structure, links and state files are the sandbox's own. Linking the whole - * node_modules let a sandboxed pnpm install rewrite the real tree (its workspace links then - * pointed into a sandbox that was deleted), and kept workspace links aimed at the unmutated - * original packages. + * node_modules let a sandboxed pnpm install rewrite the real tree: its workspace links then + * pointed into a sandbox that was deleted. Inside the `.pnpm` store each package entry is one + * link; only the store's hoisted `node_modules` is rebuilt. */ -function mirrorNodeModules(srcDir: string, dstDir: string, ctx: SandboxContext, depth = 0): void { - mkdirSync(dstDir, { recursive: true }); - for (const entry of readdirSync(srcDir, { withFileTypes: true })) { +async function mirrorNodeModules(srcDir: string, dstDir: string, ctx: SandboxContext, inStore = false): Promise { + await mkdir(dstDir, { recursive: true }); + await inBatches(await readdir(srcDir, { withFileTypes: true }), async (entry) => { const src = join(srcDir, entry.name); const dst = join(dstDir, entry.name); if (entry.isSymbolicLink()) { let target: string; + let isDirectory: boolean; try { - target = realpathSync(src); + target = await realpath(src); + isDirectory = (await stat(target)).isDirectory(); } catch { - continue; // dangling link: nothing to expose + return; // dangling link: nothing to expose } const mapped = sandboxTarget(target, ctx); - if (statSync(target).isDirectory()) { - linkDirectory(mapped, dst); + if (isDirectory) { + await linkDirectory(mapped, dst); } else { try { - symlinkSync(mapped, dst, "file"); + await symlink(mapped, dst, "file"); } catch { - cpSync(target, dst); + await copyFile(target, dst); } } - continue; + return; } - if (entry.isDirectory()) { - const structural = entry.name === "node_modules" || entry.name === ".pnpm" || entry.name.startsWith("@"); - if (structural && depth < MAX_MIRROR_DEPTH) { - mirrorNodeModules(src, dst, ctx, depth + 1); - } else if (entry.name.startsWith(".pnpm-")) { - cpSync(src, dst, { recursive: true }); // small pnpm state directories, written during runs - } else { - linkDirectory(realpathSync(src), dst); - } - continue; + if (!entry.isDirectory()) { + await copyFile(src, dst); + } else if (entry.name === "node_modules") { + await mirrorNodeModules(src, dst, ctx); + } else if (inStore) { + await linkDirectory(await realpath(src), dst); + } else if (entry.name === ".pnpm") { + await mirrorNodeModules(src, dst, ctx, true); + } else if (entry.name.startsWith("@")) { + await mirrorNodeModules(src, dst, ctx); + } else if (CACHE_DIRS.has(entry.name)) { + await mkdir(dst, { recursive: true }); + } else if (entry.name === ".bin" || entry.name.startsWith(".")) { + // Shims and tool state: private copies. Relative links keep pointing inside the sandbox. + await cp(src, dst, { recursive: true, verbatimSymlinks: true }); + } else { + await linkDirectory(await realpath(src), dst); } - cpSync(src, dst); - } + }); } -function copyTreeLinkingDeps(srcDir: string, dstDir: string, ctx: SandboxContext, depth = 0): void { - for (const entry of readdirSync(srcDir, { withFileTypes: true })) { +async function copyTreeLinkingDeps(srcDir: string, dstDir: string, ctx: SandboxContext, depth = 0): Promise { + for (const entry of await readdir(srcDir, { withFileTypes: true })) { if (depth === 0 && SKIP_COPY_DIRS.has(entry.name)) continue; if (entry.name === ".git") continue; const src = join(srcDir, entry.name); const dst = join(dstDir, entry.name); + const dirLike = entry.isDirectory() || entry.isSymbolicLink(); - if (entry.name === "node_modules" && (entry.isDirectory() || entry.isSymbolicLink())) { - mirrorNodeModules(realpathSync(src), dst, ctx); + if (entry.name === "target" && dirLike && BUILD_MANIFESTS.some((m) => existsSync(join(srcDir, m)))) continue; + + if (ctx.pnpm && entry.name === "node_modules" && dirLike) { + await mirrorNodeModules(await realpath(src), dst, ctx); continue; } - if (HEAVY_DEPENDENCY_DIRS.has(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())) { + if (HEAVY_DEPENDENCY_DIRS.has(entry.name) && dirLike) { try { - const target = realpathSync(src); - symlinkSync(target, dst, process.platform === "win32" ? "junction" : "dir"); + await linkDirectory(await realpath(src), dst); continue; } catch { // fallback to copy if symlink/junction unavailable @@ -186,27 +228,27 @@ function copyTreeLinkingDeps(srcDir: string, dstDir: string, ctx: SandboxContext } if (entry.isDirectory() && depth < 3) { - mkdirSync(dst, { recursive: true }); - copyTreeLinkingDeps(src, dst, ctx, depth + 1); + await mkdir(dst, { recursive: true }); + await copyTreeLinkingDeps(src, dst, ctx, depth + 1); continue; } - cpSync(src, dst, { recursive: true }); + await cp(src, dst, { recursive: true }); } } -function createIsolatedWorkspace(repoDir: string): string { - const sandboxDir = mkdtempSync(join(tmpdir(), "killdiff-box-")); +/** + * Build one sandbox. All file work is asynchronous so that building one sandbox never delays + * another worker's process exit or timeout. + */ +export async function createIsolatedWorkspace(repoDir: string): Promise { + const sandboxDir = await mkdtemp(join(tmpdir(), "killdiff-box-")); try { - copyTreeLinkingDeps(repoDir, sandboxDir, { repoReal: realpathSync(repoDir), sandboxDir }, 0); + const repoReal = await realpath(repoDir); + await copyTreeLinkingDeps(repoDir, sandboxDir, { repoReal, sandboxDir, pnpm: usesPnpm(repoReal) }); return sandboxDir; } catch (err) { - try { - detachLinks(sandboxDir); - rmSync(sandboxDir, { recursive: true, force: true }); - } catch { - // best effort cleanup - } + await removeDirSafe(sandboxDir); throw err; } } @@ -232,32 +274,29 @@ export function applyMutantToWorkspace(sandboxDir: string, mutant: Mutant): void } /** Remove every link in the sandbox without following it, so cleanup never reaches link targets. */ -function detachLinks(dir: string): void { +async function detachLinks(dir: string): Promise { let entries; try { - entries = readdirSync(dir, { withFileTypes: true }); + entries = await readdir(dir, { withFileTypes: true }); } catch { return; } - for (const entry of entries) { + await inBatches(entries, async (entry) => { const path = join(dir, entry.name); - if (entry.isSymbolicLink() || lstatSync(path).isSymbolicLink()) { - try { - unlinkSync(path); - } catch { - // retried by removeDirSafe - } - } else if (entry.isDirectory()) { - detachLinks(path); + try { + if (entry.isSymbolicLink() || (await lstat(path)).isSymbolicLink()) await unlink(path); + else if (entry.isDirectory()) await detachLinks(path); + } catch { + // retried by removeDirSafe } - } + }); } -async function removeDirSafe(dir: string): Promise { +export async function removeDirSafe(dir: string): Promise { for (let i = 0; i < 10; i++) { try { - detachLinks(dir); - rmSync(dir, { recursive: true, force: true }); + await detachLinks(dir); + await rm(dir, { recursive: true, force: true }); if (!existsSync(dir)) return; } catch { // brief retry on Windows lock release @@ -287,13 +326,15 @@ export async function runMutationSuite(opts: RunMutationSuiteOptions): Promise { + for (const name of readdirSync(d)) { + const p = join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) rmSync(p, { force: true }); + else if (st.isDirectory()) walk(p); + } + }; + if (existsSync(dir)) walk(dir); + rmSync(dir, { recursive: true, force: true }); +} + +afterEach(() => { + while (tempDirs.length > 0) removeTemp(tempDirs.pop()!); +}); + +const isLink = (p: string) => lstatSync(p).isSymbolicLink(); + +describe("sandbox dependency layouts", () => { + it("links node_modules as one directory outside pnpm projects", async () => { + const repo = temp("kd-npm-"); + put(join(repo, "package-lock.json"), "{}\n"); + put(join(repo, "node_modules", "left", "index.js"), "module.exports = 1;\n"); + const box = await createIsolatedWorkspace(repo); + try { + expect(isLink(join(box, "node_modules"))).toBe(true); + expect(realpathSync(join(box, "node_modules"))).toBe(join(repo, "node_modules")); + } finally { + await removeDirSafe(box); + } + expect(readFileSync(join(repo, "node_modules", "left", "index.js"), "utf8")).toBe("module.exports = 1;\n"); + }); + + it("gives a pnpm sandbox its own tree with one link per store entry and empty caches", async () => { + const repo = temp("kd-pnpm-"); + const nm = join(repo, "node_modules"); + const entry = join(nm, ".pnpm", "@scope+dep@1.0.0"); + put(join(entry, "node_modules", "@scope", "dep", "index.js"), "module.exports = 2;\n"); + put(join(nm, ".pnpm", "lock.yaml"), "lock\n"); + put(join(nm, ".vite", "results.json"), "real\n"); + put(join(nm, ".bin", "tool.cmd"), "@echo off\n"); + put(join(nm, ".modules.yaml"), "state\n"); + mkdirSync(join(nm, "@scope"), { recursive: true }); + symlinkSync(join(entry, "node_modules", "@scope", "dep"), join(nm, "@scope", "dep"), linkType); + + const box = await createIsolatedWorkspace(repo); + try { + const boxNm = join(box, "node_modules"); + for (const real of [boxNm, join(boxNm, ".pnpm"), join(boxNm, "@scope"), join(boxNm, ".vite"), join(boxNm, ".bin")]) { + expect(isLink(real)).toBe(false); + } + expect(isLink(join(boxNm, ".pnpm", "@scope+dep@1.0.0"))).toBe(true); + expect(readdirSync(join(boxNm, ".vite"))).toEqual([]); + expect(readFileSync(join(boxNm, "@scope", "dep", "index.js"), "utf8")).toBe("module.exports = 2;\n"); + writeFileSync(join(boxNm, ".vite", "results.json"), "sandbox\n"); + writeFileSync(join(boxNm, ".bin", "tool.cmd"), "sandbox\n"); + writeFileSync(join(boxNm, ".modules.yaml"), "sandbox\n"); + writeFileSync(join(boxNm, ".pnpm", "lock.yaml"), "sandbox\n"); + } finally { + await removeDirSafe(box); + } + expect(readFileSync(join(nm, ".vite", "results.json"), "utf8")).toBe("real\n"); + expect(readFileSync(join(nm, ".bin", "tool.cmd"), "utf8")).toBe("@echo off\n"); + expect(readFileSync(join(nm, ".modules.yaml"), "utf8")).toBe("state\n"); + expect(readFileSync(join(nm, ".pnpm", "lock.yaml"), "utf8")).toBe("lock\n"); + expect(readFileSync(join(entry, "node_modules", "@scope", "dep", "index.js"), "utf8")).toBe("module.exports = 2;\n"); + }); + + it("treats a package inside a pnpm workspace as pnpm", async () => { + const root = temp("kd-sub-"); + put(join(root, "pnpm-workspace.yaml"), "packages:\n - 'packages/*'\n"); + const pkg = join(root, "packages", "app"); + put(join(pkg, "node_modules", "left", "index.js"), "module.exports = 1;\n"); + const box = await createIsolatedWorkspace(pkg); + try { + expect(isLink(join(box, "node_modules"))).toBe(false); + expect(isLink(join(box, "node_modules", "left"))).toBe(true); + } finally { + await removeDirSafe(box); + } + expect(existsSync(join(pkg, "node_modules", "left", "index.js"))).toBe(true); + }); + + it("builds sandboxes without blocking the event loop", async () => { + const repo = temp("kd-async-"); + put(join(repo, "node_modules", ".modules.yaml"), "x\n"); + for (let i = 0; i < 80; i++) put(join(repo, "node_modules", `p${i}`, "index.js"), "x\n"); + let ticked = false; + setImmediate(() => { + ticked = true; + }); + const pending = createIsolatedWorkspace(repo); + const box = await pending; + try { + expect(ticked).toBe(true); + expect(readdirSync(join(box, "node_modules"))).toHaveLength(81); + } finally { + await removeDirSafe(box); + } + }); +}); + +describe("pnpm sandbox environment", () => { + const check = (expected: string) => + [ + "const a = process.env.npm_config_verify_deps_before_run ?? 'unset';", + "const b = process.env.pnpm_config_verify_deps_before_run ?? 'unset';", + `if (a !== '${expected}' || b !== '${expected}') process.exit(3);`, + ].join("\n"); + + for (const [label, marker, expected] of [ + ["turns off pnpm's install-before-run check in pnpm projects", "pnpm-lock.yaml", "false"], + ["leaves package-manager settings alone elsewhere", "package-lock.json", "unset"], + ]) { + it(label, async () => { + const repo = temp("kd-env-"); + const src = "export const n = 1 + 1;\n"; + put(join(repo, "lib.mjs"), src); + put(join(repo, marker), "{}\n"); + put(join(repo, "t.mjs"), check(expected)); + const saved = { ...process.env }; + delete process.env.npm_config_verify_deps_before_run; + delete process.env.pnpm_config_verify_deps_before_run; + try { + const report = await runMutationSuite({ + repoDir: repo, + mutants: generateMutantsForFile("lib.mjs", src, new Set([1])), + testCmd: `"${process.execPath}" t.mjs`, + maxMutants: 1, + concurrency: 1, + }); + expect(report.totalMutants).toBe(1); + expect(report.survived).toBe(1); + } finally { + for (const key of ["npm_config_verify_deps_before_run", "pnpm_config_verify_deps_before_run"]) { + if (saved[key] !== undefined) process.env[key] = saved[key]; + } + } + }); + } +}); + +describe("build output isolation", () => { + it("never shares Cargo or Maven target directories, and keeps an ordinary target folder", async () => { + const repo = temp("kd-target-"); + put(join(repo, "Cargo.toml"), "[workspace]\n"); + put(join(repo, "target", "debug", "app"), "real build\n"); + put(join(repo, "java", "pom.xml"), "\n"); + put(join(repo, "java", "target", "app.jar"), "real jar\n"); + put(join(repo, "src", "target", "keep.txt"), "source folder\n"); + + const box = await createIsolatedWorkspace(repo); + try { + expect(existsSync(join(box, "target"))).toBe(false); + expect(existsSync(join(box, "java", "target"))).toBe(false); + expect(isLink(join(box, "src", "target"))).toBe(false); + expect(readFileSync(join(box, "src", "target", "keep.txt"), "utf8")).toBe("source folder\n"); + put(join(box, "target", "debug", "app"), "mutant build\n"); + } finally { + await removeDirSafe(box); + } + expect(readFileSync(join(repo, "target", "debug", "app"), "utf8")).toBe("real build\n"); + }); + + it("redirects an environment CARGO_TARGET_DIR into the sandbox", async () => { + const repo = temp("kd-cargo-env-"); + const shared = temp("kd-shared-target-"); + const src = "export const n = 1 + 1;\n"; + put(join(repo, "lib.mjs"), src); + put( + join(repo, "t.mjs"), + [ + 'import { mkdirSync, writeFileSync } from "node:fs";', + 'import { join, resolve } from "node:path";', + "const dir = process.env.CARGO_TARGET_DIR;", + 'if (resolve(dir) !== resolve("target")) process.exit(3);', + "mkdirSync(dir, { recursive: true });", + 'writeFileSync(join(dir, "marker"), "x");', + ].join("\n") + ); + const previous = process.env.CARGO_TARGET_DIR; + process.env.CARGO_TARGET_DIR = shared; + try { + const report = await runMutationSuite({ + repoDir: repo, + mutants: generateMutantsForFile("lib.mjs", src, new Set([1])), + testCmd: `"${process.execPath}" t.mjs`, + maxMutants: 1, + concurrency: 1, + }); + expect(report.totalMutants).toBe(1); + } finally { + if (previous === undefined) delete process.env.CARGO_TARGET_DIR; + else process.env.CARGO_TARGET_DIR = previous; + } + expect(readdirSync(shared)).toEqual([]); + }); +}); From 29f494a39b7ac08f9462d562bbf2c351ee6a6a30 Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:54:34 -0700 Subject: [PATCH 4/6] test: compare real paths on Windows and macOS, share the cleanup helper Co-Authored-By: Claude Sonnet 5.5 --- tests/helpers/remove-temp.ts | 16 ++++++++++++++++ tests/sandbox-isolation.test.ts | 24 ++++++------------------ tests/timeout-and-deps.test.ts | 18 +----------------- 3 files changed, 23 insertions(+), 35 deletions(-) create mode 100644 tests/helpers/remove-temp.ts diff --git a/tests/helpers/remove-temp.ts b/tests/helpers/remove-temp.ts new file mode 100644 index 0000000..20e7bfe --- /dev/null +++ b/tests/helpers/remove-temp.ts @@ -0,0 +1,16 @@ +import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; + +/** Delete a test folder, unlinking links first so cleanup never walks through them. */ +export function removeTemp(dir: string): void { + const walk = (d: string) => { + for (const name of readdirSync(d)) { + const p = join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) rmSync(p, { force: true }); + else if (st.isDirectory()) walk(p); + } + }; + if (existsSync(dir)) walk(dir); + rmSync(dir, { recursive: true, force: true }); +} diff --git a/tests/sandbox-isolation.test.ts b/tests/sandbox-isolation.test.ts index 783cc67..b127ef0 100644 --- a/tests/sandbox-isolation.test.ts +++ b/tests/sandbox-isolation.test.ts @@ -7,7 +7,6 @@ import { readFileSync, readdirSync, realpathSync, - rmSync, symlinkSync, writeFileSync, } from "node:fs"; @@ -15,6 +14,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { createIsolatedWorkspace, removeDirSafe, runMutationSuite } from "../src/runner/sandbox.js"; import { generateMutantsForFile } from "../src/mutate/operators.js"; +import { removeTemp } from "./helpers/remove-temp.js"; const linkType = process.platform === "win32" ? "junction" : "dir"; const tempDirs: string[] = []; @@ -30,19 +30,6 @@ function put(file: string, text: string): void { writeFileSync(file, text); } -function removeTemp(dir: string): void { - const walk = (d: string) => { - for (const name of readdirSync(d)) { - const p = join(d, name); - const st = lstatSync(p); - if (st.isSymbolicLink()) rmSync(p, { force: true }); - else if (st.isDirectory()) walk(p); - } - }; - if (existsSync(dir)) walk(dir); - rmSync(dir, { recursive: true, force: true }); -} - afterEach(() => { while (tempDirs.length > 0) removeTemp(tempDirs.pop()!); }); @@ -57,7 +44,7 @@ describe("sandbox dependency layouts", () => { const box = await createIsolatedWorkspace(repo); try { expect(isLink(join(box, "node_modules"))).toBe(true); - expect(realpathSync(join(box, "node_modules"))).toBe(join(repo, "node_modules")); + expect(realpathSync.native(join(box, "node_modules"))).toBe(realpathSync.native(join(repo, "node_modules"))); } finally { await removeDirSafe(box); } @@ -203,10 +190,11 @@ describe("build output isolation", () => { put( join(repo, "t.mjs"), [ - 'import { mkdirSync, writeFileSync } from "node:fs";', - 'import { join, resolve } from "node:path";', + 'import { mkdirSync, realpathSync, writeFileSync } from "node:fs";', + 'import { basename, dirname, join, resolve } from "node:path";', "const dir = process.env.CARGO_TARGET_DIR;", - 'if (resolve(dir) !== resolve("target")) process.exit(3);', + 'const inside = realpathSync(dirname(resolve(dir))) === realpathSync(process.cwd());', + 'if (!inside || basename(dir) !== "target") process.exit(3);', "mkdirSync(dir, { recursive: true });", 'writeFileSync(join(dir, "marker"), "x");', ].join("\n") diff --git a/tests/timeout-and-deps.test.ts b/tests/timeout-and-deps.test.ts index c9fa328..9962d33 100644 --- a/tests/timeout-and-deps.test.ts +++ b/tests/timeout-and-deps.test.ts @@ -2,14 +2,11 @@ import { describe, it, expect, afterEach } from "vitest"; import { execFileSync } from "node:child_process"; import { existsSync, - lstatSync, mkdirSync, mkdtempSync, readFileSync, - readdirSync, readlinkSync, realpathSync, - rmSync, symlinkSync, writeFileSync, } from "node:fs"; @@ -20,23 +17,10 @@ import { parseCliArgs } from "../src/cli.js"; import { startMcpStdioServer } from "../src/mcp/server.js"; import { runMutationSuite } from "../src/runner/sandbox.js"; import { generateMutantsForFile } from "../src/mutate/operators.js"; +import { removeTemp } from "./helpers/remove-temp.js"; const linkType = process.platform === "win32" ? "junction" : "dir"; -function removeTemp(dir: string): void { - // Unlink links first so test cleanup never walks through them. - const walk = (d: string) => { - for (const name of readdirSync(d)) { - const p = join(d, name); - const st = lstatSync(p); - if (st.isSymbolicLink()) rmSync(p, { force: true }); - else if (st.isDirectory()) walk(p); - } - }; - if (existsSync(dir)) walk(dir); - rmSync(dir, { recursive: true, force: true }); -} - describe("--timeout option", () => { it("parses a millisecond timeout and rejects invalid values", () => { expect(parseCliArgs(["--timeout", "90000"]).timeoutMs).toBe(90_000); From 1b899bf5a73f7d043e0ed434683a0253e64a513f Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:56:27 -0700 Subject: [PATCH 5/6] Always set the Cargo target directory; run Cargo and Maven mutants serially From the re-review: - A target-dir in a Cargo config file still pointed sandboxes at a shared directory. CARGO_TARGET_DIR is now always set inside the sandbox. - Parallel from-scratch builds could exceed 2.5x the solo baseline and report TIMEOUT as a kill. Rust and Maven projects run one mutant at a time. - README and CHANGELOG state what is still shared, including the pnpm case where a stored dependency loads the original workspace package. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 ++-- README.md | 7 ++++--- src/runner/sandbox.ts | 24 ++++++++++++++------- tests/sandbox-isolation.test.ts | 37 +++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 765804c..9f7d7c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,8 @@ All notable changes to killdiff are recorded here. The format follows [Keep a Ch - `killdiff --version` and `-v` print the package version. Help and the MCP server read the same constant, and a test keeps it equal to `package.json`. ### Fixed -- pnpm projects: a run could rewrite the real tree through the linked `node_modules` (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each pnpm sandbox now rebuilds that structure, links package contents, copies pnpm state, starts tool caches empty, turns off pnpm's install-before-run check and re-points in-repo links at the sandbox copy, so workspace-package mutants are exercised. -- Rust and Maven `target` directories are no longer linked into sandboxes. Before, binaries built from a mutant could stay in the real `target/` and be reused by the next build. A `CARGO_TARGET_DIR` set in the environment is redirected into the sandbox. First builds are slower, so large projects may need `--timeout`. +- pnpm projects: a run could rewrite the real tree through the linked `node_modules` (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each pnpm sandbox now rebuilds that structure, links package contents, copies pnpm state, starts tool caches empty, turns off pnpm's install-before-run check and re-points in-repo links at the sandbox copy, so mutants in directly imported workspace packages are exercised. A `.pnpm` dependency that loads a workspace package still gets the original. +- Rust and Maven: `target` folders are no longer linked into sandboxes, and `CARGO_TARGET_DIR` is always set inside the sandbox, overriding the environment and Cargo config files. Before, binaries built from a mutant could stay in a real target directory and be reused by the next build. Because every sandbox now builds from scratch, these projects run one mutant at a time and large ones may need `--timeout`. - Sandboxes are built and removed asynchronously, so one worker's setup cannot push another worker's run into a false timeout. - Sandbox cleanup unlinks every link before removing the directory. diff --git a/README.md b/README.md index f45145b..1174197 100644 --- a/README.md +++ b/README.md @@ -114,9 +114,10 @@ npx killdiff main...HEAD --cmd "go test ./..." --timeout 300000 - **Diff-only scope:** Parses `git diff --unified=0` so only executable code on changed lines is mutated (skips test files, comments, strings, imports, and type declarations). - **Polyglot on Day 1:** Mutates TypeScript/JavaScript, Python, Go, and Rust across boundary (`>=`/`>`, `<=`/`<`), equality (`===`/`!==`, `==`/`!=`), logical (`&&`/`||`, `and`/`or`), boolean (`true`/`false`, `True`/`False`), and arithmetic (`+`/`-`) operators. -- **Isolated parallel sandboxes:** Never edits your source files. Each run uses temporary workspaces and removes them afterwards, unlinking links without following them. `node_modules` and `.venv` are linked. In pnpm projects each sandbox gets its own `node_modules` structure and pnpm's install-before-run check is turned off, so state files and workspace links stay in the sandbox. Install dependencies before running killdiff. Rust and Maven `target` directories are not shared: each sandbox builds its own. -- **Shared by design:** package contents (and, outside pnpm projects, tool caches such as `node_modules/.vite`) are links to your real install, so a test that writes there writes the real files. npm and Yarn workspace packages imported through `node_modules` resolve to the unmutated originals. -- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). The baseline limit defaults to 60 s and each mutant gets 2.5x the baseline time; `--timeout ` replaces both limits, so set it comfortably above your slowest run. A first Rust or Maven build in a fresh sandbox can need it. +- **Isolated parallel sandboxes:** killdiff applies mutants only to temporary copies and removes them afterwards, unlinking links without following them. `node_modules` and `.venv` are linked. In pnpm projects each sandbox gets its own `node_modules` structure and pnpm's install-before-run check is turned off, so state files and workspace links stay in the sandbox. Install dependencies before running killdiff. +- **Rust and Maven:** `target` folders next to `Cargo.toml` or `pom.xml` are not shared and `CARGO_TARGET_DIR` always points inside the sandbox. Every sandbox therefore builds from scratch, mutants run one at a time, and large projects may need `--timeout`. +- **Shared by design:** package contents (and, outside pnpm projects, tool caches such as `node_modules/.vite`) are links to your real install, so a test that writes there, including through a linked workspace package, writes the real files. npm and Yarn workspace packages imported through `node_modules` resolve to the unmutated originals. In pnpm projects the same applies when a dependency stored in `.pnpm` (for example a `file:` plugin with a peer dependency) loads a workspace package: it gets the original, a second copy beside the sandbox one. +- **Baseline & timeout guards:** Verifies baseline tests pass before mutating, caps runs with `--max 25`, and terminates infinite-loop mutants cleanly as `TIMEOUT` (counted as killed). The baseline limit defaults to 60 s and each mutant gets 2.5x the baseline time; `--timeout ` replaces both limits, so set it comfortably above your slowest run. --- diff --git a/src/runner/sandbox.ts b/src/runner/sandbox.ts index 7440f49..de078cb 100644 --- a/src/runner/sandbox.ts +++ b/src/runner/sandbox.ts @@ -51,7 +51,8 @@ function killTreeSync(pid: number | undefined): void { /** * Environment for a sandbox run. pnpm would otherwise install into the sandbox before running a - * script, and a Cargo target directory set in the environment would bypass the sandbox. + * script. Cargo can be pointed at a shared target directory by the environment or by a config + * file, so its target directory is always set inside the sandbox. */ function sandboxEnv(sandboxDir: string, pnpm: boolean): NodeJS.ProcessEnv { const env = { ...process.env }; @@ -60,11 +61,10 @@ function sandboxEnv(sandboxDir: string, pnpm: boolean): NodeJS.ProcessEnv { env.npm_config_verify_deps_before_run = "false"; env.pnpm_config_verify_deps_before_run = "false"; } - const keys = Object.keys(env).filter((k) => /^CARGO_(BUILD_)?TARGET_DIR$/i.test(k)); - if (keys.length > 0) { - for (const key of keys) delete env[key]; - env.CARGO_TARGET_DIR = join(sandboxDir, "target"); + for (const key of Object.keys(env)) { + if (/^CARGO_(BUILD_)?TARGET_DIR$/i.test(key)) delete env[key]; } + env.CARGO_TARGET_DIR = join(sandboxDir, "target"); return env; } @@ -140,6 +140,14 @@ function usesPnpm(repoReal: string): boolean { } } +/** + * Rust and Maven sandboxes build from scratch. Running several at once slows each build far past + * the solo baseline, which would report false timeouts, so their mutants run one at a time. + */ +function buildsFromScratch(repoReal: string, testCmd: string): boolean { + return BUILD_MANIFESTS.some((m) => existsSync(join(repoReal, m))) || /\b(cargo|mvnw?)\b/.test(testCmd); +} + /** A link target inside the repository is re-pointed at the same path in the sandbox. */ function sandboxTarget(target: string, ctx: SandboxContext): string { const rel = relative(ctx.repoReal, target); @@ -326,7 +334,9 @@ export async function runMutationSuite(opts: RunMutationSuiteOptions): Promise worker()) + Array.from({ length: Math.min(workers, selected.length) }, () => worker()) ); const firstRejection = settled.find((s): s is PromiseRejectedResult => s.status === "rejected"); if (firstRejection) { diff --git a/tests/sandbox-isolation.test.ts b/tests/sandbox-isolation.test.ts index b127ef0..b60ee9c 100644 --- a/tests/sandbox-isolation.test.ts +++ b/tests/sandbox-isolation.test.ts @@ -182,6 +182,43 @@ describe("build output isolation", () => { expect(readFileSync(join(repo, "target", "debug", "app"), "utf8")).toBe("real build\n"); }); + it("runs Cargo projects one mutant at a time with a sandbox target directory", async () => { + const repo = temp("kd-serial-"); + const log = join(temp("kd-serial-log-"), "runs.txt"); + const src = "export const f = (a, b) => a + b - a + b - a;\n"; + put(join(repo, "lib.mjs"), src); + put(join(repo, "Cargo.toml"), "[workspace]\n"); + put( + join(repo, "t.mjs"), + [ + 'import { appendFileSync } from "node:fs";', + 'import { basename } from "node:path";', + 'if (basename(process.env.CARGO_TARGET_DIR ?? "") !== "target") process.exit(3);', + `appendFileSync(${JSON.stringify(log)}, "start\\n");`, + "await new Promise((r) => setTimeout(r, 250));", + `appendFileSync(${JSON.stringify(log)}, "end\\n");`, + ].join("\n") + ); + const saved = { a: process.env.CARGO_TARGET_DIR, b: process.env.CARGO_BUILD_TARGET_DIR }; + delete process.env.CARGO_TARGET_DIR; + delete process.env.CARGO_BUILD_TARGET_DIR; + try { + const report = await runMutationSuite({ + repoDir: repo, + mutants: generateMutantsForFile("lib.mjs", src, new Set([1])), + testCmd: `"${process.execPath}" t.mjs`, + maxMutants: 3, + concurrency: 4, + }); + expect(report.totalMutants).toBe(3); + expect(report.survived).toBe(3); + } finally { + if (saved.a !== undefined) process.env.CARGO_TARGET_DIR = saved.a; + if (saved.b !== undefined) process.env.CARGO_BUILD_TARGET_DIR = saved.b; + } + expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(Array(4).fill(["start", "end"]).flat()); + }, 60_000); + it("redirects an environment CARGO_TARGET_DIR into the sandbox", async () => { const repo = temp("kd-cargo-env-"); const shared = temp("kd-shared-target-"); From ba76e2ea671f90ea833a4c292a6dfeba267cb608 Mon Sep 17 00:00:00 2001 From: Dillon Rodriguez <169501444+flipcyde101@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:59:52 -0700 Subject: [PATCH 6/6] Report the released version in SARIF output and the action example Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + README.md | 2 +- src/report/format.ts | 3 ++- tests/version.test.ts | 7 +++++++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f7d7c1..8386062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to killdiff are recorded here. The format follows [Keep a Ch ### Fixed - pnpm projects: a run could rewrite the real tree through the linked `node_modules` (pnpm's pre-run install re-pointed workspace links into the sandbox, which was then deleted), and pnpm 12 refused to run tests under a linked `node_modules`. Each pnpm sandbox now rebuilds that structure, links package contents, copies pnpm state, starts tool caches empty, turns off pnpm's install-before-run check and re-points in-repo links at the sandbox copy, so mutants in directly imported workspace packages are exercised. A `.pnpm` dependency that loads a workspace package still gets the original. - Rust and Maven: `target` folders are no longer linked into sandboxes, and `CARGO_TARGET_DIR` is always set inside the sandbox, overriding the environment and Cargo config files. Before, binaries built from a mutant could stay in a real target directory and be reused by the next build. Because every sandbox now builds from scratch, these projects run one mutant at a time and large ones may need `--timeout`. +- SARIF output and the README action example report the released version. - Sandboxes are built and removed asynchronously, so one worker's setup cannot push another worker's run into a false timeout. - Sandbox cleanup unlinks every link before removing the directory. diff --git a/README.md b/README.md index 1174197..8435014 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ npx killdiff main...HEAD --cmd "go test ./..." --timeout 300000 ## Reusable GitHub Action ```yaml -- uses: flipcyde101/killdiff@v0.1.0 +- uses: flipcyde101/killdiff@v0.1.1 with: range: origin/main...HEAD max-mutants: 25 diff --git a/src/report/format.ts b/src/report/format.ts index 6cca71c..728733a 100644 --- a/src/report/format.ts +++ b/src/report/format.ts @@ -1,4 +1,5 @@ import type { MutationReport } from "../types.js"; +import { KILLDIFF_VERSION } from "../version.js"; function mdCodeSpan(text: string, escapeTablePipe = false): string { const safe = escapeTablePipe ? text.replace(/\|/g, "\\|") : text; @@ -67,7 +68,7 @@ export function formatSarifReport(report: MutationReport): string { tool: { driver: { name: "killdiff", - version: "0.1.0", + version: KILLDIFF_VERSION, informationUri: "https://github.com/flipcyde101/killdiff", rules: [ { diff --git a/tests/version.test.ts b/tests/version.test.ts index df361b6..0544fd1 100644 --- a/tests/version.test.ts +++ b/tests/version.test.ts @@ -4,6 +4,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { KILLDIFF_VERSION } from "../src/version.js"; import { parseCliArgs } from "../src/cli.js"; +import { formatSarifReport } from "../src/report/format.js"; const pkg = JSON.parse(readFileSync(resolve(process.cwd(), "package.json"), "utf8")); @@ -12,6 +13,12 @@ describe("version reporting", () => { expect(KILLDIFF_VERSION).toBe(pkg.version); }); + it("reports the same version in SARIF output and the README action example", () => { + const report = { range: "x", testCmd: "x", baselineMs: 0, durationMs: 0, totalMutants: 0, killed: 0, survived: 0, timedOut: 0, mutationScore: 100, results: [] }; + expect(JSON.parse(formatSarifReport(report)).runs[0].tool.driver.version).toBe(pkg.version); + expect(readFileSync(resolve(process.cwd(), "README.md"), "utf8")).toContain(`flipcyde101/killdiff@v${pkg.version}`); + }); + it("parses --version and -v as version mode", () => { expect(parseCliArgs(["--version"]).mode).toBe("version"); expect(parseCliArgs(["-v"]).mode).toBe("version");