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,915 @@
|
|
|
1
|
+
import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { matchTestPath } from "../../core/src/ci-link.mjs";
|
|
5
|
+
import { validPytestCase } from "../../core/src/pytest.mjs";
|
|
6
|
+
import { ensureCommit } from "../../core/src/worktree.mjs";
|
|
7
|
+
import { BlockedError, UsageError } from "./errors.mjs";
|
|
8
|
+
import {
|
|
9
|
+
changedFiles,
|
|
10
|
+
changedThroughLinks,
|
|
11
|
+
filesAtCommit,
|
|
12
|
+
githubRepository,
|
|
13
|
+
headCommit,
|
|
14
|
+
onFirstParentLine,
|
|
15
|
+
showFile,
|
|
16
|
+
hasUncommittedChanges,
|
|
17
|
+
repositoryRoot,
|
|
18
|
+
resolveCommit,
|
|
19
|
+
worktreeChanged,
|
|
20
|
+
worktreeSnapshot,
|
|
21
|
+
} from "./git.mjs";
|
|
22
|
+
import { newRequestId, repositoryId, singleRunEnvelope, verifyEnvelope } from "./evidence.mjs";
|
|
23
|
+
import { githubAuth, resolveActionsLink } from "./github.mjs";
|
|
24
|
+
import { listReceipts, readReceipt, receiptMarkdown, writeReceipt } from "./receipt.mjs";
|
|
25
|
+
import { cacheDirectory, listEvidence, readEvidence, runTest } from "./run.mjs";
|
|
26
|
+
import { cleanOutput, compactFailure } from "./compact.mjs";
|
|
27
|
+
import {
|
|
28
|
+
checkVerdict,
|
|
29
|
+
EXIT,
|
|
30
|
+
exitCodeFor,
|
|
31
|
+
guardRecheckVerdict,
|
|
32
|
+
guardVerdict,
|
|
33
|
+
receiptTest,
|
|
34
|
+
reproVerdict,
|
|
35
|
+
verifyVerdict,
|
|
36
|
+
} from "./verdicts.mjs";
|
|
37
|
+
import { VERSION } from "./version.mjs";
|
|
38
|
+
|
|
39
|
+
const HELP = `traceyard ${VERSION}: prove a failing test is fixed, on your machine.
|
|
40
|
+
|
|
41
|
+
Usage:
|
|
42
|
+
traceyard repro [test] [--at <sha> | --from <actions-url>] Rerun the failing test at the exact commit
|
|
43
|
+
traceyard check [test] Run the test against your working tree
|
|
44
|
+
traceyard verify [test] [--before <sha>] [--after <sha>] Failed before, passes now, test untouched
|
|
45
|
+
traceyard guard [receipt] [--before <sha>] Rerun the receipt's test; exit 0 if it is still fixed at HEAD
|
|
46
|
+
traceyard explain [evidence] [--failure <n>] The failure, where it happened, and the source there
|
|
47
|
+
traceyard inspect [evidence] [--offset <n>] [--limit <n>] Recent runs, or one run's full log in slices
|
|
48
|
+
traceyard receipt [id] Show the latest (or a given) receipt
|
|
49
|
+
traceyard mcp Serve these tools to coding agents over MCP (stdio)
|
|
50
|
+
|
|
51
|
+
Options:
|
|
52
|
+
--case <name> Pytest case to run, e.g. TestCart::test_total
|
|
53
|
+
--json Print one JSON object on stdout (see docs/CLI.md)
|
|
54
|
+
--log Include the last lines of test output
|
|
55
|
+
--fetch Allow git to fetch a commit that isn't in this clone
|
|
56
|
+
--install Install dependencies in your working tree if they're missing (check)
|
|
57
|
+
--fresh Ignore cached results for the same commit and test
|
|
58
|
+
--timeout <sec> Time limit for one test run (default 180)
|
|
59
|
+
--repo <dir> Repository to use (default: current directory)
|
|
60
|
+
-h, --help Show this help
|
|
61
|
+
-v, --version Show the version
|
|
62
|
+
|
|
63
|
+
Exit codes: 0 reproduced/passed/fixed, 1 failing/unverified, 2 needs review, 3 blocked, 64 usage error.`;
|
|
64
|
+
|
|
65
|
+
const options = {
|
|
66
|
+
at: { type: "string" },
|
|
67
|
+
from: { type: "string" },
|
|
68
|
+
before: { type: "string" },
|
|
69
|
+
after: { type: "string" },
|
|
70
|
+
case: { type: "string" },
|
|
71
|
+
failure: { type: "string" },
|
|
72
|
+
offset: { type: "string" },
|
|
73
|
+
limit: { type: "string" },
|
|
74
|
+
json: { type: "boolean", default: false },
|
|
75
|
+
log: { type: "boolean", default: false },
|
|
76
|
+
fetch: { type: "boolean", default: false },
|
|
77
|
+
install: { type: "boolean", default: false },
|
|
78
|
+
fresh: { type: "boolean", default: false },
|
|
79
|
+
timeout: { type: "string" },
|
|
80
|
+
repo: { type: "string" },
|
|
81
|
+
help: { type: "boolean", short: "h", default: false },
|
|
82
|
+
version: { type: "boolean", short: "v", default: false },
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const defaults = { json: false, log: false, fetch: false, install: false, fresh: false };
|
|
86
|
+
|
|
87
|
+
/** Flags that only make sense for some commands. Everything else applies everywhere. */
|
|
88
|
+
const allowed = {
|
|
89
|
+
repro: ["at", "from", "case"],
|
|
90
|
+
check: ["case"],
|
|
91
|
+
verify: ["before", "after", "case"],
|
|
92
|
+
guard: ["before"],
|
|
93
|
+
explain: ["failure"],
|
|
94
|
+
inspect: ["offset", "limit"],
|
|
95
|
+
receipt: [],
|
|
96
|
+
};
|
|
97
|
+
const commandFlags = ["at", "from", "before", "after", "case", "failure", "offset", "limit"];
|
|
98
|
+
|
|
99
|
+
const MAX_FAILURES = 5;
|
|
100
|
+
const MAX_MESSAGE = 600;
|
|
101
|
+
const MAX_OUTPUT = 4000;
|
|
102
|
+
const SLICE_DEFAULT = 3000;
|
|
103
|
+
const SLICE_MAX = 4000;
|
|
104
|
+
|
|
105
|
+
/** Agent-facing run shape: bounded so a whole result stays well under 1,500 tokens. */
|
|
106
|
+
function publicRun(role, run, { log }, root) {
|
|
107
|
+
const compacted = run.failures.map((f) => ({ ...f, message: compactFailure(f.message, root) }));
|
|
108
|
+
const failures = compacted
|
|
109
|
+
.slice(0, MAX_FAILURES)
|
|
110
|
+
.map(({ file, name, message }) => ({ file, name, message: message.slice(0, MAX_MESSAGE) }));
|
|
111
|
+
return {
|
|
112
|
+
role,
|
|
113
|
+
commit: run.commit,
|
|
114
|
+
workingTree: run.commit === null,
|
|
115
|
+
status: run.status,
|
|
116
|
+
counts: run.counts,
|
|
117
|
+
failures,
|
|
118
|
+
truncated:
|
|
119
|
+
run.truncated ||
|
|
120
|
+
run.failures.length > MAX_FAILURES ||
|
|
121
|
+
compacted.some((f) => f.message.length > MAX_MESSAGE),
|
|
122
|
+
durationMs: run.durationMs,
|
|
123
|
+
cached: run.cached,
|
|
124
|
+
dependencies: run.dependencies,
|
|
125
|
+
evidenceId: run.evidenceId ?? null,
|
|
126
|
+
message: cleanOutput(run.message, root).slice(0, MAX_MESSAGE),
|
|
127
|
+
...(log ? { output: cleanOutput(run.output, root).slice(-MAX_OUTPUT) } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function stateDirectory(root) {
|
|
132
|
+
const dir = join(root, ".traceyard");
|
|
133
|
+
await mkdir(dir, { recursive: true });
|
|
134
|
+
// Keep local evidence out of commits without touching the project's .gitignore.
|
|
135
|
+
await writeFile(join(dir, ".gitignore"), "*\n");
|
|
136
|
+
return dir;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function lastRepro(stateDir) {
|
|
140
|
+
try {
|
|
141
|
+
return JSON.parse(await readFile(join(stateDir, "last-repro.json"), "utf8"));
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function testArgument(value, cwd, root) {
|
|
148
|
+
if (!value) return null;
|
|
149
|
+
const path = relative(root, resolve(cwd, value)).split("\\").join("/");
|
|
150
|
+
if (!path || path.startsWith("..") || isAbsolute(path))
|
|
151
|
+
throw new UsageError(`The test file ${value} is outside this repository.`);
|
|
152
|
+
return path;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function commitArgument(root, ref, flag, fetch) {
|
|
156
|
+
if (!ref) return null;
|
|
157
|
+
if (/^[0-9a-f]{40}$/i.test(ref)) return ref.toLowerCase();
|
|
158
|
+
const sha = await resolveCommit(root, ref);
|
|
159
|
+
if (sha) return sha;
|
|
160
|
+
if (/^[0-9a-f]{7,39}$/i.test(ref) && fetch)
|
|
161
|
+
throw new UsageError(`Pass the full 40-character SHA for ${flag} so Traceyard can fetch it.`);
|
|
162
|
+
throw new UsageError(
|
|
163
|
+
`${flag} ${ref} is not a commit in this clone.` +
|
|
164
|
+
(/^[0-9a-f]{7,40}$/i.test(ref) ? " Pass --fetch to download it." : ""),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function text(result) {
|
|
169
|
+
if (result.command === "receipt" && result.receipt?.markdown)
|
|
170
|
+
return [result.receipt.markdown.trimEnd(), ...result.warnings.map((w) => "Note: " + w)].join(
|
|
171
|
+
"\n",
|
|
172
|
+
);
|
|
173
|
+
const icon = { 0: "✔", 1: "✖", 2: "!", 3: "■" }[result.exitCode] ?? "✖";
|
|
174
|
+
const lines = [`${icon} ${result.verdict}: ${result.summary}`];
|
|
175
|
+
for (const run of result.runs) {
|
|
176
|
+
const where = run.commit ? run.commit : "working tree";
|
|
177
|
+
const counts = `${run.counts.passed} passed, ${run.counts.failed} failed, ${run.counts.skipped} skipped`;
|
|
178
|
+
lines.push(
|
|
179
|
+
` ${run.role.padEnd(9)} ${where} ${run.status.toLowerCase()} (${counts}, ${(run.durationMs / 1000).toFixed(1)}s${run.cached ? ", cached" : ""})`,
|
|
180
|
+
);
|
|
181
|
+
for (const failure of run.failures.slice(0, 3)) {
|
|
182
|
+
lines.push(` - ${failure.name}`);
|
|
183
|
+
const messageLines = failure.message.split("\n").filter((l) => l.trim());
|
|
184
|
+
// Prefer the assertion line (Pytest prints it after "E "), else the first line.
|
|
185
|
+
const first = messageLines.find((l) => /^E\s/.test(l.trim())) ?? messageLines[0];
|
|
186
|
+
if (first) lines.push(` ${first.trim().slice(0, 200)}`);
|
|
187
|
+
}
|
|
188
|
+
if (run.output) lines.push("", run.output.trimEnd(), "");
|
|
189
|
+
}
|
|
190
|
+
if (result.explanation) {
|
|
191
|
+
const { failure, location, source } = result.explanation;
|
|
192
|
+
lines.push(` Failure ${failure.index} of ${failure.of}: ${failure.name}`);
|
|
193
|
+
if (location) lines.push(` At ${location.path}:${location.line}`);
|
|
194
|
+
lines.push("", failure.message.trimEnd());
|
|
195
|
+
if (source) lines.push("", source.text);
|
|
196
|
+
lines.push("");
|
|
197
|
+
}
|
|
198
|
+
if (result.items)
|
|
199
|
+
for (const item of result.items)
|
|
200
|
+
lines.push(
|
|
201
|
+
` ${item.kind.padEnd(8)} ${item.id} ${String(item.status).toLowerCase()} ${item.test ?? ""}${item.commit ? " @ " + item.commit.slice(0, 12) : ""}`,
|
|
202
|
+
);
|
|
203
|
+
if (result.evidence) lines.push("", result.evidence.text.trimEnd(), "");
|
|
204
|
+
if (result.changedTests?.length)
|
|
205
|
+
lines.push(` Test files changed: ${result.changedTests.join(", ")}`);
|
|
206
|
+
if (result.receipt) lines.push(` Receipt: ${result.receipt.markdownPath}`);
|
|
207
|
+
for (const warning of result.warnings) lines.push(` Note: ${warning}`);
|
|
208
|
+
lines.push(`Next: ${result.next}`);
|
|
209
|
+
return lines.join("\n");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Entry point. Returns the process exit code. `io` lets tests capture output;
|
|
214
|
+
* `env` and `fetcher` let tests run without real GitHub access.
|
|
215
|
+
*/
|
|
216
|
+
export async function main(argv, io = defaultIo(), { env = process.env, fetcher } = {}) {
|
|
217
|
+
let parsed;
|
|
218
|
+
try {
|
|
219
|
+
parsed = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
|
|
220
|
+
} catch (error) {
|
|
221
|
+
return emit(usageResult(error.message, null), argv.includes("--json"), io);
|
|
222
|
+
}
|
|
223
|
+
const { values, positionals } = parsed;
|
|
224
|
+
if (values.version) {
|
|
225
|
+
io.stdout(VERSION);
|
|
226
|
+
return EXIT.OK;
|
|
227
|
+
}
|
|
228
|
+
const [command, ...rest] = positionals;
|
|
229
|
+
if (values.help || !command || command === "help") {
|
|
230
|
+
io.stdout(HELP);
|
|
231
|
+
return command || values.help ? EXIT.OK : EXIT.USAGE;
|
|
232
|
+
}
|
|
233
|
+
if (command === "mcp") {
|
|
234
|
+
if (rest.length) return emit(usageResult("traceyard mcp takes no arguments.", null), false, io);
|
|
235
|
+
const { serveMcp } = await import("./mcp.mjs");
|
|
236
|
+
await serveMcp({ repo: values.repo, env, fetcher });
|
|
237
|
+
return EXIT.OK;
|
|
238
|
+
}
|
|
239
|
+
if (rest.length > 1)
|
|
240
|
+
return emit(
|
|
241
|
+
usageResult("Pass one test file at a time.", knownCommand(command)),
|
|
242
|
+
values.json,
|
|
243
|
+
io,
|
|
244
|
+
);
|
|
245
|
+
const progress = values.json ? undefined : (message) => io.stderr(message);
|
|
246
|
+
const result = await execute(command, values, rest[0], { env, fetcher, progress });
|
|
247
|
+
if (result.exitCode === EXIT.INTERNAL) {
|
|
248
|
+
io.stderr(`traceyard: unexpected error: ${result.summary}`);
|
|
249
|
+
return EXIT.INTERNAL;
|
|
250
|
+
}
|
|
251
|
+
return emit(result, values.json, io);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const knownCommand = (command) => (command in allowed ? command : null);
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Run one command and return its result object. Shared by the command line and
|
|
258
|
+
* the MCP server, so both always agree. Never throws: usage problems become
|
|
259
|
+
* ERROR, unexpected failures become exit code 70.
|
|
260
|
+
*/
|
|
261
|
+
export async function execute(
|
|
262
|
+
command,
|
|
263
|
+
input = {},
|
|
264
|
+
testInput,
|
|
265
|
+
{ env = process.env, fetcher, progress } = {},
|
|
266
|
+
) {
|
|
267
|
+
const values = { ...defaults, ...input };
|
|
268
|
+
try {
|
|
269
|
+
if (!(command in allowed))
|
|
270
|
+
throw new UsageError(`Unknown command "${command}". Run traceyard --help.`);
|
|
271
|
+
for (const flag of commandFlags)
|
|
272
|
+
if (values[flag] !== undefined && !allowed[command].includes(flag))
|
|
273
|
+
throw new UsageError(`--${flag} doesn't apply to traceyard ${command}.`);
|
|
274
|
+
if (values.case !== undefined && !validPytestCase(values.case))
|
|
275
|
+
throw new UsageError(
|
|
276
|
+
"--case takes a Pytest case like TestCart::test_total, without the file path.",
|
|
277
|
+
);
|
|
278
|
+
const timeoutSeconds = values.timeout === undefined ? 180 : Number(values.timeout);
|
|
279
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 3600)
|
|
280
|
+
throw new UsageError("--timeout takes a whole number of seconds between 1 and 3600.");
|
|
281
|
+
for (const flag of ["offset", "limit", "failure"])
|
|
282
|
+
if (values[flag] !== undefined && !/^\d+$/.test(String(values[flag])))
|
|
283
|
+
throw new UsageError(`--${flag} takes a whole number.`);
|
|
284
|
+
const cwd = await realpath(resolve(values.repo ?? process.cwd())).catch(() =>
|
|
285
|
+
resolve(values.repo ?? process.cwd()),
|
|
286
|
+
);
|
|
287
|
+
const root = await repositoryRoot(cwd);
|
|
288
|
+
if (!root) throw new UsageError("Run traceyard inside a git repository, or pass --repo <dir>.");
|
|
289
|
+
const stateDir = await stateDirectory(root);
|
|
290
|
+
const context = {
|
|
291
|
+
root,
|
|
292
|
+
cwd,
|
|
293
|
+
stateDir,
|
|
294
|
+
values,
|
|
295
|
+
testInput,
|
|
296
|
+
progress,
|
|
297
|
+
timeoutMs: timeoutSeconds * 1000,
|
|
298
|
+
env,
|
|
299
|
+
fetcher,
|
|
300
|
+
requestId: newRequestId(),
|
|
301
|
+
startedAt: new Date().toISOString(),
|
|
302
|
+
};
|
|
303
|
+
const result = await handlers[command](context);
|
|
304
|
+
return { schemaVersion: 1, command, ...result, exitCode: exitCodeFor(result.verdict) };
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (error instanceof UsageError) return usageResult(error.message, knownCommand(command));
|
|
307
|
+
if (error instanceof BlockedError)
|
|
308
|
+
return {
|
|
309
|
+
schemaVersion: 1,
|
|
310
|
+
command,
|
|
311
|
+
verdict: "BLOCKED",
|
|
312
|
+
exitCode: EXIT.BLOCKED,
|
|
313
|
+
summary: error.message,
|
|
314
|
+
next: "Fix what blocked the run, then rerun the same command.",
|
|
315
|
+
test: null,
|
|
316
|
+
runs: [],
|
|
317
|
+
warnings: [],
|
|
318
|
+
};
|
|
319
|
+
return {
|
|
320
|
+
schemaVersion: 1,
|
|
321
|
+
command: knownCommand(command),
|
|
322
|
+
verdict: "ERROR",
|
|
323
|
+
exitCode: EXIT.INTERNAL,
|
|
324
|
+
summary: String(error?.stack ?? error),
|
|
325
|
+
next: "This is a bug in Traceyard. Please report it with the command you ran.",
|
|
326
|
+
test: null,
|
|
327
|
+
runs: [],
|
|
328
|
+
warnings: [],
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function usageResult(message, command) {
|
|
334
|
+
return {
|
|
335
|
+
schemaVersion: 1,
|
|
336
|
+
command,
|
|
337
|
+
verdict: "ERROR",
|
|
338
|
+
exitCode: EXIT.USAGE,
|
|
339
|
+
summary: message,
|
|
340
|
+
next: "Run traceyard --help for usage.",
|
|
341
|
+
test: null,
|
|
342
|
+
runs: [],
|
|
343
|
+
warnings: [],
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function emit(result, json, io) {
|
|
348
|
+
if (json) io.stdout(JSON.stringify(result));
|
|
349
|
+
else if (result.verdict === "ERROR") io.stderr(`traceyard: ${result.summary}`);
|
|
350
|
+
else io.stdout(text(result));
|
|
351
|
+
return result.exitCode;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function defaultIo() {
|
|
355
|
+
return {
|
|
356
|
+
stdout: (line) => process.stdout.write(line + "\n"),
|
|
357
|
+
stderr: (line) => process.stderr.write(line + "\n"),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const runOptions = (ctx) => ({
|
|
362
|
+
repo: ctx.root,
|
|
363
|
+
stateDir: ctx.stateDir,
|
|
364
|
+
fetch: ctx.values.fetch,
|
|
365
|
+
fresh: ctx.values.fresh,
|
|
366
|
+
timeoutMs: ctx.timeoutMs,
|
|
367
|
+
progress: ctx.progress,
|
|
368
|
+
env: ctx.env,
|
|
369
|
+
cacheDir: cacheDirectory(ctx.env),
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* The one file at `commit` that a job log's failing test can mean. Anything
|
|
374
|
+
* else is an error, so a monorepo path is never guessed.
|
|
375
|
+
*/
|
|
376
|
+
async function testPathFromLog(root, commit, logPaths) {
|
|
377
|
+
const files = await filesAtCommit(root, commit);
|
|
378
|
+
const matches = logPaths.map((logPath) => ({ logPath, found: matchTestPath(logPath, files) }));
|
|
379
|
+
const candidates = [...new Set(matches.flatMap((match) => match.found))];
|
|
380
|
+
const missing = matches.filter((match) => !match.found.length).map((match) => match.logPath);
|
|
381
|
+
if (candidates.length === 1 && !missing.length) return candidates[0];
|
|
382
|
+
const list = (paths) =>
|
|
383
|
+
paths.slice(0, 8).join(", ") + (paths.length > 8 ? `, and ${paths.length - 8} more` : "");
|
|
384
|
+
const notFound = missing.length ? ` Not found at ${commit.slice(0, 12)}: ${list(missing)}.` : "";
|
|
385
|
+
if (!candidates.length) throw new UsageError(`${notFound.trim()} Pass the test path.`);
|
|
386
|
+
throw new UsageError(
|
|
387
|
+
`The job log can mean more than one test file. Pick one: ${list(candidates)}.${notFound}`,
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function repro(ctx) {
|
|
392
|
+
const { values, root } = ctx;
|
|
393
|
+
if (values.at && values.from) throw new UsageError("Pass either --at or --from, not both.");
|
|
394
|
+
const warnings = [];
|
|
395
|
+
let testPath = testArgument(ctx.testInput, ctx.cwd, root);
|
|
396
|
+
let commit;
|
|
397
|
+
let source;
|
|
398
|
+
if (values.from) {
|
|
399
|
+
const link = await resolveActionsLink(values.from, await githubRepository(root), {
|
|
400
|
+
auth: await githubAuth(ctx.env),
|
|
401
|
+
fetcher: ctx.fetcher,
|
|
402
|
+
});
|
|
403
|
+
source = { jobUrl: link.jobUrl, commit: link.commit, mergeCommit: link.mergeCommit };
|
|
404
|
+
commit = link.commit;
|
|
405
|
+
if (link.mergeCommit)
|
|
406
|
+
warnings.push("CI tested the pull request merge commit, not the branch head.");
|
|
407
|
+
if (!testPath && link.unreadableFailures.length)
|
|
408
|
+
throw new UsageError(
|
|
409
|
+
`The job log has a failure Traceyard can't read as a test path: ${link.unreadableFailures[0]} Pass the test path.`,
|
|
410
|
+
);
|
|
411
|
+
if (!testPath && !link.failingTests.length)
|
|
412
|
+
throw new UsageError("No failing test file was found in the job log. Pass the test path.");
|
|
413
|
+
if (!(await resolveCommit(root, commit))) {
|
|
414
|
+
if (!values.fetch)
|
|
415
|
+
throw new UsageError(
|
|
416
|
+
`The commit CI tested (${commit}) isn't in this clone. Pass --fetch to download it.`,
|
|
417
|
+
);
|
|
418
|
+
if (!testPath)
|
|
419
|
+
await ensureCommit(root, commit, { fetch: true }).catch((error) => {
|
|
420
|
+
throw new BlockedError(error.message);
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
if (!testPath) {
|
|
424
|
+
testPath = await testPathFromLog(root, commit, link.failingTests);
|
|
425
|
+
if (!link.failingTests.includes(testPath))
|
|
426
|
+
warnings.push(
|
|
427
|
+
`The job log says ${link.failingTests[0]}; using ${testPath}, the only matching file at that commit.`,
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
} else {
|
|
431
|
+
commit = await commitArgument(root, values.at ?? "HEAD", "--at", values.fetch);
|
|
432
|
+
}
|
|
433
|
+
if (!testPath)
|
|
434
|
+
throw new UsageError("Pass the test file to reproduce, e.g. traceyard repro src/cart.test.ts");
|
|
435
|
+
if (!values.at && !values.from && (await hasUncommittedChanges(root)))
|
|
436
|
+
warnings.push("Ran the last commit (HEAD). Your uncommitted changes were not included.");
|
|
437
|
+
const run = await runTest({ ...runOptions(ctx), commit, testPath, testCase: values.case });
|
|
438
|
+
const verdict = reproVerdict(run, testPath, { fromCi: Boolean(source) });
|
|
439
|
+
const test = { path: testPath, case: values.case ?? null };
|
|
440
|
+
const evidenceEnvelope = singleRunEnvelope({
|
|
441
|
+
command: "repro",
|
|
442
|
+
run,
|
|
443
|
+
test,
|
|
444
|
+
repository: repositoryId(await githubRepository(root), root),
|
|
445
|
+
requestId: ctx.requestId,
|
|
446
|
+
next: verdict.next,
|
|
447
|
+
startedAt: ctx.startedAt,
|
|
448
|
+
completedAt: new Date().toISOString(),
|
|
449
|
+
});
|
|
450
|
+
if (run.status !== "BLOCKED")
|
|
451
|
+
await writeFile(
|
|
452
|
+
join(ctx.stateDir, "last-repro.json"),
|
|
453
|
+
JSON.stringify(
|
|
454
|
+
{ test: testPath, case: values.case ?? null, commit: run.commit, verdict: verdict.verdict },
|
|
455
|
+
null,
|
|
456
|
+
2,
|
|
457
|
+
),
|
|
458
|
+
);
|
|
459
|
+
return {
|
|
460
|
+
...verdict,
|
|
461
|
+
test,
|
|
462
|
+
runs: [publicRun("repro", run, values, root)],
|
|
463
|
+
...(source ? { source } : {}),
|
|
464
|
+
evidenceEnvelope,
|
|
465
|
+
warnings,
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function defaultTest(ctx) {
|
|
470
|
+
const explicit = testArgument(ctx.testInput, ctx.cwd, ctx.root);
|
|
471
|
+
const last = await lastRepro(ctx.stateDir);
|
|
472
|
+
if (explicit) return { path: explicit, case: ctx.values.case ?? null, last };
|
|
473
|
+
if (!last?.test)
|
|
474
|
+
throw new UsageError(
|
|
475
|
+
"Pass the test file, or run `traceyard repro <test>` first so Traceyard remembers it.",
|
|
476
|
+
);
|
|
477
|
+
return { path: last.test, case: ctx.values.case ?? last.case ?? null, last };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async function check(ctx) {
|
|
481
|
+
const test = await defaultTest(ctx);
|
|
482
|
+
// Fingerprint the tree before and after: an edit during the run makes it stale.
|
|
483
|
+
const before = await worktreeSnapshot(ctx.root);
|
|
484
|
+
const run = await runTest({
|
|
485
|
+
...runOptions(ctx),
|
|
486
|
+
commit: null,
|
|
487
|
+
testPath: test.path,
|
|
488
|
+
testCase: test.case ?? undefined,
|
|
489
|
+
install: ctx.values.install,
|
|
490
|
+
});
|
|
491
|
+
const after = await worktreeSnapshot(ctx.root);
|
|
492
|
+
const verdict = checkVerdict(run, test.path);
|
|
493
|
+
const stale = worktreeChanged(before, after);
|
|
494
|
+
const selected = { path: test.path, case: test.case };
|
|
495
|
+
const evidenceEnvelope = singleRunEnvelope({
|
|
496
|
+
command: "check",
|
|
497
|
+
run,
|
|
498
|
+
test: selected,
|
|
499
|
+
repository: repositoryId(await githubRepository(ctx.root), ctx.root),
|
|
500
|
+
requestId: ctx.requestId,
|
|
501
|
+
worktree: {
|
|
502
|
+
fingerprint: before.fingerprint,
|
|
503
|
+
stale,
|
|
504
|
+
complete: before.complete && after.complete,
|
|
505
|
+
},
|
|
506
|
+
next: stale ? "Stop editing files, then rerun `traceyard check`." : verdict.next,
|
|
507
|
+
startedAt: ctx.startedAt,
|
|
508
|
+
completedAt: new Date().toISOString(),
|
|
509
|
+
});
|
|
510
|
+
return {
|
|
511
|
+
...(stale
|
|
512
|
+
? {
|
|
513
|
+
verdict: "INCONCLUSIVE",
|
|
514
|
+
summary: `Files changed while ${test.path} ran, so the result may not match your working tree.`,
|
|
515
|
+
next: "Stop editing files, then rerun `traceyard check`.",
|
|
516
|
+
}
|
|
517
|
+
: verdict),
|
|
518
|
+
test: selected,
|
|
519
|
+
runs: [publicRun("check", run, ctx.values, ctx.root)],
|
|
520
|
+
evidenceEnvelope,
|
|
521
|
+
warnings: [],
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Run the test at both commits and judge the pair. Shared by verify and guard. */
|
|
526
|
+
async function compare(ctx, { before, after, test, fresh = ctx.values.fresh }) {
|
|
527
|
+
const { values, root } = ctx;
|
|
528
|
+
const run = (commit) =>
|
|
529
|
+
runTest({
|
|
530
|
+
...runOptions(ctx),
|
|
531
|
+
fresh,
|
|
532
|
+
commit,
|
|
533
|
+
testPath: test.path,
|
|
534
|
+
testCase: test.case ?? undefined,
|
|
535
|
+
});
|
|
536
|
+
const baseline = await run(before);
|
|
537
|
+
const candidate = baseline.status === "FAILED" ? await run(after) : null;
|
|
538
|
+
const files = candidate ? await changedFiles(root, before, after) : [];
|
|
539
|
+
const verdict = verifyVerdict({
|
|
540
|
+
baseline,
|
|
541
|
+
candidate: candidate ?? baseline,
|
|
542
|
+
testPath: test.path,
|
|
543
|
+
changedFiles: files,
|
|
544
|
+
linked: candidate ? await changedThroughLinks(root, before, after, files) : [],
|
|
545
|
+
});
|
|
546
|
+
const runs = [publicRun("baseline", baseline, values, root)];
|
|
547
|
+
if (candidate) runs.push(publicRun("candidate", candidate, values, root));
|
|
548
|
+
return { baseline, candidate, verdict, runs };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async function verify(ctx) {
|
|
552
|
+
const { values, root } = ctx;
|
|
553
|
+
const test = await defaultTest(ctx);
|
|
554
|
+
const sameTest =
|
|
555
|
+
test.last && test.last.test === test.path && (test.last.case ?? null) === test.case;
|
|
556
|
+
const beforeRef =
|
|
557
|
+
values.before ?? (sameTest && test.last.verdict === "REPRODUCED" ? test.last.commit : null);
|
|
558
|
+
if (!beforeRef)
|
|
559
|
+
throw new UsageError(
|
|
560
|
+
"Pass --before <sha> (the commit where the test failed), or run `traceyard repro` for this test first.",
|
|
561
|
+
);
|
|
562
|
+
const before = await commitArgument(root, beforeRef, "--before", values.fetch);
|
|
563
|
+
const after = await commitArgument(root, values.after ?? "HEAD", "--after", values.fetch);
|
|
564
|
+
const warnings = [];
|
|
565
|
+
if (!values.after && (await hasUncommittedChanges(root)))
|
|
566
|
+
warnings.push(
|
|
567
|
+
"Verified the last commit (HEAD). Commit your changes first if they are part of the fix.",
|
|
568
|
+
);
|
|
569
|
+
const { baseline, candidate, verdict, runs } = await compare(ctx, {
|
|
570
|
+
before,
|
|
571
|
+
after,
|
|
572
|
+
test,
|
|
573
|
+
});
|
|
574
|
+
const repository = await githubRepository(root);
|
|
575
|
+
const evidenceEnvelope = verifyEnvelope({
|
|
576
|
+
baseline,
|
|
577
|
+
candidate,
|
|
578
|
+
test: { path: test.path, case: test.case },
|
|
579
|
+
changedTests: verdict.changedTests,
|
|
580
|
+
repository: repositoryId(repository, root),
|
|
581
|
+
requestId: ctx.requestId,
|
|
582
|
+
next: verdict.next,
|
|
583
|
+
startedAt: ctx.startedAt,
|
|
584
|
+
completedAt: new Date().toISOString(),
|
|
585
|
+
});
|
|
586
|
+
let receiptInfo;
|
|
587
|
+
if (candidate && verdict.verdict !== "BLOCKED") {
|
|
588
|
+
const written = await writeReceipt(ctx.stateDir, {
|
|
589
|
+
repository,
|
|
590
|
+
test: { path: test.path, case: test.case },
|
|
591
|
+
verdict,
|
|
592
|
+
baseline,
|
|
593
|
+
candidate,
|
|
594
|
+
evidenceEnvelope,
|
|
595
|
+
});
|
|
596
|
+
receiptInfo = {
|
|
597
|
+
id: written.receipt.id,
|
|
598
|
+
path: relative(root, written.jsonPath).split("\\").join("/"),
|
|
599
|
+
markdownPath: relative(root, written.markdownPath).split("\\").join("/"),
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
verdict: verdict.verdict,
|
|
604
|
+
summary: verdict.summary,
|
|
605
|
+
next: verdict.next,
|
|
606
|
+
test: { path: test.path, case: test.case },
|
|
607
|
+
runs,
|
|
608
|
+
changedTests: verdict.changedTests,
|
|
609
|
+
...(receiptInfo ? { receipt: receiptInfo } : {}),
|
|
610
|
+
evidenceEnvelope,
|
|
611
|
+
warnings,
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
async function receipt(ctx) {
|
|
616
|
+
const id = ctx.testInput;
|
|
617
|
+
const found = await readReceipt(ctx.stateDir, id);
|
|
618
|
+
if (!found)
|
|
619
|
+
throw new UsageError(
|
|
620
|
+
id
|
|
621
|
+
? `No receipt ${id} in .traceyard/receipts.`
|
|
622
|
+
: "No receipts yet. Run `traceyard verify` first.",
|
|
623
|
+
);
|
|
624
|
+
const r = found.receipt;
|
|
625
|
+
const warnings = found.intact
|
|
626
|
+
? []
|
|
627
|
+
: ["This receipt was edited after it was written. Its digest doesn't match."];
|
|
628
|
+
return {
|
|
629
|
+
verdict: found.intact ? r.verdict : "INCONCLUSIVE",
|
|
630
|
+
summary: r.summary,
|
|
631
|
+
next: "Paste the Markdown receipt into your pull request.",
|
|
632
|
+
test: r.test,
|
|
633
|
+
runs: [],
|
|
634
|
+
receipt: {
|
|
635
|
+
id: r.id,
|
|
636
|
+
path: relative(ctx.root, found.jsonPath).split("\\").join("/"),
|
|
637
|
+
markdownPath: relative(ctx.root, found.jsonPath.replace(/\.json$/, ".md"))
|
|
638
|
+
.split("\\")
|
|
639
|
+
.join("/"),
|
|
640
|
+
intact: found.intact,
|
|
641
|
+
// Agents get the Markdown to paste into a pull request; --json gets the full body.
|
|
642
|
+
body: ctx.values.json && !ctx.values.agent ? r : undefined,
|
|
643
|
+
markdown: ctx.values.json && !ctx.values.agent ? undefined : receiptMarkdown(r),
|
|
644
|
+
},
|
|
645
|
+
warnings,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Reruns the receipt's test and passes only if that run is FIXED. A receipt is
|
|
651
|
+
* a file anyone with write access can rewrite, digest included, so it only
|
|
652
|
+
* says which test and failing commit to try. Both commits are run fresh,
|
|
653
|
+
* ignoring cached results. The failing commit must be on HEAD's first-parent
|
|
654
|
+
* line unless the caller names it with --before. That narrows what a rewritten
|
|
655
|
+
* receipt can point at; it does not stop someone who can write commits.
|
|
656
|
+
* Use it in a pre-push hook or as an agent's last step.
|
|
657
|
+
*/
|
|
658
|
+
async function guard(ctx) {
|
|
659
|
+
const found = await readReceipt(ctx.stateDir, ctx.testInput);
|
|
660
|
+
if (ctx.testInput && !found)
|
|
661
|
+
throw new UsageError(`No receipt ${ctx.testInput} in .traceyard/receipts.`);
|
|
662
|
+
const pinned = ctx.values.before
|
|
663
|
+
? await commitArgument(ctx.root, ctx.values.before, "--before", ctx.values.fetch)
|
|
664
|
+
: null;
|
|
665
|
+
const head = await headCommit(ctx.root);
|
|
666
|
+
const warnings = [];
|
|
667
|
+
if (await hasUncommittedChanges(ctx.root))
|
|
668
|
+
warnings.push("You have uncommitted changes. The guard checks the last commit (HEAD) only.");
|
|
669
|
+
let verdict = guardVerdict({
|
|
670
|
+
receipt: found?.receipt ?? null,
|
|
671
|
+
intact: found?.intact ?? false,
|
|
672
|
+
head,
|
|
673
|
+
id: found?.id,
|
|
674
|
+
});
|
|
675
|
+
let runs = [];
|
|
676
|
+
let changedTests;
|
|
677
|
+
// Only a receipt that would pass is rechecked; nothing else can turn into FIXED.
|
|
678
|
+
if (verdict.verdict === "FIXED") {
|
|
679
|
+
const test = receiptTest(found.receipt);
|
|
680
|
+
const baseline = pinned ?? found.receipt.baseline.commit;
|
|
681
|
+
if (!pinned && !(await onFirstParentLine(ctx.root, baseline, head)))
|
|
682
|
+
verdict = {
|
|
683
|
+
verdict: "NEEDS_REVIEW",
|
|
684
|
+
summary: `The receipt's failing commit ${baseline.slice(0, 12)} is not on HEAD's first-parent line, so it can't be taken on the receipt's word.`,
|
|
685
|
+
next: "Check which commit really failed, then run `traceyard guard --before <sha>`.",
|
|
686
|
+
};
|
|
687
|
+
else {
|
|
688
|
+
const checked = await compare(ctx, { before: baseline, after: head, test, fresh: true });
|
|
689
|
+
runs = checked.runs;
|
|
690
|
+
changedTests = checked.verdict.changedTests;
|
|
691
|
+
verdict = guardRecheckVerdict({ recheck: checked.verdict, test, baseline, head });
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
...verdict,
|
|
696
|
+
test: found ? receiptTest(found.receipt) : null,
|
|
697
|
+
runs,
|
|
698
|
+
...(changedTests ? { changedTests } : {}),
|
|
699
|
+
...(found
|
|
700
|
+
? {
|
|
701
|
+
receipt: {
|
|
702
|
+
id: found.id,
|
|
703
|
+
path: relative(ctx.root, found.jsonPath).split("\\").join("/"),
|
|
704
|
+
markdownPath: relative(ctx.root, found.jsonPath.replace(/\.json$/, ".md"))
|
|
705
|
+
.split("\\")
|
|
706
|
+
.join("/"),
|
|
707
|
+
intact: found.intact,
|
|
708
|
+
},
|
|
709
|
+
}
|
|
710
|
+
: {}),
|
|
711
|
+
warnings,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async function latestEvidenceId(ctx) {
|
|
716
|
+
const last = await readJson(join(ctx.stateDir, "last-evidence.json"));
|
|
717
|
+
if (last?.evidenceId) return last.evidenceId;
|
|
718
|
+
return (await listEvidence(ctx.stateDir, 1))[0]?.evidenceId ?? null;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async function evidenceFor(ctx) {
|
|
722
|
+
const id = ctx.testInput ?? (await latestEvidenceId(ctx));
|
|
723
|
+
if (!id) throw new UsageError("No runs yet. Run `traceyard repro` or `traceyard check` first.");
|
|
724
|
+
const run = await readEvidence(ctx.stateDir, id);
|
|
725
|
+
if (!run)
|
|
726
|
+
throw new UsageError(
|
|
727
|
+
`No run ${id} in .traceyard/runs. Run \`traceyard inspect\` to list runs.`,
|
|
728
|
+
);
|
|
729
|
+
return run;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// A path:line[:column] reference to a JavaScript, TypeScript or Python file.
|
|
733
|
+
const LOCATION = /(?:^|[\s(])((?:[\w@.+-]+\/)*[\w@.+-]+\.(?:[cm]?[jt]sx?|py)):(\d+)(?::(\d+))?/m;
|
|
734
|
+
|
|
735
|
+
/** Where the failure points: the first file:line in the message that exists in the repository. */
|
|
736
|
+
async function failureLocation(ctx, run, message) {
|
|
737
|
+
for (const line of message.split("\n")) {
|
|
738
|
+
const match = line.match(LOCATION);
|
|
739
|
+
if (!match || /node_modules|site-packages/.test(match[1])) continue;
|
|
740
|
+
const source = await showFile(ctx.root, run.commit, match[1]);
|
|
741
|
+
if (source === null) continue;
|
|
742
|
+
return {
|
|
743
|
+
path: match[1],
|
|
744
|
+
line: Number(match[2]),
|
|
745
|
+
column: match[3] ? Number(match[3]) : null,
|
|
746
|
+
source,
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
return null;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** The first failure in a run, where it happened, and the source lines around it. */
|
|
753
|
+
async function explain(ctx) {
|
|
754
|
+
const run = await evidenceFor(ctx);
|
|
755
|
+
const index = Math.max(1, Number(ctx.values.failure ?? 1));
|
|
756
|
+
const failure = run.failures[index - 1];
|
|
757
|
+
const base = {
|
|
758
|
+
test: run.test ?? null,
|
|
759
|
+
runs: [publicRun(run.commit ? "repro" : "check", { ...run, cached: true }, {}, ctx.root)],
|
|
760
|
+
warnings: [],
|
|
761
|
+
};
|
|
762
|
+
if (!failure)
|
|
763
|
+
return {
|
|
764
|
+
verdict: "AVAILABLE",
|
|
765
|
+
summary: run.failures.length
|
|
766
|
+
? `Run ${run.evidenceId} has ${run.failures.length} failure(s); there is no failure ${index}.`
|
|
767
|
+
: `Run ${run.evidenceId} has no failures: ${run.status.toLowerCase()}.`,
|
|
768
|
+
next: run.failures.length
|
|
769
|
+
? `Pass a failure number from 1 to ${run.failures.length}.`
|
|
770
|
+
: "Nothing to explain. Run `traceyard inspect` for its log.",
|
|
771
|
+
...base,
|
|
772
|
+
};
|
|
773
|
+
const message = compactFailure(failure.message, ctx.root);
|
|
774
|
+
const location = await failureLocation(ctx, run, message);
|
|
775
|
+
let excerpt = null;
|
|
776
|
+
if (location) {
|
|
777
|
+
const lines = location.source.split("\n");
|
|
778
|
+
const start = Math.max(1, location.line - 6);
|
|
779
|
+
const end = Math.min(lines.length, location.line + 6);
|
|
780
|
+
excerpt = {
|
|
781
|
+
path: location.path,
|
|
782
|
+
commit: run.commit,
|
|
783
|
+
startLine: start,
|
|
784
|
+
text: lines
|
|
785
|
+
.slice(start - 1, end)
|
|
786
|
+
.map(
|
|
787
|
+
(l, i) =>
|
|
788
|
+
`${String(start + i).padStart(5)}${start + i === location.line ? " >" : " "} ${l}`,
|
|
789
|
+
)
|
|
790
|
+
.join("\n")
|
|
791
|
+
.slice(0, 1600),
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
return {
|
|
795
|
+
verdict: "AVAILABLE",
|
|
796
|
+
summary: `${failure.name} failed${location ? ` at ${location.path}:${location.line}` : ""}.`,
|
|
797
|
+
next: run.commit
|
|
798
|
+
? "Fix the code, not the test, then run `traceyard check`."
|
|
799
|
+
: "Change the code and run `traceyard check` again.",
|
|
800
|
+
...base,
|
|
801
|
+
explanation: {
|
|
802
|
+
evidenceId: run.evidenceId,
|
|
803
|
+
failure: {
|
|
804
|
+
index,
|
|
805
|
+
of: run.failures.length,
|
|
806
|
+
file: failure.file,
|
|
807
|
+
name: failure.name,
|
|
808
|
+
message: message.slice(0, 2000),
|
|
809
|
+
},
|
|
810
|
+
location: location
|
|
811
|
+
? { path: location.path, line: location.line, column: location.column }
|
|
812
|
+
: null,
|
|
813
|
+
source: excerpt,
|
|
814
|
+
},
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** Without an ID: recent runs and receipts. With one: that run's log, in bounded slices. */
|
|
819
|
+
async function inspect(ctx) {
|
|
820
|
+
if (!ctx.testInput) {
|
|
821
|
+
const runs = await listEvidence(ctx.stateDir, 8);
|
|
822
|
+
const receipts = await listReceipts(ctx.stateDir, 5);
|
|
823
|
+
return {
|
|
824
|
+
verdict: "AVAILABLE",
|
|
825
|
+
summary: `${runs.length} recent run(s) and ${receipts.length} receipt(s) in .traceyard.`,
|
|
826
|
+
next: runs.length
|
|
827
|
+
? "Pass an evidence ID to read its log, or use `traceyard explain <id>`."
|
|
828
|
+
: "Run `traceyard repro <test>` first.",
|
|
829
|
+
test: null,
|
|
830
|
+
runs: [],
|
|
831
|
+
items: [
|
|
832
|
+
...runs.map((r) => ({
|
|
833
|
+
kind: "run",
|
|
834
|
+
id: r.evidenceId,
|
|
835
|
+
test: r.test?.path ?? null,
|
|
836
|
+
commit: r.commit,
|
|
837
|
+
status: r.status,
|
|
838
|
+
recordedAt: r.recordedAt ?? null,
|
|
839
|
+
})),
|
|
840
|
+
...receipts.map((r) => ({
|
|
841
|
+
kind: "receipt",
|
|
842
|
+
id: r.id,
|
|
843
|
+
test: r.test?.path ?? null,
|
|
844
|
+
commit: r.candidate?.commit ?? null,
|
|
845
|
+
status: r.verdict,
|
|
846
|
+
recordedAt: r.createdAt ?? null,
|
|
847
|
+
})),
|
|
848
|
+
],
|
|
849
|
+
warnings: [],
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
if (ctx.testInput.startsWith("rcpt_")) return receipt(ctx);
|
|
853
|
+
const run = await evidenceFor(ctx);
|
|
854
|
+
const output = cleanOutput(run.output ?? "", ctx.root);
|
|
855
|
+
const offset = Math.min(Number(ctx.values.offset ?? 0), output.length);
|
|
856
|
+
const limit = Math.min(SLICE_MAX, Math.max(200, Number(ctx.values.limit ?? SLICE_DEFAULT)));
|
|
857
|
+
const slice = output.slice(offset, offset + limit);
|
|
858
|
+
const nextOffset = offset + slice.length < output.length ? offset + slice.length : null;
|
|
859
|
+
return {
|
|
860
|
+
verdict: "AVAILABLE",
|
|
861
|
+
summary: output.length
|
|
862
|
+
? `Characters ${offset}-${offset + slice.length} of ${output.length} from run ${run.evidenceId}.`
|
|
863
|
+
: `Run ${run.evidenceId} recorded no output.`,
|
|
864
|
+
next:
|
|
865
|
+
nextOffset === null
|
|
866
|
+
? "That is the end of the log."
|
|
867
|
+
: `Pass --offset ${nextOffset} for the next slice.`,
|
|
868
|
+
test: run.test ?? null,
|
|
869
|
+
runs: [],
|
|
870
|
+
evidence: {
|
|
871
|
+
id: run.evidenceId,
|
|
872
|
+
offset,
|
|
873
|
+
nextOffset,
|
|
874
|
+
total: output.length,
|
|
875
|
+
text: slice,
|
|
876
|
+
},
|
|
877
|
+
warnings: [],
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
async function readJson(path) {
|
|
882
|
+
try {
|
|
883
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
884
|
+
} catch {
|
|
885
|
+
return null;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** Remember the run an agent most likely wants to explain next: the last failing one. */
|
|
890
|
+
async function rememberEvidence(stateDir, runs) {
|
|
891
|
+
const run =
|
|
892
|
+
runs.findLast((r) => r.evidenceId && r.status === "FAILED") ??
|
|
893
|
+
runs.findLast((r) => r.evidenceId);
|
|
894
|
+
if (run)
|
|
895
|
+
await writeFile(
|
|
896
|
+
join(stateDir, "last-evidence.json"),
|
|
897
|
+
JSON.stringify({ evidenceId: run.evidenceId }, null, 2),
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const remembering = (handler) => async (ctx) => {
|
|
902
|
+
const result = await handler(ctx);
|
|
903
|
+
await rememberEvidence(ctx.stateDir, result.runs ?? []);
|
|
904
|
+
return result;
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
const handlers = {
|
|
908
|
+
repro: remembering(repro),
|
|
909
|
+
check: remembering(check),
|
|
910
|
+
verify: remembering(verify),
|
|
911
|
+
guard: remembering(guard),
|
|
912
|
+
explain,
|
|
913
|
+
inspect,
|
|
914
|
+
receipt,
|
|
915
|
+
};
|