traceyard 0.0.0-stage → 0.1.1

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,461 @@
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
+ // JavaScript evidence from before runner configs were recorded can't be
370
+ // compared for a changed test script, so it is rerun rather than reused.
371
+ const comparable = isPytestFile(testPath) || typeof cached?.runnerConfig === "string";
372
+ if (cached && !fresh && comparable) return { ...cached, cached: true };
373
+ }
374
+ const python = isPytestFile(testPath);
375
+ let dependencies = "none";
376
+ const runEnv = { ...env, CI: env.CI ?? "true" };
377
+ try {
378
+ if (python) runEnv.TRACEYARD_PYTEST_PYTHON = await findPython(repo, env);
379
+ else if (!commit)
380
+ dependencies = await prepareJavaScript({
381
+ directory: repo,
382
+ repo,
383
+ testPath,
384
+ install,
385
+ progress,
386
+ });
387
+ } catch (error) {
388
+ if (error instanceof BlockedError) return blockedRun(sha, error.message, started);
389
+ throw error;
390
+ }
391
+ progress?.(`Running ${testPath}${sha ? " at " + sha.slice(0, 12) : " in your working tree"}...`);
392
+ let report;
393
+ try {
394
+ report = await runLocalTest({
395
+ repo,
396
+ commit: sha ?? undefined,
397
+ testPath,
398
+ testCase,
399
+ timeoutMs,
400
+ env: runEnv,
401
+ beforeRun:
402
+ commit && !python
403
+ ? async (directory) => {
404
+ dependencies = await prepareJavaScript({
405
+ directory,
406
+ repo,
407
+ testPath,
408
+ install: true,
409
+ progress,
410
+ cacheDir,
411
+ });
412
+ }
413
+ : undefined,
414
+ });
415
+ } catch (error) {
416
+ if (error instanceof BlockedError) return blockedRun(sha, error.message, started);
417
+ throw error;
418
+ }
419
+ const missing = /not present in this snapshot's index/.test(report.message);
420
+ const result = {
421
+ commit: sha,
422
+ status: report.status,
423
+ counts: report.counts,
424
+ failures: report.failures,
425
+ truncated: report.truncated,
426
+ message: missing
427
+ ? `${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.`
428
+ : report.message,
429
+ durationMs: report.durationMs,
430
+ exitCode: report.exitCode,
431
+ runner: report.command?.script
432
+ ? { script: report.command.script, directory: report.command.directory }
433
+ : null,
434
+ runnerConfig: report.runnerConfig ?? null,
435
+ output: cleanOutput(report.output ?? "", repo),
436
+ dependencies,
437
+ cached: false,
438
+ evidenceId: null,
439
+ };
440
+ if (result.status !== "BLOCKED") {
441
+ // Every run that executed is kept as evidence, so agents can read the full
442
+ // log later in bounded slices instead of receiving it up front.
443
+ result.evidenceId = sha ? commitEvidenceId(sha, testPath, testCase) : workingTreeEvidenceId();
444
+ const dir = join(stateDir, "runs");
445
+ await mkdir(dir, { recursive: true });
446
+ await writeFile(
447
+ join(dir, result.evidenceId + ".json"),
448
+ JSON.stringify(
449
+ {
450
+ ...result,
451
+ test: { path: testPath, case: testCase ?? null },
452
+ recordedAt: new Date().toISOString(),
453
+ },
454
+ null,
455
+ 2,
456
+ ),
457
+ );
458
+ if (!sha) await pruneWorkingTreeRuns(dir);
459
+ }
460
+ return result;
461
+ }