diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f17524..8386062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,20 @@ 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 +- 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. + ### Changed - README now leads with the problem, a 30-second quick start with recorded output, and install options. @@ -27,5 +38,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 3c8c272..8435014 100644 --- a/README.md +++ b/README.md @@ -74,13 +74,16 @@ 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 5 minutes per run +npx killdiff main...HEAD --cmd "go test ./..." --timeout 300000 ``` --- ## 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 { @@ -98,7 +101,7 @@ npx killdiff main...HEAD --cmd "pytest -q" ## Reusable GitHub Action ```yaml -- uses: flipcyde101/killdiff@v0.1.0 +- uses: flipcyde101/killdiff@v0.1.1 with: range: origin/main...HEAD max-mutants: 25 @@ -111,8 +114,10 @@ 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:** 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/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 43c1583..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"; @@ -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 @@ -101,6 +104,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 +173,7 @@ async function main(): Promise { range: args.range ?? "working-tree", concurrency: args.concurrency, maxMutants: args.maxMutants, + timeoutMs: args.timeoutMs, }); })(); 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/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/src/runner/sandbox.ts b/src/runner/sandbox.ts index 4ba99f8..de078cb 100644 --- a/src/runner/sandbox.ts +++ b/src/runner/sandbox.ts @@ -1,23 +1,22 @@ import { spawn, spawnSync } from "node:child_process"; -import { - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - realpathSync, - rmSync, - symlinkSync, - 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 { join } 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; 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; @@ -50,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. 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 }; + 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"; + } + 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; +} + 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, @@ -90,18 +111,124 @@ function execShellCommand( }); } -function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { - for (const entry of readdirSync(srcDir, { withFileTypes: true })) { +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; + } +} + +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; + } +} + +/** + * 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); + if (rel === "") return ctx.sandboxDir; + if (!rel.startsWith("..") && !isAbsolute(rel)) return join(ctx.sandboxDir, rel); + return target; +} + +/** + * 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. Inside the `.pnpm` store each package entry is one + * link; only the store's hoisted `node_modules` is rebuilt. + */ +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 = await realpath(src); + isDirectory = (await stat(target)).isDirectory(); + } catch { + return; // dangling link: nothing to expose + } + const mapped = sandboxTarget(target, ctx); + if (isDirectory) { + await linkDirectory(mapped, dst); + } else { + try { + await symlink(mapped, dst, "file"); + } catch { + await copyFile(target, dst); + } + } + return; + } + 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); + } + }); +} + +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 === "target" && dirLike && BUILD_MANIFESTS.some((m) => existsSync(join(srcDir, m)))) continue; - if (HEAVY_DEPENDENCY_DIRS.has(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())) { + if (ctx.pnpm && entry.name === "node_modules" && dirLike) { + await mirrorNodeModules(await realpath(src), dst, ctx); + continue; + } + + 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 @@ -109,26 +236,27 @@ function copyTreeLinkingDeps(srcDir: string, dstDir: string, depth = 0): void { } if (entry.isDirectory() && depth < 3) { - mkdirSync(dst, { recursive: true }); - copyTreeLinkingDeps(src, dst, 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, 0); + const repoReal = await realpath(repoDir); + await copyTreeLinkingDeps(repoDir, sandboxDir, { repoReal, sandboxDir, pnpm: usesPnpm(repoReal) }); return sandboxDir; } catch (err) { - try { - rmSync(sandboxDir, { recursive: true, force: true }); - } catch { - // best effort cleanup - } + await removeDirSafe(sandboxDir); throw err; } } @@ -153,10 +281,30 @@ export function applyMutantToWorkspace(sandboxDir: string, mutant: Mutant): void writeFileSync(target, lines.join(eol), "utf8"); } -async function removeDirSafe(dir: string): Promise { +/** Remove every link in the sandbox without following it, so cleanup never reaches link targets. */ +async function detachLinks(dir: string): Promise { + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return; + } + await inBatches(entries, async (entry) => { + const path = join(dir, entry.name); + try { + if (entry.isSymbolicLink() || (await lstat(path)).isSymbolicLink()) await unlink(path); + else if (entry.isDirectory()) await detachLinks(path); + } catch { + // retried by removeDirSafe + } + }); +} + +export async function removeDirSafe(dir: string): Promise { for (let i = 0; i < 10; i++) { try { - 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 @@ -186,16 +334,26 @@ 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 { @@ -216,9 +374,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/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/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 new file mode 100644 index 0000000..b60ee9c --- /dev/null +++ b/tests/sandbox-isolation.test.ts @@ -0,0 +1,256 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +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[] = []; + +function temp(prefix: string): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); + tempDirs.push(dir); + return dir; +} + +function put(file: string, text: string): void { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} + +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.native(join(box, "node_modules"))).toBe(realpathSync.native(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("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-"); + const src = "export const n = 1 + 1;\n"; + put(join(repo, "lib.mjs"), src); + put( + join(repo, "t.mjs"), + [ + 'import { mkdirSync, realpathSync, writeFileSync } from "node:fs";', + 'import { basename, dirname, join, resolve } from "node:path";', + "const dir = process.env.CARGO_TARGET_DIR;", + '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") + ); + 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([]); + }); +}); diff --git a/tests/timeout-and-deps.test.ts b/tests/timeout-and-deps.test.ts new file mode 100644 index 0000000..9962d33 --- /dev/null +++ b/tests/timeout-and-deps.test.ts @@ -0,0 +1,203 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { execFileSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readlinkSync, + realpathSync, + symlinkSync, + writeFileSync, +} 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"; +import { removeTemp } from "./helpers/remove-temp.js"; + +const linkType = process.platform === "win32" ? "junction" : "dir"; + +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("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(() => { + 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); +}); 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");