traceyard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,457 @@
1
+ import { spawn, execFile } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import {
4
+ copyFile,
5
+ lstat,
6
+ mkdir,
7
+ readFile,
8
+ readdir,
9
+ rm,
10
+ stat,
11
+ symlink,
12
+ utimes,
13
+ writeFile,
14
+ } from "node:fs/promises";
15
+ import { homedir } from "node:os";
16
+ import { dirname, join, relative, resolve } from "node:path";
17
+ import { promisify } from "node:util";
18
+ import { runLocalTest } from "../../core/src/index.mjs";
19
+ import { detectPackageManager, installCommand } from "../../core/src/package-manager.mjs";
20
+ import { isPytestFile } from "../../core/src/pytest.mjs";
21
+ import { summarizeCommandFailure } from "../../core/src/failure-summary.mjs";
22
+ import { ensureCommit } from "../../core/src/worktree.mjs";
23
+ import { BlockedError } from "./errors.mjs";
24
+ import { cleanOutput } from "./compact.mjs";
25
+ import { VERSION } from "./version.mjs";
26
+
27
+ const execFileAsync = promisify(execFile);
28
+ const exists = (path) =>
29
+ lstat(path).then(
30
+ () => true,
31
+ () => false,
32
+ );
33
+ const lockfileNames = [
34
+ "package-lock.json",
35
+ "npm-shrinkwrap.json",
36
+ "pnpm-lock.yaml",
37
+ "yarn.lock",
38
+ "bun.lock",
39
+ "bun.lockb",
40
+ ];
41
+
42
+ async function readJson(path) {
43
+ try {
44
+ return JSON.parse(await readFile(path, "utf8"));
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /** Nearest directory at or above the test file that has a package.json, inside `root`. */
51
+ async function packageDirectory(root, testPath) {
52
+ for (let directory = dirname(resolve(root, testPath)); ; directory = dirname(directory)) {
53
+ if (relative(root, directory).startsWith("..")) return null;
54
+ if (await exists(join(directory, "package.json"))) return directory;
55
+ if (directory === root || dirname(directory) === directory) return null;
56
+ }
57
+ }
58
+
59
+ const declaresDependencies = (pkg) =>
60
+ ["dependencies", "devDependencies", "optionalDependencies"].some(
61
+ (field) => pkg?.[field] && Object.keys(pkg[field]).length > 0,
62
+ );
63
+
64
+ /** Same lockfiles and root package.json in both trees, so node_modules can be shared. */
65
+ async function sameDependencies(a, b) {
66
+ for (const name of [...lockfileNames, "package.json"]) {
67
+ const [left, right] = await Promise.all([
68
+ readFile(join(a, name)).catch(() => null),
69
+ readFile(join(b, name)).catch(() => null),
70
+ ]);
71
+ if ((left === null) !== (right === null)) return false;
72
+ if (left && right && !left.equals(right)) return false;
73
+ }
74
+ return true;
75
+ }
76
+
77
+ function runInstall(command, cwd, timeoutMs) {
78
+ return new Promise((done, fail) => {
79
+ const child = spawn(command.program, command.args, {
80
+ cwd,
81
+ env: { ...process.env, CI: "true" },
82
+ shell: process.platform === "win32",
83
+ stdio: ["ignore", "pipe", "pipe"],
84
+ });
85
+ let tail = "";
86
+ const capture = (chunk) => (tail = (tail + chunk.toString()).slice(-16000));
87
+ child.stdout.on("data", capture);
88
+ child.stderr.on("data", capture);
89
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
90
+ child.on("error", (error) => {
91
+ clearTimeout(timer);
92
+ fail(new BlockedError(`Could not start ${command.program}: ${error.message}`));
93
+ });
94
+ child.on("close", (code, signal) => {
95
+ clearTimeout(timer);
96
+ if (code === 0) done();
97
+ else fail(new BlockedError(summarizeCommandFailure(tail, "install", signal ?? code)));
98
+ });
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Make dependencies available for a JavaScript test in `directory`.
104
+ * - Already installed: use them.
105
+ * - Exact-commit checkout with the same lockfile as the developer's clone: link
106
+ * the clone's node_modules instead of reinstalling.
107
+ * - Otherwise install with lifecycle scripts off, when allowed.
108
+ */
109
+ async function prepareJavaScript({ directory, repo, testPath, install, progress, cacheDir }) {
110
+ const pkgDir = await packageDirectory(directory, testPath);
111
+ if (!pkgDir) return "none";
112
+ const manager = await detectPackageManager(directory, pkgDir);
113
+ const roots = [...new Set([manager.installRoot, pkgDir])];
114
+ const manifests = await Promise.all(roots.map((root) => readJson(join(root, "package.json"))));
115
+ if (!manifests.some(declaresDependencies)) return "none";
116
+ if (await exists(join(manager.installRoot, "node_modules"))) return "existing";
117
+ if (directory !== repo) {
118
+ const source = resolve(repo, relative(directory, manager.installRoot));
119
+ if (
120
+ (await exists(join(source, "node_modules"))) &&
121
+ (await sameDependencies(source, manager.installRoot))
122
+ ) {
123
+ for (const root of roots) {
124
+ const from = resolve(repo, relative(directory, root), "node_modules");
125
+ const to = join(root, "node_modules");
126
+ if ((await exists(from)) && !(await exists(to)))
127
+ await symlink(from, to, process.platform === "win32" ? "junction" : "dir");
128
+ }
129
+ return "linked";
130
+ }
131
+ }
132
+ if (!install)
133
+ throw new BlockedError(
134
+ `Dependencies are not installed in ${relative(repo, manager.installRoot) || "the repository root"}. Install them, or pass --install.`,
135
+ );
136
+ if (directory !== repo && cacheDir && roots.length === 1) {
137
+ const cached = await cachedDependencies({
138
+ manager,
139
+ manifest: manifests[0],
140
+ cacheDir,
141
+ progress,
142
+ });
143
+ if (cached) {
144
+ await symlink(
145
+ cached.nodeModules,
146
+ join(manager.installRoot, "node_modules"),
147
+ process.platform === "win32" ? "junction" : "dir",
148
+ );
149
+ return cached.reused ? "cached" : "installed";
150
+ }
151
+ }
152
+ let command = installCommand(manager);
153
+ if (manager.name === "npm" && !(await exists(join(manager.installRoot, "package-lock.json"))))
154
+ command = { ...command, args: ["install", "--ignore-scripts", "--no-audit", "--no-fund"] };
155
+ progress?.(`Installing dependencies with ${manager.name}...`);
156
+ await runInstall(command, manager.installRoot, 10 * 60 * 1000);
157
+ return "installed";
158
+ }
159
+
160
+ /** Per-user cache directory: TRACEYARD_CACHE_DIR, else the platform's cache location. */
161
+ export function cacheDirectory(env = process.env) {
162
+ if (env.TRACEYARD_CACHE_DIR) return resolve(env.TRACEYARD_CACHE_DIR);
163
+ if (process.platform === "win32")
164
+ return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "traceyard", "Cache");
165
+ if (process.platform === "darwin") return join(homedir(), "Library", "Caches", "traceyard");
166
+ return join(env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "traceyard");
167
+ }
168
+
169
+ const KEEP_DEPENDENCY_SETS = 5;
170
+ const COMPLETE = ".traceyard-complete";
171
+
172
+ /**
173
+ * Install dependencies once per lockfile and reuse them for every exact-commit
174
+ * run with the same lockfile. Keyed by package manager, lockfile, package.json,
175
+ * Node major version and platform. Only for single-package projects whose
176
+ * dependencies come from a registry: workspaces and file:/link: dependencies
177
+ * need the full checkout, so they install in place.
178
+ */
179
+ async function cachedDependencies({ manager, manifest, cacheDir, progress }) {
180
+ if (!manifest || manifest.workspaces) return null;
181
+ const local = ["dependencies", "devDependencies", "optionalDependencies"].some((field) =>
182
+ Object.values(manifest[field] ?? {}).some((spec) =>
183
+ /^(?:file:|link:|workspace:|portal:|\.{0,2}\/)/.test(String(spec)),
184
+ ),
185
+ );
186
+ if (local || (await exists(join(manager.installRoot, ".yarnrc.yml")))) return null;
187
+ let lockfile = null;
188
+ for (const name of lockfileNames)
189
+ if (await exists(join(manager.installRoot, name))) {
190
+ lockfile = name;
191
+ break;
192
+ }
193
+ if (!lockfile) return null;
194
+ const hash = createHash("sha256");
195
+ hash.update(manager.name + "\0" + process.version.split(".")[0] + "\0" + process.platform);
196
+ hash.update("\0" + process.arch);
197
+ for (const name of [lockfile, "package.json", ".npmrc"])
198
+ hash.update(
199
+ "\0" +
200
+ name +
201
+ "\0" +
202
+ ((await readFile(join(manager.installRoot, name)).catch(() => "")) || ""),
203
+ );
204
+ const key = hash.digest("hex").slice(0, 20);
205
+ const root = join(cacheDir, "deps", key);
206
+ const nodeModules = join(root, "node_modules");
207
+ if (await exists(join(nodeModules, COMPLETE))) {
208
+ const now = new Date();
209
+ await utimes(root, now, now).catch(() => {});
210
+ return { nodeModules, reused: true };
211
+ }
212
+ await rm(root, { recursive: true, force: true });
213
+ await mkdir(root, { recursive: true });
214
+ for (const name of [lockfile, "package.json", ".npmrc"])
215
+ if (await exists(join(manager.installRoot, name)))
216
+ await copyFile(join(manager.installRoot, name), join(root, name));
217
+ let command = installCommand(manager);
218
+ if (
219
+ manager.name === "npm" &&
220
+ lockfile !== "package-lock.json" &&
221
+ lockfile !== "npm-shrinkwrap.json"
222
+ )
223
+ command = { ...command, args: ["install", "--ignore-scripts", "--no-audit", "--no-fund"] };
224
+ progress?.(`Installing dependencies with ${manager.name} (cached for next time)...`);
225
+ try {
226
+ await runInstall(command, root, 10 * 60 * 1000);
227
+ } catch (error) {
228
+ await rm(root, { recursive: true, force: true });
229
+ throw error;
230
+ }
231
+ if (!(await exists(nodeModules))) {
232
+ await rm(root, { recursive: true, force: true });
233
+ return null;
234
+ }
235
+ await writeFile(join(nodeModules, COMPLETE), new Date().toISOString() + "\n");
236
+ await pruneDependencyCache(join(cacheDir, "deps"), key);
237
+ return { nodeModules, reused: false };
238
+ }
239
+
240
+ /** Keep the most recently used dependency sets; delete the rest. */
241
+ async function pruneDependencyCache(depsDir, keep) {
242
+ const entries = await readdir(depsDir).catch(() => []);
243
+ const dated = [];
244
+ for (const name of entries)
245
+ dated.push({ name, time: (await stat(join(depsDir, name)).catch(() => null))?.mtimeMs ?? 0 });
246
+ dated.sort((a, b) => b.time - a.time);
247
+ for (const { name } of dated.slice(KEEP_DEPENDENCY_SETS))
248
+ if (name !== keep) await rm(join(depsDir, name), { recursive: true, force: true });
249
+ }
250
+
251
+ async function canRunPytest(python) {
252
+ try {
253
+ await execFileAsync(python, ["-c", "import pytest"], { timeout: 15000 });
254
+ return true;
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+
260
+ /** A Python interpreter that can import pytest: TRACEYARD_PYTHON, a repo virtualenv, then PATH. */
261
+ async function findPython(repo, env) {
262
+ const windows = process.platform === "win32";
263
+ const candidates = [
264
+ env.TRACEYARD_PYTHON,
265
+ env.VIRTUAL_ENV && join(env.VIRTUAL_ENV, windows ? "Scripts/python.exe" : "bin/python"),
266
+ ...[".venv", "venv"].map((name) =>
267
+ join(repo, name, windows ? "Scripts/python.exe" : "bin/python"),
268
+ ),
269
+ windows ? "python" : "python3",
270
+ "python",
271
+ ].filter(Boolean);
272
+ for (const candidate of candidates) if (await canRunPytest(candidate)) return candidate;
273
+ throw new BlockedError(
274
+ "No Python with pytest was found. Activate your virtualenv, or set TRACEYARD_PYTHON to an interpreter that has pytest installed.",
275
+ );
276
+ }
277
+
278
+ /** Evidence ID for a run at a commit. The same commit and test always map to the same ID. */
279
+ const commitEvidenceId = (sha, testPath, testCase) =>
280
+ "ev_" +
281
+ sha.slice(0, 12) +
282
+ "_" +
283
+ createHash("sha256")
284
+ .update(JSON.stringify({ sha, testPath, testCase: testCase ?? null, version: VERSION }))
285
+ .digest("hex")
286
+ .slice(0, 12);
287
+
288
+ /** Working-tree runs can't be cached (the files change), so each gets its own ID. */
289
+ const workingTreeEvidenceId = () =>
290
+ "ev_wt_" + Date.now().toString(36) + "_" + randomBytes(3).toString("hex");
291
+
292
+ export const EVIDENCE_ID = /^ev_[a-z0-9]+_[a-z0-9_]+$/;
293
+ const KEEP_WORKING_TREE_RUNS = 20;
294
+
295
+ /** Load a recorded run by its evidence ID. */
296
+ export async function readEvidence(stateDir, evidenceId) {
297
+ if (!EVIDENCE_ID.test(evidenceId ?? "")) return null;
298
+ return readJson(join(stateDir, "runs", evidenceId + ".json"));
299
+ }
300
+
301
+ /** Recorded runs, newest first. */
302
+ export async function listEvidence(stateDir, limit = 8) {
303
+ const dir = join(stateDir, "runs");
304
+ const names = (await readdir(dir).catch(() => [])).filter((n) => /^ev_.*\.json$/.test(n));
305
+ const runs = [];
306
+ for (const name of names) {
307
+ const run = await readJson(join(dir, name));
308
+ if (run?.evidenceId) runs.push(run);
309
+ }
310
+ runs.sort((a, b) => String(b.recordedAt).localeCompare(String(a.recordedAt)));
311
+ return runs.slice(0, limit);
312
+ }
313
+
314
+ async function pruneWorkingTreeRuns(dir) {
315
+ const names = (await readdir(dir).catch(() => []))
316
+ .filter((n) => n.startsWith("ev_wt_"))
317
+ .sort()
318
+ .reverse();
319
+ for (const name of names.slice(KEEP_WORKING_TREE_RUNS))
320
+ await rm(join(dir, name), { force: true });
321
+ }
322
+
323
+ function blockedRun(commit, message, started) {
324
+ return {
325
+ commit,
326
+ status: "BLOCKED",
327
+ counts: { passed: 0, failed: 0, skipped: 0 },
328
+ failures: [],
329
+ truncated: false,
330
+ message,
331
+ durationMs: Date.now() - started,
332
+ exitCode: null,
333
+ runner: null,
334
+ output: "",
335
+ dependencies: "none",
336
+ cached: false,
337
+ evidenceId: null,
338
+ };
339
+ }
340
+
341
+ /**
342
+ * Run one test, either in the working tree (commit = null) or at an exact
343
+ * commit in a throwaway worktree. Results at a commit are cached in
344
+ * `.traceyard/runs` so the same commit and test never run twice.
345
+ */
346
+ export async function runTest({
347
+ repo,
348
+ cacheDir = cacheDirectory(),
349
+ commit,
350
+ testPath,
351
+ testCase,
352
+ install = false,
353
+ fetch = false,
354
+ fresh = false,
355
+ timeoutMs = 180000,
356
+ stateDir,
357
+ progress,
358
+ env = process.env,
359
+ }) {
360
+ const started = Date.now();
361
+ let sha = null;
362
+ if (commit) {
363
+ try {
364
+ sha = await ensureCommit(repo, commit, { fetch });
365
+ } catch (error) {
366
+ throw new BlockedError(error.message);
367
+ }
368
+ const cached = await readEvidence(stateDir, commitEvidenceId(sha, testPath, testCase));
369
+ if (cached && !fresh) return { ...cached, cached: true };
370
+ }
371
+ const python = isPytestFile(testPath);
372
+ let dependencies = "none";
373
+ const runEnv = { ...env, CI: env.CI ?? "true" };
374
+ try {
375
+ if (python) runEnv.TRACEYARD_PYTEST_PYTHON = await findPython(repo, env);
376
+ else if (!commit)
377
+ dependencies = await prepareJavaScript({
378
+ directory: repo,
379
+ repo,
380
+ testPath,
381
+ install,
382
+ progress,
383
+ });
384
+ } catch (error) {
385
+ if (error instanceof BlockedError) return blockedRun(sha, error.message, started);
386
+ throw error;
387
+ }
388
+ progress?.(`Running ${testPath}${sha ? " at " + sha.slice(0, 12) : " in your working tree"}...`);
389
+ let report;
390
+ try {
391
+ report = await runLocalTest({
392
+ repo,
393
+ commit: sha ?? undefined,
394
+ testPath,
395
+ testCase,
396
+ timeoutMs,
397
+ env: runEnv,
398
+ beforeRun:
399
+ commit && !python
400
+ ? async (directory) => {
401
+ dependencies = await prepareJavaScript({
402
+ directory,
403
+ repo,
404
+ testPath,
405
+ install: true,
406
+ progress,
407
+ cacheDir,
408
+ });
409
+ }
410
+ : undefined,
411
+ });
412
+ } catch (error) {
413
+ if (error instanceof BlockedError) return blockedRun(sha, error.message, started);
414
+ throw error;
415
+ }
416
+ const missing = /not present in this snapshot's index/.test(report.message);
417
+ const result = {
418
+ commit: sha,
419
+ status: report.status,
420
+ counts: report.counts,
421
+ failures: report.failures,
422
+ truncated: report.truncated,
423
+ message: missing
424
+ ? `${testPath} isn't a test file Traceyard can find ${sha ? "at " + sha.slice(0, 12) : "in your working tree"}. Check the path; it must be a Vitest, Jest or Pytest test file.`
425
+ : report.message,
426
+ durationMs: report.durationMs,
427
+ exitCode: report.exitCode,
428
+ runner: report.command?.script
429
+ ? { script: report.command.script, directory: report.command.directory }
430
+ : null,
431
+ output: cleanOutput(report.output ?? "", repo),
432
+ dependencies,
433
+ cached: false,
434
+ evidenceId: null,
435
+ };
436
+ if (result.status !== "BLOCKED") {
437
+ // Every run that executed is kept as evidence, so agents can read the full
438
+ // log later in bounded slices instead of receiving it up front.
439
+ result.evidenceId = sha ? commitEvidenceId(sha, testPath, testCase) : workingTreeEvidenceId();
440
+ const dir = join(stateDir, "runs");
441
+ await mkdir(dir, { recursive: true });
442
+ await writeFile(
443
+ join(dir, result.evidenceId + ".json"),
444
+ JSON.stringify(
445
+ {
446
+ ...result,
447
+ test: { path: testPath, case: testCase ?? null },
448
+ recordedAt: new Date().toISOString(),
449
+ },
450
+ null,
451
+ 2,
452
+ ),
453
+ );
454
+ if (!sha) await pruneWorkingTreeRuns(dir);
455
+ }
456
+ return result;
457
+ }
@@ -0,0 +1,189 @@
1
+ // Verdicts and exit codes for every command. Pure functions, so the rules are
2
+ // easy to read and test. Exit codes are part of the public contract (docs/CLI.md).
3
+
4
+ export const EXIT = {
5
+ OK: 0, // REPRODUCED, PASSED, FIXED
6
+ FAILING: 1, // FAILING, STILL_FAILING, UNVERIFIED
7
+ REVIEW: 2, // NOT_REPRODUCED, NEEDS_REVIEW, INCONCLUSIVE
8
+ BLOCKED: 3, // BLOCKED: the test could not run here
9
+ USAGE: 64, // bad arguments
10
+ INTERNAL: 70, // a bug in Traceyard
11
+ };
12
+
13
+ export const exitCodeFor = (verdict) =>
14
+ ({
15
+ REPRODUCED: EXIT.OK,
16
+ PASSED: EXIT.OK,
17
+ FIXED: EXIT.OK,
18
+ AVAILABLE: EXIT.OK,
19
+ FAILING: EXIT.FAILING,
20
+ STILL_FAILING: EXIT.FAILING,
21
+ UNVERIFIED: EXIT.FAILING,
22
+ NOT_REPRODUCED: EXIT.REVIEW,
23
+ NEEDS_REVIEW: EXIT.REVIEW,
24
+ INCONCLUSIVE: EXIT.REVIEW,
25
+ BLOCKED: EXIT.BLOCKED,
26
+ ERROR: EXIT.USAGE,
27
+ })[verdict] ?? EXIT.INTERNAL;
28
+
29
+ const short = (sha) => (sha ? sha.slice(0, 12) : "your working tree");
30
+
31
+ /** Tests, fixtures, snapshots and Pytest configuration: edits here can make a test pass without a fix. */
32
+ export const isTestInput = (path) =>
33
+ /\.(?:test|spec|fixture)\.[cm]?[jt]sx?$|(?:^|\/)(?:__(?:tests|fixtures|snapshots|mocks)__|tests?|fixtures?)\/|\.snap$/i.test(
34
+ path,
35
+ ) ||
36
+ /(?:^|\/)(?:test_[^/]+\.py|[^/]+_test\.py|conftest\.py|pytest\.ini|pyproject\.toml|setup\.cfg|tox\.ini|requirements[^/]*\.txt)$/.test(
37
+ path,
38
+ ) ||
39
+ /(?:^|\/)(?:vitest|vite|jest)\.config\.[cm]?[jt]s$/.test(path);
40
+
41
+ export function reproVerdict(run, testPath, { fromCi = false } = {}) {
42
+ if (run.status === "BLOCKED")
43
+ return {
44
+ verdict: "BLOCKED",
45
+ summary: run.message,
46
+ next: "Fix what blocked the run, then rerun the same command.",
47
+ };
48
+ if (run.status === "FAILED")
49
+ return {
50
+ verdict: "REPRODUCED",
51
+ summary: `${testPath} fails at ${short(run.commit)}: ${run.counts.failed} failed, ${run.counts.passed} passed.`,
52
+ next: "Fix the code, not the test. Run `traceyard check` after each attempt, then commit and run `traceyard verify`.",
53
+ };
54
+ return {
55
+ verdict: "NOT_REPRODUCED",
56
+ summary: `${testPath} passed at ${short(run.commit)}, so the failure did not reproduce.`,
57
+ next: fromCi
58
+ ? "This is the commit CI tested, so the failure may depend on CI's environment or on another test. Check the job log, then try the failing test CI named."
59
+ : "Check the commit and test file. If CI failed, pass the job link with --from so Traceyard uses the commit CI tested.",
60
+ };
61
+ }
62
+
63
+ export function checkVerdict(run, testPath) {
64
+ if (run.status === "BLOCKED")
65
+ return {
66
+ verdict: "BLOCKED",
67
+ summary: run.message,
68
+ next: "Fix what blocked the run, then rerun `traceyard check`.",
69
+ };
70
+ if (run.status === "FAILED")
71
+ return {
72
+ verdict: "FAILING",
73
+ summary: `${testPath} still fails in ${short(run.commit)}: ${run.counts.failed} failed, ${run.counts.passed} passed.`,
74
+ next: "Read the first failure, change the code, and run `traceyard check` again.",
75
+ };
76
+ if (!run.counts.passed)
77
+ return {
78
+ verdict: "BLOCKED",
79
+ summary: `${testPath} ran no passing tests, so nothing was checked.`,
80
+ next: "Make sure the test is not skipped, then rerun `traceyard check`.",
81
+ };
82
+ return {
83
+ verdict: "PASSED",
84
+ summary: `${testPath} passes in ${short(run.commit)}: ${run.counts.passed} passed.`,
85
+ next: "Commit the fix and run `traceyard verify` to record a receipt.",
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Compare a baseline (failing commit) and a candidate (fix commit). Mirrors the
91
+ * hosted verification: a pass only counts as FIXED when the failure reproduced,
92
+ * the same test passed, nothing was skipped away and no test inputs changed.
93
+ */
94
+ export function verifyVerdict({ baseline, candidate, testPath, changedFiles }) {
95
+ const changedTests = changedFiles.filter(isTestInput);
96
+ const result = (verdict, summary, next) => ({ verdict, summary, next, changedTests });
97
+ if (baseline.status === "BLOCKED")
98
+ return result(
99
+ "BLOCKED",
100
+ "The failing commit could not run: " + baseline.message,
101
+ "Fix what blocked the run, then rerun `traceyard verify`.",
102
+ );
103
+ if (baseline.status !== "FAILED" || !baseline.counts.failed)
104
+ return result(
105
+ "NOT_REPRODUCED",
106
+ `${testPath} passed at the failing commit ${short(baseline.commit)}, so there is no failure to verify a fix against.`,
107
+ "Check the --before commit. Use the commit CI tested, or pass the job link to `traceyard repro --from`.",
108
+ );
109
+ if (candidate.status === "BLOCKED")
110
+ return result(
111
+ "BLOCKED",
112
+ "The fix commit could not run: " + candidate.message,
113
+ "Fix what blocked the run, then rerun `traceyard verify`.",
114
+ );
115
+ if (baseline.commit === candidate.commit)
116
+ return result(
117
+ "INCONCLUSIVE",
118
+ "The failing commit and the fix commit are the same.",
119
+ "Commit the fix, then run `traceyard verify` again.",
120
+ );
121
+ if (candidate.status === "FAILED") {
122
+ const same =
123
+ candidate.failures[0]?.name && candidate.failures[0].name === baseline.failures[0]?.name;
124
+ return result(
125
+ "STILL_FAILING",
126
+ same
127
+ ? `${testPath} still fails at ${short(candidate.commit)} with the same test case.`
128
+ : `${testPath} fails at ${short(candidate.commit)} with a different test case.`,
129
+ "Read the first failure, change the code, and run `traceyard check` before verifying again.",
130
+ );
131
+ }
132
+ if (!candidate.counts.passed || candidate.counts.skipped > baseline.counts.skipped)
133
+ return result(
134
+ "INCONCLUSIVE",
135
+ `${testPath} did not fail at ${short(candidate.commit)}, but ${candidate.counts.skipped - baseline.counts.skipped} more test(s) were skipped, so the pass doesn't prove a fix.`,
136
+ "Remove the skips and verify again.",
137
+ );
138
+ if (changedTests.length)
139
+ return result(
140
+ "NEEDS_REVIEW",
141
+ `${testPath} passes at ${short(candidate.commit)}, but test files or fixtures changed between the commits.`,
142
+ "Review the changed test files before accepting the fix. A fix should change code, not the test.",
143
+ );
144
+ return result(
145
+ "FIXED",
146
+ `${testPath} failed at ${short(baseline.commit)} and passes at ${short(candidate.commit)}, with no test files changed.`,
147
+ "Open a pull request and attach the receipt.",
148
+ );
149
+ }
150
+
151
+ /**
152
+ * The merge gate. FIXED only for an intact receipt whose verdict is FIXED and
153
+ * whose fix commit is exactly HEAD; anything else keeps the claim unproven.
154
+ */
155
+ export function guardVerdict({ receipt, intact, head }) {
156
+ const verify = "Run `traceyard verify` on the fix commit, then run `traceyard guard` again.";
157
+ if (!receipt)
158
+ return {
159
+ verdict: "UNVERIFIED",
160
+ summary: "No receipt yet, so nothing proves this commit fixes a failing test.",
161
+ next: "Run `traceyard repro <test>` on the failing commit, fix the code, commit, then `traceyard verify`.",
162
+ };
163
+ if (!intact)
164
+ return {
165
+ verdict: "NEEDS_REVIEW",
166
+ summary: `Receipt ${receipt.id} was edited after it was written; its digest doesn't match.`,
167
+ next: verify,
168
+ };
169
+ if (receipt.verdict !== "FIXED")
170
+ return {
171
+ verdict: receipt.verdict === "NEEDS_REVIEW" ? "NEEDS_REVIEW" : "UNVERIFIED",
172
+ summary: `The latest receipt (${receipt.id}) says ${receipt.verdict}, not FIXED: ${receipt.summary}`,
173
+ next:
174
+ receipt.verdict === "NEEDS_REVIEW"
175
+ ? "A person should review the changed test files before this merges."
176
+ : verify,
177
+ };
178
+ if (!head || receipt.candidate?.commit !== head)
179
+ return {
180
+ verdict: "UNVERIFIED",
181
+ summary: `Receipt ${receipt.id} proves ${short(receipt.candidate?.commit)}, but HEAD is ${short(head)}. Commits after the receipt aren't verified.`,
182
+ next: verify,
183
+ };
184
+ return {
185
+ verdict: "FIXED",
186
+ summary: `HEAD ${short(head)} is proven: ${receipt.test.path} failed at ${short(receipt.baseline.commit)} and passes here, with no test files changed.`,
187
+ next: "Safe to open or merge the pull request. Attach the receipt.",
188
+ };
189
+ }
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const VERSION = JSON.parse(
4
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
5
+ ).version;