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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Praise Omosanya Oluwafisayo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,218 @@
1
- # Temporary Holding Version
1
+ # Traceyard CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Prove a failing test is fixed, on your own machine. No account, no server, no network unless you ask for it.
4
+
5
+ ```bash
6
+ traceyard repro src/cart.test.ts --at 3f2c9e1 # fails at the commit CI tested
7
+ traceyard check # run it against your edits, as often as you like
8
+ git commit -am "Fix cart rounding"
9
+ traceyard verify # failed before, passes now, test untouched
10
+ traceyard guard # exit 0 only if HEAD is proven fixed
11
+ traceyard receipt # Markdown you can paste into the PR
12
+ ```
13
+
14
+ Coding agents get the same commands as MCP tools with `traceyard mcp`. See [Coding agents](#coding-agents-mcp).
15
+
16
+ Until the npm package ships (#49), run it from a Traceyard checkout with `node packages/cli/bin/traceyard.mjs`. Node 22.12 or later.
17
+
18
+ ## Commands
19
+
20
+ ### `traceyard repro [test] [--at <sha> | --from <actions-url>]`
21
+
22
+ Runs the test at an exact commit in a throwaway `git worktree`. Your working tree, index and stash are never touched. `--at` defaults to `HEAD`.
23
+
24
+ `--from` takes a GitHub Actions run or job link. Traceyard reads the job log, finds the commit `actions/checkout` checked out, and picks the failing test file if the log names exactly one. It uses `GITHUB_TOKEN` or `GH_TOKEN` if set, then an authenticated `gh` CLI. Public repositories work without either. If the tested commit isn't in your clone (for example a pull request merge commit), add `--fetch`.
25
+
26
+ Traceyard remembers the test and commit, so `check` and `verify` can run without arguments afterwards.
27
+
28
+ ### `traceyard check [test]`
29
+
30
+ Runs the test in your working tree, including uncommitted edits. This is the fast loop for each attempt at a fix. It never writes a receipt, because uncommitted code can't be pinned to a commit.
31
+
32
+ ### `traceyard verify [test] [--before <sha>] [--after <sha>]`
33
+
34
+ Runs the test at the failing commit (`--before`, default: the last reproduced commit) and at the fix commit (`--after`, default `HEAD`). It compares the files changed between them. The verdict is `FIXED` only when all of these are true:
35
+
36
+ 1. The test failed at `--before`.
37
+ 2. The same test file passed at `--after`, with at least one passing test and no extra skips.
38
+ 3. No tests, fixtures, snapshots, mocks or test runner config changed between the two commits.
39
+
40
+ Each verify writes a receipt to `.traceyard/receipts/` as JSON and Markdown.
41
+
42
+ ### `traceyard guard [receipt]`
43
+
44
+ A merge gate for scripts, hooks and agents. It passes (`FIXED`, exit 0) only when the newest receipt (or the one you name) is intact, says `FIXED`, and its fix commit is exactly `HEAD`. If there is no receipt, or commits were added after it, the verdict is `UNVERIFIED` (exit 1). An edited receipt or a `NEEDS_REVIEW` receipt gives `NEEDS_REVIEW` (exit 2). Uncommitted changes add a warning, because only `HEAD` is checked.
45
+
46
+ ```bash
47
+ # .git/hooks/pre-push
48
+ traceyard guard || exit 1
49
+ ```
50
+
51
+ ### `traceyard explain [evidence] [--failure <n>]`
52
+
53
+ Explains one failure from a recorded run. The default is the last failing run's first failure. You get the failure message with terminal codes and dependency stack frames removed, the `file:line` it points to, and 13 lines of source around that line at the run's commit, so an agent doesn't have to open the file.
54
+
55
+ ### `traceyard inspect [evidence] [--offset <n>] [--limit <n>]`
56
+
57
+ Without an ID, `inspect` lists the 8 most recent runs and the 5 most recent receipts. With an evidence ID, it returns one slice of that run's full test log, 3,000 characters by default and at most 4,000. Follow `evidence.nextOffset` to read the next slice. With a receipt ID, it behaves like `receipt`.
58
+
59
+ ### `traceyard receipt [id]`
60
+
61
+ Prints the newest receipt (or the one with that id) as Markdown. With `--json`, it returns the receipt body. Each receipt carries a SHA-256 digest of its contents. If the file was edited, `receipt` reports `intact: false` and the verdict `INCONCLUSIVE`.
62
+
63
+ Receipts have trust level `local`: they record what ran on this machine. Signed CI receipts come with the GitHub Action in Phase 3.
64
+
65
+ ## Options
66
+
67
+ | Option | Effect |
68
+ | ----------------- | ------------------------------------------------------------------------ |
69
+ | `--case <name>` | Pytest case to run, such as `TestCart::test_total`. |
70
+ | `--json` | Print exactly one JSON object on stdout. Progress messages are silenced. |
71
+ | `--log` | Include the last 4,000 characters of test output. |
72
+ | `--fetch` | Let git fetch a commit that isn't in this clone. |
73
+ | `--install` | `check` only: install missing dependencies in your working tree. |
74
+ | `--fresh` | Ignore the cached result for the same commit and test. |
75
+ | `--timeout <sec>` | Time limit for one test run. Default 180. |
76
+ | `--repo <dir>` | Repository to use. Default: the current directory. |
77
+ | `--failure <n>` | `explain` only: which failure to explain. Default 1. |
78
+ | `--offset <n>` | `inspect` only: where the log slice starts. Default 0. |
79
+ | `--limit <n>` | `inspect` only: slice length in characters, 200 to 4,000. Default 3,000. |
80
+
81
+ ## Exit codes
82
+
83
+ | Code | Verdicts | Meaning |
84
+ | ---- | ------------------------------------------------ | ------------------------------------------ |
85
+ | 0 | `REPRODUCED`, `PASSED`, `FIXED`, `AVAILABLE` | The command got the answer it was for. |
86
+ | 1 | `FAILING`, `STILL_FAILING`, `UNVERIFIED` | The test fails, or the fix isn't proven. |
87
+ | 2 | `NOT_REPRODUCED`, `NEEDS_REVIEW`, `INCONCLUSIVE` | A person needs to look before trusting it. |
88
+ | 3 | `BLOCKED` | The test could not run here. |
89
+ | 64 | `ERROR` | The command line was wrong. |
90
+ | 70 | | A bug in Traceyard. Please report it. |
91
+
92
+ ## JSON output
93
+
94
+ Every command prints one object. The schema is `cliResultSchema` in [`shared/contracts/cli.ts`](https://github.com/fysaio/traceyard/blob/main/docs/../shared/contracts/cli.ts), and contract tests check every command against it. Fields are only added within `schemaVersion: 1`.
95
+
96
+ ```json
97
+ {
98
+ "schemaVersion": 1,
99
+ "command": "verify",
100
+ "verdict": "FIXED",
101
+ "exitCode": 0,
102
+ "summary": "src/sum.test.js failed at c2b9e3e081cb and passes at 48c7902bf4c5, with no test files changed.",
103
+ "next": "Open a pull request and attach the receipt.",
104
+ "test": { "path": "src/sum.test.js", "case": null },
105
+ "runs": [
106
+ {
107
+ "role": "baseline",
108
+ "commit": "c2b9e3e081cb88e2a02f39960433d6b625abf56c",
109
+ "workingTree": false,
110
+ "status": "FAILED",
111
+ "counts": { "passed": 1, "failed": 1, "skipped": 0 },
112
+ "failures": [
113
+ {
114
+ "file": "src/sum.test.js",
115
+ "name": "adds numbers",
116
+ "message": "AssertionError: expected -1 to be 3 // Object.is equality\n at src/sum.test.js:3:44"
117
+ }
118
+ ],
119
+ "truncated": false,
120
+ "durationMs": 737,
121
+ "cached": true,
122
+ "dependencies": "linked",
123
+ "evidenceId": "ev_c2b9e3e081cb_3fd09b30eb84",
124
+ "message": "1 passed, 1 failed, 0 skipped."
125
+ },
126
+ {
127
+ "role": "candidate",
128
+ "commit": "48c7902bf4c59e0320d0749bcf4553a9bd1c9327",
129
+ "status": "SUCCEEDED",
130
+ "...": "..."
131
+ }
132
+ ],
133
+ "changedTests": [],
134
+ "receipt": {
135
+ "id": "rcpt_20261120084918982_d3a80a",
136
+ "path": ".traceyard/receipts/rcpt_20261120084918982_d3a80a.json",
137
+ "markdownPath": ".traceyard/receipts/rcpt_20261120084918982_d3a80a.md"
138
+ },
139
+ "warnings": []
140
+ }
141
+ ```
142
+
143
+ - `next` is one sentence telling a person or agent what to do next.
144
+ - Output is bounded for agents: up to 5 failures, 600 characters each, with stack frames from `node_modules` removed. Raw output only appears with `--log`. A full result stays well under 1,500 tokens.
145
+ - Every run that executed has an `evidenceId`. The full log stays on disk; read it with `inspect <evidenceId>` in bounded slices. Terminal colours, progress bars, repeated lines and absolute paths are removed first.
146
+ - `dependencies` says how packages were made available:
147
+ - `existing`: already installed.
148
+ - `linked`: the commit has the same lockfile as your clone, so your `node_modules` was linked in.
149
+ - `cached`: a previous run installed this exact lockfile, and that copy was reused.
150
+ - `installed`: installed with lifecycle scripts off. For single-package projects the install goes into the dependency cache, so the next commit with the same lockfile reuses it.
151
+ - `none`: the project needs no packages.
152
+
153
+ ## Where things are stored
154
+
155
+ Everything lives in `.traceyard/` at the repository root. That folder contains its own `.gitignore`, so it never shows up in `git status`.
156
+
157
+ - `runs/`: one file per run, named by evidence ID. A commit's result never changes, so `repro` and `verify` reuse it; `--fresh` reruns. Working-tree runs from `check` are kept too (the newest 20), so `explain` and `inspect` can read them.
158
+ - `receipts/`: verification receipts.
159
+ - `last-repro.json`: the test and commit that `check` and `verify` default to.
160
+ - `last-evidence.json`: the run `explain` defaults to: the last failing one.
161
+
162
+ Installed dependencies are cached per user, outside the repository: `~/.cache/traceyard` on Linux, `~/Library/Caches/traceyard` on macOS and `%LOCALAPPDATA%\traceyard\Cache` on Windows. Set `TRACEYARD_CACHE_DIR` to move it. The 5 most recently used dependency sets are kept. Workspaces and `file:` or `link:` dependencies install inside the throwaway checkout instead, because they need the rest of the repository.
163
+
164
+ ## Supported projects
165
+
166
+ - **Vitest and Jest** through a `test` (or `test:<folder>`) script in the nearest `package.json`. npm, pnpm, Yarn and Bun are detected from `packageManager` or the lockfile, including monorepos.
167
+ - **Pytest** files named `test_*.py` or `*_test.py`, with a `requirements.txt` or `requirements-test.txt` beside them. Traceyard uses `TRACEYARD_PYTHON`, then an active virtualenv, then `.venv` or `venv` in the repository, then `python3` on `PATH`. The interpreter needs pytest installed.
168
+
169
+ ## Coding agents (MCP)
170
+
171
+ `traceyard mcp` serves six tools over stdio to any MCP client. They run on your machine with no account. They return the same envelope as the hosted server: `status` holds the verdict, and the `outputChars` budget (default 4,000) bounds every response.
172
+
173
+ | Tool | Same as | Use |
174
+ | ----------- | ------------------- | --------------------------------------------------------------------------------------- |
175
+ | `reproduce` | `traceyard repro` | Rerun the failing test at the exact commit, or at the commit a GitHub Actions job used. |
176
+ | `check` | `traceyard check` | Run it against the working tree after each fix attempt. |
177
+ | `verify` | `traceyard verify` | Prove the committed fix and write a receipt. |
178
+ | `guard` | `traceyard guard` | Before claiming "fixed": `FIXED` only if HEAD has an intact FIXED receipt. |
179
+ | `explain` | `traceyard explain` | The first failure, the line it points to, and the source around it. |
180
+ | `inspect` | `traceyard inspect` | Recent runs and receipts, a run's full log in slices, or a receipt's Markdown. |
181
+
182
+ Each tool takes an optional `repo` (absolute path). It defaults to the directory the server started in, or to `--repo`.
183
+
184
+ **Claude Code**
185
+
186
+ ```bash
187
+ claude mcp add traceyard -- npx -y traceyard mcp
188
+ ```
189
+
190
+ **Cursor** (`.cursor/mcp.json`) and other clients that use `mcpServers`:
191
+
192
+ ```json
193
+ { "mcpServers": { "traceyard": { "command": "npx", "args": ["-y", "traceyard", "mcp"] } } }
194
+ ```
195
+
196
+ **VS Code with GitHub Copilot** (`.vscode/mcp.json`):
197
+
198
+ ```json
199
+ {
200
+ "servers": {
201
+ "traceyard": { "type": "stdio", "command": "npx", "args": ["-y", "traceyard", "mcp"] }
202
+ }
203
+ }
204
+ ```
205
+
206
+ **Codex** (`~/.codex/config.toml`):
207
+
208
+ ```toml
209
+ [mcp_servers.traceyard]
210
+ command = "npx"
211
+ args = ["-y", "traceyard", "mcp"]
212
+ ```
213
+
214
+ Before the npm release, replace `npx -y traceyard` with `node /path/to/traceyard/packages/cli/bin/traceyard.mjs`.
215
+
216
+ ### Token budget
217
+
218
+ Every tool response is under 1,500 tokens. The tests check this on each call, and `node scripts/bench-cli.mjs` records it in [`docs/benchmarks/cli-agent.json`](https://github.com/fysaio/traceyard/blob/main/docs/benchmarks/cli-agent.json). On the benchmark repository (10 Vitest cases, 7 failing), the full loop costs about 1,900 tokens across eight calls: reproduce, reproduce again, explain, two inspects, check, verify and guard. The largest single call is `verify` at about 470 tokens. A repeated `reproduce` at the same commit returns in about 70 ms from the cache.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/main.mjs";
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,5 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "type": "module",
4
+ "private": true
5
+ }
@@ -0,0 +1,73 @@
1
+ // Output shaping for people and agents. Everything an agent reads passes
2
+ // through here, so it stays small and free of terminal noise.
3
+
4
+ // CSI sequences (colours, cursor moves) and OSC sequences (hyperlinks, titles).
5
+ /* eslint-disable no-control-regex */
6
+ const ANSI =
7
+ /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g;
8
+ /* eslint-enable no-control-regex */
9
+ const WORKTREE = /(?:file:\/\/)?[^\s'"()]*traceyard-worktree-[^/\\]+[/\\]checkout[/\\]/g;
10
+
11
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12
+
13
+ /** Make paths repository-relative: throwaway checkouts and, when given, the clone itself. */
14
+ export function relativePaths(text, root) {
15
+ let out = text.replace(WORKTREE, "");
16
+ if (root) {
17
+ const forward = root.split("\\").join("/");
18
+ for (const prefix of new Set([root, forward]))
19
+ out = out.replace(new RegExp(`(?:file:///?)?${escapeRegExp(prefix)}[/\\\\]`, "g"), "");
20
+ }
21
+ return out;
22
+ }
23
+
24
+ /**
25
+ * Terminal output as plain text: no ANSI codes, carriage-return progress bars
26
+ * collapsed to their final state, repeated lines and runs of blank lines
27
+ * folded into one.
28
+ */
29
+ export function cleanOutput(text, root) {
30
+ const lines = relativePaths(String(text ?? "").replace(ANSI, ""), root)
31
+ .replace(/\r\n/g, "\n")
32
+ .split("\n")
33
+ .map((line) => (line.includes("\r") ? (line.split("\r").findLast((p) => p) ?? "") : line))
34
+ .map((line) => line.trimEnd());
35
+ const kept = [];
36
+ let repeats = 0;
37
+ for (const line of lines) {
38
+ const previous = kept.at(-1);
39
+ if (previous !== undefined && line === previous) {
40
+ if (line) repeats++;
41
+ continue;
42
+ }
43
+ if (repeats)
44
+ kept.push(` (previous line repeated ${repeats} more time${repeats > 1 ? "s" : ""})`);
45
+ repeats = 0;
46
+ kept.push(line);
47
+ }
48
+ if (repeats)
49
+ kept.push(` (previous line repeated ${repeats} more time${repeats > 1 ? "s" : ""})`);
50
+ while (kept.length && !kept[0]) kept.shift();
51
+ while (kept.length && !kept.at(-1)) kept.pop();
52
+ return kept.join("\n");
53
+ }
54
+
55
+ /**
56
+ * Shorten a failure message: clean it, drop stack frames inside node_modules
57
+ * and Node internals, and keep only the first frame in the project.
58
+ */
59
+ export function compactFailure(message, root) {
60
+ const kept = [];
61
+ let frames = 0;
62
+ for (const line of cleanOutput(message, root).split("\n")) {
63
+ if (/^\s+at\s/.test(line)) {
64
+ if (/node_modules|node:internal|<anonymous>|\(native\)/.test(line) || frames >= 1) continue;
65
+ frames++;
66
+ }
67
+ kept.push(line);
68
+ }
69
+ return kept.join("\n");
70
+ }
71
+
72
+ /** Rough token count used for budgets and benchmarks: about four characters per token. */
73
+ export const estimateTokens = (text) => Math.ceil(String(text).length / 4);
@@ -0,0 +1,9 @@
1
+ /** The command line was wrong. Exit code 64. */
2
+ export class UsageError extends Error {
3
+ name = "UsageError";
4
+ }
5
+
6
+ /** The input was right but the test could not run here. Verdict BLOCKED, exit code 3. */
7
+ export class BlockedError extends Error {
8
+ name = "BlockedError";
9
+ }
@@ -0,0 +1,81 @@
1
+ import { execFile } from "node:child_process";
2
+ import { realpath } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+
5
+ const run = promisify(execFile);
6
+
7
+ export async function git(cwd, args, { timeoutMs = 15000 } = {}) {
8
+ const { stdout } = await run("git", args, {
9
+ cwd,
10
+ timeout: timeoutMs,
11
+ maxBuffer: 8 * 1024 * 1024,
12
+ });
13
+ return stdout.trim();
14
+ }
15
+
16
+ /** The top of the git repository that contains `cwd`. */
17
+ export async function repositoryRoot(cwd) {
18
+ try {
19
+ // Real paths, so Windows short names (RUNNER~1) and symlinked temp dirs
20
+ // compare equal to the long path git reports.
21
+ return await realpath(await git(cwd, ["rev-parse", "--show-toplevel"]));
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /** Resolve a ref to its full SHA, or null if this clone does not have it. */
28
+ export async function resolveCommit(repo, ref) {
29
+ try {
30
+ return await git(repo, ["rev-parse", "--verify", "--quiet", ref + "^{commit}"]);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /** Files that differ between two commits, as repository-relative paths. */
37
+ export async function changedFiles(repo, from, to) {
38
+ const out = await git(repo, ["diff", "--name-only", "--no-renames", from, to], {
39
+ timeoutMs: 60000,
40
+ });
41
+ return out ? out.split("\n").filter(Boolean) : [];
42
+ }
43
+
44
+ /** True when tracked files have uncommitted changes. Untracked files are ignored. */
45
+ export async function hasUncommittedChanges(repo) {
46
+ const out = await git(repo, ["status", "--porcelain", "--untracked-files=no"]);
47
+ return out.length > 0;
48
+ }
49
+
50
+ /** "owner/name" for the origin remote when it points at GitHub, otherwise null. */
51
+ export async function githubRepository(repo) {
52
+ let url;
53
+ try {
54
+ url = await git(repo, ["remote", "get-url", "origin"]);
55
+ } catch {
56
+ return null;
57
+ }
58
+ const match = url.match(/github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/i);
59
+ return match?.[1] ?? null;
60
+ }
61
+
62
+ /** Full SHA of HEAD, or null in a repository with no commits. */
63
+ export async function headCommit(repo) {
64
+ return resolveCommit(repo, "HEAD");
65
+ }
66
+
67
+ /**
68
+ * A file's contents at a commit (or in the working tree when commit is null).
69
+ * Null when the file doesn't exist there or isn't inside the repository.
70
+ */
71
+ export async function showFile(repo, commit, path) {
72
+ if (!path || path.startsWith("/") || path.split("/").includes("..")) return null;
73
+ try {
74
+ if (commit) return await git(repo, ["show", `${commit}:${path}`], { timeoutMs: 15000 });
75
+ const { readFile } = await import("node:fs/promises");
76
+ const { join } = await import("node:path");
77
+ return await readFile(join(repo, path), "utf8");
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
@@ -0,0 +1,137 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import {
4
+ failingTestsFromLog,
5
+ parseActionsUrl,
6
+ readCheckoutRevision,
7
+ } from "../../core/src/ci-link.mjs";
8
+ import { UsageError, BlockedError } from "./errors.mjs";
9
+
10
+ const run = promisify(execFile);
11
+
12
+ /**
13
+ * How to reach the GitHub API: a token from GITHUB_TOKEN or GH_TOKEN, else an
14
+ * authenticated `gh` CLI, else anonymous requests (public repositories only).
15
+ */
16
+ export async function githubAuth(env = process.env) {
17
+ const token = env.GITHUB_TOKEN || env.GH_TOKEN;
18
+ if (token) return { kind: "token", token };
19
+ try {
20
+ await run("gh", ["auth", "status", "--hostname", "github.com"], { timeout: 5000 });
21
+ return { kind: "gh" };
22
+ } catch {
23
+ return { kind: "anonymous" };
24
+ }
25
+ }
26
+
27
+ const refused = (auth) =>
28
+ new BlockedError(
29
+ auth.kind === "anonymous"
30
+ ? "GitHub needs a token to read this Actions run. Set GITHUB_TOKEN or sign in with `gh auth login`."
31
+ : "GitHub refused access to this Actions run. Check that your token can read the repository.",
32
+ );
33
+
34
+ function client(auth, fetcher) {
35
+ if (auth.kind === "gh")
36
+ return {
37
+ async request(path, kind) {
38
+ const call = (extra = []) =>
39
+ run("gh", ["api", ...extra, path], { timeout: 60000, maxBuffer: 64 * 1024 * 1024 });
40
+ try {
41
+ let result;
42
+ try {
43
+ result = await call();
44
+ } catch (error) {
45
+ // Newer gh refuses to print job logs (which contain ANSI colors) without this flag.
46
+ if (!/escape sequences/.test(String(error.stderr ?? ""))) throw error;
47
+ result = await call(["--allow-escape-sequences"]);
48
+ }
49
+ return kind === "text" ? result.stdout : JSON.parse(result.stdout);
50
+ } catch (error) {
51
+ if (/HTTP 40[134]/.test(String(error.stderr ?? error.message))) throw refused(auth);
52
+ throw new BlockedError(
53
+ "The gh CLI could not read the Actions run: " +
54
+ String(error.stderr ?? error.message)
55
+ .trim()
56
+ .slice(0, 300),
57
+ );
58
+ }
59
+ },
60
+ };
61
+ const headers = {
62
+ accept: "application/vnd.github+json",
63
+ "user-agent": "traceyard-cli",
64
+ "x-github-api-version": "2022-11-28",
65
+ ...(auth.token ? { authorization: "Bearer " + auth.token } : {}),
66
+ };
67
+ return {
68
+ async request(path, kind) {
69
+ const response = await fetcher("https://api.github.com" + path, { headers });
70
+ if ([401, 403, 404].includes(response.status)) throw refused(auth);
71
+ if (!response.ok)
72
+ throw new BlockedError(`GitHub returned ${response.status} for the Actions run.`);
73
+ return kind === "text" ? response.text() : response.json();
74
+ },
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Turn a GitHub Actions link into the exact commit the job tested and the test
80
+ * files that failed in it. `repository` is the local clone's GitHub "owner/name".
81
+ */
82
+ export async function resolveActionsLink(
83
+ url,
84
+ repository,
85
+ { auth = { kind: "anonymous" }, fetcher = globalThis.fetch } = {},
86
+ ) {
87
+ const link = parseActionsUrl(url);
88
+ if (!link)
89
+ throw new UsageError(
90
+ "Pass a GitHub Actions run or job link, like https://github.com/owner/repo/actions/runs/123/job/456.",
91
+ );
92
+ if (repository && link.repository.toLowerCase() !== repository.toLowerCase())
93
+ throw new UsageError(
94
+ `This link is for ${link.repository}, but this clone's origin is ${repository}.`,
95
+ );
96
+ const api = client(auth, fetcher);
97
+ const gh = {
98
+ json: (path) => api.request(path, "json"),
99
+ text: (path) => api.request(path, "text"),
100
+ };
101
+ const base = `/repos/${link.repository}/actions`;
102
+ let jobId = link.jobId;
103
+ if (!jobId) {
104
+ const runInfo = await gh.json(
105
+ `${base}/runs/${link.runId}${link.attempt ? `/attempts/${link.attempt}` : ""}`,
106
+ );
107
+ const attempt = link.attempt ?? String(runInfo.run_attempt);
108
+ const { jobs } = await gh.json(
109
+ `${base}/runs/${link.runId}/attempts/${attempt}/jobs?per_page=100`,
110
+ );
111
+ const failed = jobs.filter((job) => ["failure", "timed_out"].includes(job.conclusion ?? ""));
112
+ if (failed.length !== 1)
113
+ throw new UsageError(
114
+ failed.length
115
+ ? "More than one job failed in this run. Open the job that ran the test and pass its link."
116
+ : "No job failed in this run. Pass the link of the job that ran the failing test.",
117
+ );
118
+ jobId = String(failed[0].id);
119
+ }
120
+ const job = await gh.json(`${base}/jobs/${jobId}`);
121
+ if (String(job.run_id) !== link.runId)
122
+ throw new UsageError("This job does not belong to the linked Actions run.");
123
+ if (job.status !== "completed")
124
+ throw new BlockedError("This CI job has not finished yet. Try again when it completes.");
125
+ const log = await gh.text(`${base}/jobs/${jobId}/logs`);
126
+ const checkout = readCheckoutRevision(log, link.repository);
127
+ if (!checkout)
128
+ throw new BlockedError(
129
+ "Traceyard could not find a single checkout in this job's log. Pass the tested commit with --at instead.",
130
+ );
131
+ return {
132
+ commit: checkout.commit,
133
+ mergeCommit: checkout.merge,
134
+ failingTests: failingTestsFromLog(log),
135
+ jobUrl: `https://github.com/${link.repository}/actions/runs/${link.runId}/job/${jobId}`,
136
+ };
137
+ }