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.
- package/LICENSE +21 -0
- package/README.md +234 -2
- package/lib/cli/bin/traceyard.mjs +4 -0
- package/lib/cli/package.json +5 -0
- package/lib/cli/src/compact.mjs +73 -0
- package/lib/cli/src/errors.mjs +9 -0
- package/lib/cli/src/evidence.mjs +235 -0
- package/lib/cli/src/git.mjs +249 -0
- package/lib/cli/src/github.mjs +139 -0
- package/lib/cli/src/main.mjs +915 -0
- package/lib/cli/src/mcp.mjs +317 -0
- package/lib/cli/src/receipt.mjs +172 -0
- package/lib/cli/src/run.mjs +461 -0
- package/lib/cli/src/verdicts.mjs +254 -0
- package/lib/cli/src/version.mjs +5 -0
- package/lib/core/src/agent-result.mjs +185 -0
- package/lib/core/src/ci-link.mjs +130 -0
- package/lib/core/src/discovery.mjs +105 -0
- package/lib/core/src/evidence.mjs +118 -0
- package/lib/core/src/failure-summary.mjs +39 -0
- package/lib/core/src/index.mjs +70 -0
- package/lib/core/src/package-manager.mjs +97 -0
- package/lib/core/src/pytest-runner.py +68 -0
- package/lib/core/src/pytest.mjs +118 -0
- package/lib/core/src/repository-index.mjs +310 -0
- package/lib/core/src/runners.mjs +103 -0
- package/lib/core/src/source-flow.mjs +135 -0
- package/lib/core/src/test-evidence.mjs +326 -0
- package/lib/core/src/test-inputs.mjs +97 -0
- package/lib/core/src/test-report.mjs +64 -0
- package/lib/core/src/worktree.mjs +95 -0
- package/package.json +45 -4
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { chown, readFile, realpath, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { constants as fsConstants } from "node:fs";
|
|
3
|
+
import { join, resolve, relative, isAbsolute } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { summarizeCommandFailure } from "./failure-summary.mjs";
|
|
7
|
+
import { relatedTests } from "./repository-index.mjs";
|
|
8
|
+
import { isPytestFile } from "./pytest.mjs";
|
|
9
|
+
import { adapterForFile, adapterForScript, runnerAdapters } from "./runners.mjs";
|
|
10
|
+
import { detectPackageManager, scriptCommand } from "./package-manager.mjs";
|
|
11
|
+
import { runnerConfigDigest } from "./test-inputs.mjs";
|
|
12
|
+
|
|
13
|
+
import { sanitizeDiagnostic, normalizeVitestReport } from "./test-report.mjs";
|
|
14
|
+
export { sanitizeDiagnostic, normalizeVitestReport };
|
|
15
|
+
export function selectTest(index, question, testPath) {
|
|
16
|
+
const tests = index.files.filter((f) => f.isTest);
|
|
17
|
+
if (testPath) {
|
|
18
|
+
const test = tests.find((f) => f.path === testPath);
|
|
19
|
+
return test
|
|
20
|
+
? { test }
|
|
21
|
+
: {
|
|
22
|
+
reason: "The selected test file is not present in this snapshot's index.",
|
|
23
|
+
candidates: [],
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const words =
|
|
27
|
+
question
|
|
28
|
+
.toLowerCase()
|
|
29
|
+
.match(/[a-z0-9_-]{3,}/g)
|
|
30
|
+
?.filter(
|
|
31
|
+
(w) =>
|
|
32
|
+
![
|
|
33
|
+
"investigate",
|
|
34
|
+
"failing",
|
|
35
|
+
"failed",
|
|
36
|
+
"failure",
|
|
37
|
+
"tests",
|
|
38
|
+
"test",
|
|
39
|
+
"debug",
|
|
40
|
+
"please",
|
|
41
|
+
"why",
|
|
42
|
+
"the",
|
|
43
|
+
"with",
|
|
44
|
+
"and",
|
|
45
|
+
"this",
|
|
46
|
+
].includes(w),
|
|
47
|
+
) ?? [];
|
|
48
|
+
const ranked = tests
|
|
49
|
+
.map((test) => ({
|
|
50
|
+
test,
|
|
51
|
+
score: words.reduce(
|
|
52
|
+
(n, w) =>
|
|
53
|
+
n +
|
|
54
|
+
(test.path.toLowerCase().includes(w) ? 3 : 0) +
|
|
55
|
+
(test.tests.some((t) => t.name.toLowerCase().includes(w)) ? 1 : 0),
|
|
56
|
+
0,
|
|
57
|
+
),
|
|
58
|
+
}))
|
|
59
|
+
.sort((a, b) => b.score - a.score || a.test.path.localeCompare(b.test.path));
|
|
60
|
+
if (ranked.length === 1 || (ranked[0]?.score > 0 && ranked[0].score > (ranked[1]?.score ?? -1)))
|
|
61
|
+
return { test: ranked[0].test };
|
|
62
|
+
return {
|
|
63
|
+
reason: tests.length
|
|
64
|
+
? "More than one test could match. Select one of the indexed test paths."
|
|
65
|
+
: "No supported existing test was discovered.",
|
|
66
|
+
candidates: ranked.slice(0, 8).map((x) => x.test.path),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export async function prepareTargetedTest(workspace, index, plan) {
|
|
70
|
+
const selection = selectTest(index, plan.question, plan.testPath);
|
|
71
|
+
if (!selection.test)
|
|
72
|
+
return {
|
|
73
|
+
reason:
|
|
74
|
+
selection.reason +
|
|
75
|
+
(selection.candidates.length ? " Candidates: " + selection.candidates.join(", ") : ""),
|
|
76
|
+
};
|
|
77
|
+
const test = selection.test;
|
|
78
|
+
if (!/^[A-Za-z0-9_./@-]+$/.test(test.path))
|
|
79
|
+
return { reason: "This test path is outside the supported command argument format." };
|
|
80
|
+
const root = await realpath(workspace);
|
|
81
|
+
const directory = await realpath(resolve(root, test.packageDirectory));
|
|
82
|
+
const file = await realpath(resolve(root, test.path));
|
|
83
|
+
const packagePath = relative(root, directory);
|
|
84
|
+
const filePath = relative(directory, file);
|
|
85
|
+
if ([packagePath, filePath].some((path) => path.startsWith("..") || isAbsolute(path)))
|
|
86
|
+
return { reason: "The selected test escapes its package workspace." };
|
|
87
|
+
const fileAdapter = adapterForFile(test.path);
|
|
88
|
+
if (fileAdapter?.prepare) return fileAdapter.prepare(directory, file, test, plan);
|
|
89
|
+
if (plan.testCase !== undefined) return { reason: "A case selector requires a Pytest file." };
|
|
90
|
+
let pkg;
|
|
91
|
+
try {
|
|
92
|
+
pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
|
|
93
|
+
} catch {
|
|
94
|
+
return { reason: "The selected test needs a readable package.json." };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const candidates = Object.entries(pkg.scripts ?? {}).flatMap(([name, command]) => {
|
|
98
|
+
if (!/^[A-Za-z0-9:_-]+$/.test(name) || typeof command !== "string" || /[;&|\r\n]/.test(command))
|
|
99
|
+
return [];
|
|
100
|
+
const adapter = adapterForScript(command);
|
|
101
|
+
return adapter ? [{ name, runner: adapter.name }] : [];
|
|
102
|
+
});
|
|
103
|
+
const matching = candidates.filter(({ name }) => {
|
|
104
|
+
const kind = name.replace(/^test:/, "").toLowerCase();
|
|
105
|
+
return name.startsWith("test:") && test.path.toLowerCase().split("/").includes(kind);
|
|
106
|
+
});
|
|
107
|
+
const selected =
|
|
108
|
+
candidates.find(({ name }) => name === "test") ??
|
|
109
|
+
(matching.length === 1 ? matching[0] : candidates.length === 1 ? candidates[0] : null);
|
|
110
|
+
if (!selected)
|
|
111
|
+
return {
|
|
112
|
+
reason:
|
|
113
|
+
"Select a test in an npm package with a clear Vitest or Jest script. Use a direct test command rather than a script that chains several checks.",
|
|
114
|
+
};
|
|
115
|
+
if (plan.replayRecording && !runnerAdapters[selected.runner].supports.replay)
|
|
116
|
+
return { reason: "Isolated interaction replay requires Vitest." };
|
|
117
|
+
return {
|
|
118
|
+
root,
|
|
119
|
+
directory,
|
|
120
|
+
file,
|
|
121
|
+
runner: selected.runner,
|
|
122
|
+
runnerConfig: await runnerConfigDigest({ root, directory, pkg, script: selected.name }),
|
|
123
|
+
command: { directory: test.packageDirectory, script: selected.name, testPath: test.path },
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Options:
|
|
129
|
+
* - `replay(root, command, plan)`: runs a recorded replay. Only the hosted runner
|
|
130
|
+
* provides it, because it needs Docker; without it replay plans are blocked.
|
|
131
|
+
* - `packageManager`: force "npm" | "pnpm" | "yarn" | "bun" instead of detecting it.
|
|
132
|
+
*/
|
|
133
|
+
export async function runTargetedTest(workspace, index, plan, env, options = {}) {
|
|
134
|
+
const started = Date.now();
|
|
135
|
+
const blocked = (message, command = { directory: ".", script: "", testPath: null }) => ({
|
|
136
|
+
status: "BLOCKED",
|
|
137
|
+
counts: { passed: 0, failed: 0, skipped: 0 },
|
|
138
|
+
failures: [],
|
|
139
|
+
truncated: false,
|
|
140
|
+
message: sanitizeDiagnostic(message, 2000),
|
|
141
|
+
durationMs: Date.now() - started,
|
|
142
|
+
exitCode: null,
|
|
143
|
+
nodeVersion: process.version,
|
|
144
|
+
command,
|
|
145
|
+
});
|
|
146
|
+
const prepared = await prepareTargetedTest(workspace, index, plan);
|
|
147
|
+
if (prepared.reason) return blocked(prepared.reason);
|
|
148
|
+
const { root, directory, file, runner, command, runnerConfig } = prepared;
|
|
149
|
+
if (plan.replayRecording)
|
|
150
|
+
return options.replay
|
|
151
|
+
? options.replay(root, command, plan)
|
|
152
|
+
: blocked("Recorded replay needs the isolated Traceyard runner.", command);
|
|
153
|
+
const adapter = runnerAdapters[runner];
|
|
154
|
+
const path = relative(directory, file).split("\\").join("/");
|
|
155
|
+
const testArgument = path.startsWith("-") ? "./" + path : path;
|
|
156
|
+
const temporary = await mkdtemp(join(tmpdir(), "traceyard-evidence-")),
|
|
157
|
+
output = join(temporary, "report.json");
|
|
158
|
+
// A hosted sandbox runs the test as a separate user, which must own the
|
|
159
|
+
// directory its structured reporter writes to.
|
|
160
|
+
const sandbox = options.sandbox ?? null;
|
|
161
|
+
if (sandbox) await chown(temporary, sandbox.uid, sandbox.gid);
|
|
162
|
+
let tail = "",
|
|
163
|
+
timedOut = false;
|
|
164
|
+
try {
|
|
165
|
+
const isPytest = adapter.language === "python";
|
|
166
|
+
if (isPytest && !env.TRACEYARD_PYTEST_PYTHON)
|
|
167
|
+
return blocked("Install this package's Pytest dependencies before rerunning.", command);
|
|
168
|
+
const runnerArgs = adapter.args({ testArgument, output, plan });
|
|
169
|
+
const invocation = isPytest
|
|
170
|
+
? { program: env.TRACEYARD_PYTEST_PYTHON, args: runnerArgs }
|
|
171
|
+
: scriptCommand(
|
|
172
|
+
options.packageManager ?? (await detectPackageManager(root, directory)),
|
|
173
|
+
command.script,
|
|
174
|
+
runnerArgs,
|
|
175
|
+
);
|
|
176
|
+
let evidenceError;
|
|
177
|
+
const exitCode = await new Promise((done, reject) => {
|
|
178
|
+
const childEnv = adapter.environment ? adapter.environment(env) : env;
|
|
179
|
+
const child = spawn(invocation.program, invocation.args, {
|
|
180
|
+
cwd: directory,
|
|
181
|
+
env: sandbox ? { ...childEnv, HOME: sandbox.home } : childEnv,
|
|
182
|
+
...(sandbox ? { uid: sandbox.uid, gid: sandbox.gid } : {}),
|
|
183
|
+
shell: !isPytest && process.platform === "win32",
|
|
184
|
+
detached: process.platform !== "win32",
|
|
185
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
186
|
+
});
|
|
187
|
+
const capture = (chunk) => {
|
|
188
|
+
tail = (tail + chunk.toString()).slice(-16000);
|
|
189
|
+
};
|
|
190
|
+
child.stdout.on("data", capture);
|
|
191
|
+
child.stderr.on("data", capture);
|
|
192
|
+
const timer = setTimeout(() => {
|
|
193
|
+
timedOut = true;
|
|
194
|
+
try {
|
|
195
|
+
if (process.platform === "win32") child.kill("SIGKILL");
|
|
196
|
+
else process.kill(-child.pid, "SIGKILL");
|
|
197
|
+
} catch {
|
|
198
|
+
/* Already stopped. */
|
|
199
|
+
}
|
|
200
|
+
}, plan.timeoutMs);
|
|
201
|
+
child.on("error", (error) => {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
reject(error);
|
|
204
|
+
});
|
|
205
|
+
child.on("close", (code) => {
|
|
206
|
+
clearTimeout(timer);
|
|
207
|
+
if (process.platform !== "win32")
|
|
208
|
+
try {
|
|
209
|
+
process.kill(-child.pid, "SIGTERM");
|
|
210
|
+
} catch {
|
|
211
|
+
/* No children remain. */
|
|
212
|
+
}
|
|
213
|
+
done(code);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
let result;
|
|
217
|
+
const retainedOutput = sanitizeDiagnostic(tail.slice(-4000), 4000);
|
|
218
|
+
try {
|
|
219
|
+
// The reporter output is written by the test process; never follow a link
|
|
220
|
+
// it planted in place of the file.
|
|
221
|
+
const text = await readFile(output, {
|
|
222
|
+
encoding: "utf8",
|
|
223
|
+
flag: process.platform === "win32" ? "r" : fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,
|
|
224
|
+
});
|
|
225
|
+
if (Buffer.byteLength(text) > 8_000_000)
|
|
226
|
+
return blocked("The structured reporter exceeded the supported artifact size.");
|
|
227
|
+
if (timedOut)
|
|
228
|
+
return {
|
|
229
|
+
...blocked("The focused test exceeded its time budget.", command),
|
|
230
|
+
output: retainedOutput,
|
|
231
|
+
};
|
|
232
|
+
const data = JSON.parse(text);
|
|
233
|
+
try {
|
|
234
|
+
result = adapter.normalize(data, exitCode, { root, directory, file, command });
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (isPytest) evidenceError = error.message;
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
if (result.blocked) return { ...blocked(result.blocked, command), output: retainedOutput };
|
|
240
|
+
} catch {
|
|
241
|
+
return {
|
|
242
|
+
...blocked(
|
|
243
|
+
timedOut
|
|
244
|
+
? "The focused test exceeded its time budget."
|
|
245
|
+
: (evidenceError ?? summarizeCommandFailure(tail, "test", exitCode ?? "interrupted")),
|
|
246
|
+
command,
|
|
247
|
+
),
|
|
248
|
+
output: retainedOutput,
|
|
249
|
+
exitCode,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
...result,
|
|
254
|
+
output: retainedOutput,
|
|
255
|
+
durationMs: Date.now() - started,
|
|
256
|
+
exitCode,
|
|
257
|
+
nodeVersion: process.version,
|
|
258
|
+
command,
|
|
259
|
+
...(runnerConfig ? { runnerConfig } : {}),
|
|
260
|
+
};
|
|
261
|
+
} finally {
|
|
262
|
+
await rm(temporary, { recursive: true, force: true });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
export async function runInvestigationPlan(workspace, index, plan, env, options = {}) {
|
|
266
|
+
const started = Date.now(),
|
|
267
|
+
selection = selectTest(index, plan.question, plan.testPath);
|
|
268
|
+
if (!selection.test || isPytestFile(selection.test.path))
|
|
269
|
+
return runTargetedTest(workspace, index, plan, env, options);
|
|
270
|
+
const related = [
|
|
271
|
+
...new Set(
|
|
272
|
+
(plan.changedFiles ?? []).flatMap((file) => relatedTests(index, file).map((t) => t.path)),
|
|
273
|
+
),
|
|
274
|
+
].filter((path) => path !== selection.test.path && !isPytestFile(path));
|
|
275
|
+
const selected = [
|
|
276
|
+
selection.test.path,
|
|
277
|
+
...related.slice(0, (plan.replayRecording ? 1 : (plan.maxTestFiles ?? 1)) - 1),
|
|
278
|
+
];
|
|
279
|
+
const results = [];
|
|
280
|
+
for (const path of selected) {
|
|
281
|
+
const remaining = plan.timeoutMs - (Date.now() - started);
|
|
282
|
+
if (remaining < 1000) break;
|
|
283
|
+
const result = await runTargetedTest(
|
|
284
|
+
workspace,
|
|
285
|
+
index,
|
|
286
|
+
{ ...plan, testPath: path, timeoutMs: remaining },
|
|
287
|
+
env,
|
|
288
|
+
options,
|
|
289
|
+
);
|
|
290
|
+
results.push(result);
|
|
291
|
+
if (result.status !== "SUCCEEDED") break;
|
|
292
|
+
}
|
|
293
|
+
const primary = results[0];
|
|
294
|
+
if (!primary) return runTargetedTest(workspace, index, plan, env, options);
|
|
295
|
+
const failed = results.some((r) => r.status === "FAILED"),
|
|
296
|
+
blocked = results.some((r) => r.status === "BLOCKED");
|
|
297
|
+
const counts = results.reduce(
|
|
298
|
+
(sum, r) => ({
|
|
299
|
+
passed: sum.passed + r.counts.passed,
|
|
300
|
+
failed: sum.failed + r.counts.failed,
|
|
301
|
+
skipped: sum.skipped + r.counts.skipped,
|
|
302
|
+
}),
|
|
303
|
+
{ passed: 0, failed: 0, skipped: 0 },
|
|
304
|
+
);
|
|
305
|
+
const failures = results.flatMap((r) => r.failures),
|
|
306
|
+
omittedTests = 1 + related.length - results.length;
|
|
307
|
+
return {
|
|
308
|
+
...primary,
|
|
309
|
+
status: failed ? "FAILED" : blocked ? "BLOCKED" : "SUCCEEDED",
|
|
310
|
+
counts,
|
|
311
|
+
failures: failures.slice(0, 8),
|
|
312
|
+
exitCode: failed ? 1 : blocked ? null : 0,
|
|
313
|
+
truncated: results.some((r) => r.truncated) || failures.length > 8,
|
|
314
|
+
durationMs: Date.now() - started,
|
|
315
|
+
message:
|
|
316
|
+
`${counts.passed} passed, ${counts.failed} failed across ${results.length} test file(s). ${omittedTests ? `${omittedTests} related test file(s) remain outside this attempt.` : "Selected coverage completed."} ${results.find((r) => r.status !== "SUCCEEDED")?.message ?? ""}`.slice(
|
|
317
|
+
0,
|
|
318
|
+
2000,
|
|
319
|
+
),
|
|
320
|
+
checks: results.map((r) => ({
|
|
321
|
+
testPath: r.command.testPath ?? selection.test.path,
|
|
322
|
+
status: r.status,
|
|
323
|
+
})),
|
|
324
|
+
coverage: { omittedTests },
|
|
325
|
+
};
|
|
326
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
// Files whose edits can make a test pass without fixing the code: the tests
|
|
6
|
+
// themselves, fixtures, snapshots, mocks, setup files and runner configuration.
|
|
7
|
+
// The CLI and the hosted verification both use these rules, so a fix commit is
|
|
8
|
+
// judged the same way wherever it is verified.
|
|
9
|
+
|
|
10
|
+
const javascriptTestInput = [
|
|
11
|
+
/\.(?:test|spec|fixture)\.[cm]?[jt]sx?$/i,
|
|
12
|
+
/(?:^|\/)(?:__(?:tests|fixtures|snapshots|mocks)__|tests?|fixtures?)\//i,
|
|
13
|
+
/\.snap$/i,
|
|
14
|
+
// Runner configuration and workspaces.
|
|
15
|
+
/(?:^|\/)(?:vitest|vite|jest)\.(?:config|workspace)(?:\.[^/]+)?\.(?:[cm]?[jt]s|json)$/i,
|
|
16
|
+
/(?:^|\/)vitest\.(?:projects?)\.[cm]?[jt]s$/i,
|
|
17
|
+
// Setup files that run before every test.
|
|
18
|
+
/(?:^|\/)(?:setup-?tests?|tests?-?setup|(?:vitest|jest)[.-]setup(?:[.-][^/]+)?)\.[cm]?[jt]sx?$/i,
|
|
19
|
+
/\.setup\.[cm]?[jt]sx?$/i,
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
// The config names are every file Pytest reads settings from, including the
|
|
23
|
+
// hidden and TOML forms. Any of them can redirect imports with `pythonpath`.
|
|
24
|
+
const pytestTestInput =
|
|
25
|
+
/(?:^|\/)(?:test_[^/]+\.py|[^/]+_test\.py|conftest\.py|\.?pytest\.(?:ini|toml)|pyproject\.toml|setup\.cfg|tox\.ini|requirements[^/]*\.txt)$/;
|
|
26
|
+
|
|
27
|
+
/** True for JavaScript test inputs: tests, fixtures, snapshots, mocks, setup and runner config. */
|
|
28
|
+
export const isJavaScriptTestInput = (path) => javascriptTestInput.some((rule) => rule.test(path));
|
|
29
|
+
|
|
30
|
+
/** True for Pytest test inputs: test modules, conftest and Pytest or dependency configuration. */
|
|
31
|
+
export const isPytestInput = (path) => pytestTestInput.test(path);
|
|
32
|
+
|
|
33
|
+
/** True when a path is a test input for any supported runner. */
|
|
34
|
+
export const isTestInput = (path) => isJavaScriptTestInput(path) || isPytestInput(path);
|
|
35
|
+
|
|
36
|
+
/** The `--config`/`-c` file a runner script names, when it names one. */
|
|
37
|
+
export function scriptConfigPath(command) {
|
|
38
|
+
const words = String(command).trim().split(/\s+/);
|
|
39
|
+
for (let i = 0; i < words.length; i++) {
|
|
40
|
+
const word = words[i].replace(/^["']|["']$/g, "");
|
|
41
|
+
const inline = word.match(/^(?:--config|-c)=(.+)$/);
|
|
42
|
+
if (inline) return inline[1].replace(/^["']|["']$/g, "");
|
|
43
|
+
if ((word === "--config" || word === "-c") && words[i + 1])
|
|
44
|
+
return words[i + 1].replace(/^["']|["']$/g, "");
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A digest of the runner configuration a JavaScript run used: the package
|
|
51
|
+
* script that ran, the package.json `jest` key, and the contents of a config
|
|
52
|
+
* file the script names. Two runs with different digests did not run the test
|
|
53
|
+
* the same way, even when no file matched the test-input rules.
|
|
54
|
+
*/
|
|
55
|
+
export async function runnerConfigDigest({ root, directory, pkg, script }) {
|
|
56
|
+
const command = String(pkg.scripts?.[script] ?? "");
|
|
57
|
+
const configPath = scriptConfigPath(command);
|
|
58
|
+
let config = null;
|
|
59
|
+
if (configPath) {
|
|
60
|
+
try {
|
|
61
|
+
// Compare resolved paths: on Windows a temporary root may be a short 8.3
|
|
62
|
+
// name while realpath returns the long one.
|
|
63
|
+
const file = await realpath(resolve(directory, configPath));
|
|
64
|
+
const inside = relative(await realpath(root), file);
|
|
65
|
+
config =
|
|
66
|
+
inside.startsWith("..") || isAbsolute(inside)
|
|
67
|
+
? "outside-repository"
|
|
68
|
+
: createHash("sha256")
|
|
69
|
+
.update(await readFile(file))
|
|
70
|
+
.digest("hex");
|
|
71
|
+
} catch {
|
|
72
|
+
config = "missing";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return createHash("sha256")
|
|
76
|
+
.update(JSON.stringify({ script, command, jest: pkg.jest ?? null, configPath, config }))
|
|
77
|
+
.digest("hex");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The package.json a pair of runs disagrees about. Returns `changed` with the
|
|
82
|
+
* package.json path when both runs recorded different runner configurations.
|
|
83
|
+
* When only one run recorded one, `unknown` is true and a package.json listed
|
|
84
|
+
* in `changedFiles` counts as changed, since it can't be ruled out.
|
|
85
|
+
*/
|
|
86
|
+
export function runnerConfigChange(baseline, candidate, directory = ".", changedFiles = []) {
|
|
87
|
+
if (!baseline || !candidate) return { changed: [], unknown: false };
|
|
88
|
+
const dir = String(directory || ".").replace(/\/+$/, "");
|
|
89
|
+
const manifest = dir === "." || !dir ? "package.json" : dir + "/package.json";
|
|
90
|
+
if (!baseline.runnerConfig || !candidate.runnerConfig) {
|
|
91
|
+
const unknown = !!(baseline.runnerConfig || candidate.runnerConfig);
|
|
92
|
+
// Without both digests, a changed package.json can't be ruled out.
|
|
93
|
+
return { changed: unknown && changedFiles.includes(manifest) ? [manifest] : [], unknown };
|
|
94
|
+
}
|
|
95
|
+
if (baseline.runnerConfig === candidate.runnerConfig) return { changed: [], unknown: false };
|
|
96
|
+
return { changed: [manifest], unknown: false };
|
|
97
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { isAbsolute, relative } from "node:path";
|
|
2
|
+
export function sanitizeDiagnostic(value, max = 1500) {
|
|
3
|
+
return String(value)
|
|
4
|
+
.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer [redacted]")
|
|
5
|
+
.replace(/(?:sk-|tyk_|tyr_)[A-Za-z0-9_-]{16,}/g, "[redacted]")
|
|
6
|
+
.replace(/((?:api[_-]?key|password|secret)\s*[=:]\s*)[^\s,;]+/gi, "$1[redacted]")
|
|
7
|
+
.slice(0, max);
|
|
8
|
+
}
|
|
9
|
+
export function normalizeVitestReport(data, exitCode, root = "") {
|
|
10
|
+
const failures = [];
|
|
11
|
+
let omitted = false;
|
|
12
|
+
for (const file of data.testResults ?? []) {
|
|
13
|
+
const path = String(file.name ?? "");
|
|
14
|
+
const fileName = (root && isAbsolute(path) ? relative(root, path) : path).split("\\").join("/");
|
|
15
|
+
for (const test of file.assertionResults ?? [])
|
|
16
|
+
if (test.status === "failed") {
|
|
17
|
+
if (failures.length === 8) {
|
|
18
|
+
omitted = true;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const raw = (test.failureMessages ?? []).join("\n");
|
|
22
|
+
if (raw.length > 1500) omitted = true;
|
|
23
|
+
failures.push({
|
|
24
|
+
file: fileName.slice(0, 240),
|
|
25
|
+
name: sanitizeDiagnostic(test.fullName ?? test.title ?? "Unnamed assertion", 250),
|
|
26
|
+
message: sanitizeDiagnostic(raw || "Assertion failed without a retained message."),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
if (
|
|
30
|
+
file.status === "failed" &&
|
|
31
|
+
!file.assertionResults?.some((t) => t.status === "failed") &&
|
|
32
|
+
failures.length < 8
|
|
33
|
+
)
|
|
34
|
+
failures.push({
|
|
35
|
+
file: fileName.slice(0, 240),
|
|
36
|
+
name: "Suite initialization",
|
|
37
|
+
message: sanitizeDiagnostic(file.message ?? "The suite could not initialize."),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const counts = {
|
|
41
|
+
passed: Math.max(0, Number(data.numPassedTests) || 0),
|
|
42
|
+
failed: Math.max(0, Number(data.numFailedTests) || 0),
|
|
43
|
+
skipped: Math.max(0, Number(data.numPendingTests) || 0),
|
|
44
|
+
};
|
|
45
|
+
const status =
|
|
46
|
+
exitCode === 0 && counts.passed > 0 && !counts.failed && !failures.length
|
|
47
|
+
? "SUCCEEDED"
|
|
48
|
+
: exitCode === 0
|
|
49
|
+
? "BLOCKED"
|
|
50
|
+
: "FAILED";
|
|
51
|
+
const text = failures.map((f) => f.message).join("\n");
|
|
52
|
+
const configuration = /No Groq API keys configured|GROQ_API_KEY_PRIMARY is missing/.test(text)
|
|
53
|
+
? " A Groq configuration guard stopped execution; check whether a mocked suite reaches its provider mock before requesting real credentials."
|
|
54
|
+
: /supabaseUrl is required|supabaseKey is required/.test(text)
|
|
55
|
+
? " Supabase initialized before the test mock; inspect fixture initialization."
|
|
56
|
+
: "";
|
|
57
|
+
return {
|
|
58
|
+
status,
|
|
59
|
+
counts,
|
|
60
|
+
failures,
|
|
61
|
+
truncated: omitted,
|
|
62
|
+
message: `${counts.passed} passed, ${counts.failed} failed, ${counts.skipped} skipped.${configuration}${status === "BLOCKED" ? " No passing executed test establishes success." : ""}`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
|
|
7
|
+
const run = promisify(execFile);
|
|
8
|
+
const shaPattern = /^[0-9a-f]{7,64}$/i;
|
|
9
|
+
|
|
10
|
+
async function git(cwd, args, options = {}) {
|
|
11
|
+
const { stdout } = await run("git", args, {
|
|
12
|
+
cwd,
|
|
13
|
+
timeout: options.timeoutMs ?? 15000,
|
|
14
|
+
env: options.env ?? process.env,
|
|
15
|
+
maxBuffer: 1024 * 1024,
|
|
16
|
+
});
|
|
17
|
+
return stdout.trim();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Build an environment that authenticates GitHub fetches without writing the token to disk. */
|
|
21
|
+
export function githubFetchEnv(token, env = process.env) {
|
|
22
|
+
if (!token) return env;
|
|
23
|
+
return {
|
|
24
|
+
...env,
|
|
25
|
+
GIT_CONFIG_COUNT: "1",
|
|
26
|
+
GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader",
|
|
27
|
+
GIT_CONFIG_VALUE_0:
|
|
28
|
+
"AUTHORIZATION: basic " + Buffer.from("x-access-token:" + token).toString("base64"),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Make sure `commit` exists locally. Fetching is opt-in so local runs never
|
|
34
|
+
* touch the network unless asked to.
|
|
35
|
+
*/
|
|
36
|
+
export async function ensureCommit(repo, commit, { fetch = false, token } = {}) {
|
|
37
|
+
if (!shaPattern.test(commit)) throw Error("Use a full or abbreviated commit SHA.");
|
|
38
|
+
try {
|
|
39
|
+
return await git(repo, ["rev-parse", "--verify", "--quiet", commit + "^{commit}"]);
|
|
40
|
+
} catch {
|
|
41
|
+
if (!fetch)
|
|
42
|
+
throw Error(
|
|
43
|
+
`Commit ${commit} is not in this clone. Run \`git fetch origin ${commit}\` or allow fetching.`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
await git(repo, ["fetch", "--no-tags", "origin", commit], { env: githubFetchEnv(token) });
|
|
48
|
+
return await git(repo, ["rev-parse", "--verify", "--quiet", commit + "^{commit}"]);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
throw Error(
|
|
51
|
+
"Git could not fetch the selected commit. Confirm it is accessible from the origin remote.",
|
|
52
|
+
{ cause: error },
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Check out `commit` into a detached, throwaway worktree. The developer's own
|
|
59
|
+
* working tree and index are never touched. Always call `remove()`.
|
|
60
|
+
*/
|
|
61
|
+
export async function checkoutCommit(repo, commit, options = {}) {
|
|
62
|
+
const sha = await ensureCommit(repo, commit, options);
|
|
63
|
+
const parent = await mkdtemp(join(options.tmpdir ?? tmpdir(), "traceyard-worktree-"));
|
|
64
|
+
const path = join(parent, "checkout");
|
|
65
|
+
try {
|
|
66
|
+
await git(repo, ["worktree", "add", "--detach", "--force", path, sha], { timeoutMs: 120000 });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
await rm(parent, { recursive: true, force: true });
|
|
69
|
+
throw Error("Git could not create a checkout for " + sha.slice(0, 12) + ": " + error.message, {
|
|
70
|
+
cause: error,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
let removed = false;
|
|
74
|
+
return {
|
|
75
|
+
path,
|
|
76
|
+
sha,
|
|
77
|
+
async remove() {
|
|
78
|
+
if (removed) return;
|
|
79
|
+
removed = true;
|
|
80
|
+
await git(repo, ["worktree", "remove", "--force", path]).catch(() => {});
|
|
81
|
+
await rm(parent, { recursive: true, force: true });
|
|
82
|
+
await git(repo, ["worktree", "prune"]).catch(() => {});
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Run `fn(checkout)` against an exact commit and always clean up afterwards. */
|
|
88
|
+
export async function withCommit(repo, commit, fn, options) {
|
|
89
|
+
const checkout = await checkoutCommit(repo, commit, options);
|
|
90
|
+
try {
|
|
91
|
+
return await fn(checkout);
|
|
92
|
+
} finally {
|
|
93
|
+
await checkout.remove();
|
|
94
|
+
}
|
|
95
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "traceyard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Reproduce a failing test at the exact commit, check a fix, and record a receipt that it passed. No account, no server.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"traceyard": "lib/cli/bin/traceyard.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"lib",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22.12.0"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@babel/parser": "^7.29.14",
|
|
20
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
21
|
+
"zod": "^4.6.7"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"testing",
|
|
25
|
+
"ci",
|
|
26
|
+
"reproduce",
|
|
27
|
+
"flaky-tests",
|
|
28
|
+
"mcp",
|
|
29
|
+
"coding-agents",
|
|
30
|
+
"vitest",
|
|
31
|
+
"jest",
|
|
32
|
+
"pytest"
|
|
33
|
+
],
|
|
34
|
+
"homepage": "https://github.com/fysaio/traceyard/blob/main/docs/CLI.md",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/fysaio/traceyard.git",
|
|
38
|
+
"directory": "packages/cli"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/fysaio/traceyard/issues"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"provenance": true
|
|
46
|
+
}
|
|
47
|
+
}
|