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