pr-evidence 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 Dylan Brine
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,116 @@
1
- # Temporary Holding Version
1
+ # pr-evidence
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
+ Test a branch in a real browser and post screenshots and a GIF as evidence on its pull request.
4
+
5
+ You ask your coding agent to gather evidence. It works out what to test from the diff, the PR description and the ticket, and you approve the list. It then drives a real browser against your running app and judges each criterion. You review the evidence, and one comment on the PR is created or updated.
6
+
7
+ The tool only reports. It never changes the code under test.
8
+
9
+ Web apps only, on github.com and `*.ghe.com`. macOS and Linux.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npx pr-evidence setup
15
+ ```
16
+
17
+ The `npx` examples require a published release containing these changes. Until then, build this checkout with `npm ci` and `npm run build`, then use `node /absolute/path/to/pr-evidence/dist/cli.js setup`. For helper commands, run that CLI from the Git repository being tested. The installed skill also invokes `npx`, so using it requires the published release.
18
+
19
+ This installs the skill at user level for each agent it finds, and tells you if a prerequisite is missing:
20
+
21
+ | Agent | Skill location |
22
+ | --- | --- |
23
+ | Claude Code | `~/.claude/skills/pr-evidence` |
24
+ | Codex | `~/.agents/skills/pr-evidence` |
25
+ | Cursor | `~/.cursor/skills/pr-evidence` |
26
+
27
+ Use `--agent claude`, `--agent codex` or `--agent cursor` to choose instead.
28
+
29
+ You need Node 20 or later, npm, Git, a Unix environment with `sh`, `ps` and process group signals, the [GitHub CLI](https://cli.github.com) logged in with `gh auth login`, and `chrome-devtools-axi` (`npm install -g chrome-devtools-axi`). You do not need ffmpeg or ImageMagick.
30
+
31
+ ## Configure a repo
32
+
33
+ Commit a `.pr-evidence.yml`. Your agent offers to draft it the first time.
34
+
35
+ ```yaml
36
+ start: npm run dev # starts the app
37
+ readyUrl: http://localhost:3000 # answers once the app is up
38
+ login: # optional: names of env vars, never the values
39
+ usernameEnv: APP_TEST_USER
40
+ passwordEnv: APP_TEST_PASSWORD
41
+ ticketFolder: docs/tickets # optional: local Markdown tickets
42
+ ```
43
+
44
+ The start command must stay in the foreground, so use `docker compose up` rather than `docker compose up -d`. If it exits during startup, even with status 0, `start` fails. An app it leaves running in the background is not tracked or stopped.
45
+
46
+ Without a config, pass `--url` to test an app that is already running or a preview deployment. An existing config is still validated, and the external app is never stopped by this tool.
47
+
48
+ ## Use it
49
+
50
+ Ask your agent, for example:
51
+
52
+ > Gather evidence for this branch.
53
+
54
+ > Gather evidence for ABC-123 with --criteria "Saving twice does not create a duplicate".
55
+
56
+ | Option | Effect |
57
+ | --- | --- |
58
+ | `--ticket <path or key>` | Use this ticket |
59
+ | `--criteria "<text>"` | Add a criterion (repeatable) |
60
+ | `--criteria-file <path>` | Add criteria from a file |
61
+ | `--url <url>` | Test an app that is already running |
62
+ | `--allow-dirty` | Run with uncommitted changes. The evidence is marked |
63
+ | `--yes` | Skip the review before publishing |
64
+
65
+ ## Logging in
66
+
67
+ By default you log in once by hand, in a browser profile kept for this tool, and runs reuse that session. MFA and SSO work, and the agent never sees your password. For simple apps, test credentials can come from the env vars named in the config instead.
68
+
69
+ The tool never uses your day-to-day browser profile.
70
+
71
+ ## Before you publish
72
+
73
+ - GitHub offers no supported way to delete an uploaded file, so check the screenshots before you approve them.
74
+ - Use local or seeded data, not production.
75
+ - Files uploaded to a private repo need repository access to view.
76
+ - Publishing requires repository write access and an OAuth or personal access token from `gh`. GitHub App and Actions tokens are refused. For Enterprise Cloud, log in with `gh auth login --hostname <host>`.
77
+ - Push the tested commit first. Publishing refuses a commit that is not on GitHub, before uploading anything.
78
+ - If the commit is on GitHub but is not the PR head, the evidence is still posted, with the warning "The PR head differs from the tested commit".
79
+ - PRs from forks are not found.
80
+ - Each person who publishes on a PR gets their own evidence comment, so nobody can edit another person's evidence.
81
+
82
+ Evidence is saved in `~/.pr-evidence/<repository-key>/<sha>/`. On `start`, runs whose records have not changed in 14 days are pruned, except those with a live app owned by this tool. Running the same commit again replaces its earlier evidence. If the branch has no PR yet, the evidence is kept subject to that retention rule. After opening a PR, run `npx pr-evidence publish`: it prefers a finished run for the checked-out commit, otherwise selects this checkout's latest run, which must be finished. It finds the PR using the selected run's saved branch and origin repository.
83
+
84
+ To test two branches at once, use separate `git worktree` checkouts. Their apps and runs stay apart when testing different commits. The same commit can have only one unfinished run across checkouts: start exits 2 without changing evidence if another checkout owns that run. Finish it in its owning checkout first; starting the commit elsewhere then replaces its evidence. Stop and finish ignore runs owned by another checkout. Worktrees share a saved browser profile, so run the browser steps one at a time.
85
+
86
+ ## Helper commands
87
+
88
+ The skill runs these for you. Each prints one JSON document. The exit code is 0 for success, 1 when a criterion failed and 2 when the tool itself failed.
89
+
90
+ | Command | Purpose |
91
+ | --- | --- |
92
+ | `setup` | Install the skill and check prerequisites |
93
+ | `start` | Begin a run for the current commit |
94
+ | `finish --results <file>` | Stop the app, record results and build the GIF |
95
+ | `stop` | Abandon a run |
96
+ | `publish` | Publish saved evidence as described above |
97
+
98
+ `finish` reports GIF encoding or size-limit failures as warnings and keeps the results and screenshots, with `gifPath: null`. Review those warnings before publishing.
99
+
100
+ ## How the upload works
101
+
102
+ GitHub has no documented API for this. The upload uses the endpoint behind the comment box, authenticated with your `gh` token, so it could change without notice. `npm run test:smoke` checks it with one real upload, which cannot be deleted afterwards.
103
+
104
+ PNG and GIF uploads must be nonempty and at most 10 MiB each. All files are uploaded before the PR comment is changed. If a later upload fails, earlier uploaded assets may remain even though the comment is untouched. A comment request failure can leave publication uncertain; inspect the PR before retrying.
105
+
106
+ The upload contract follows [no-mistakes](https://github.com/kunchenguid/no-mistakes) (MIT).
107
+
108
+ ## Development
109
+
110
+ ```sh
111
+ npm install
112
+ npm test
113
+ npm run typecheck
114
+ ```
115
+
116
+ The regular tests run the built CLI as a black box, against real git repos, a real HTTP server and a local fake of GitHub. The opt-in upload smoke test imports `src` directly.
@@ -0,0 +1,171 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { once } from "node:events";
3
+ import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ import { CliError } from "./errors.js";
6
+ const defaultReadyTimeoutMilliseconds = 120_000;
7
+ const readyPollMilliseconds = 250;
8
+ const probeTimeoutMilliseconds = 2_000;
9
+ const stopGraceMilliseconds = 5_000;
10
+ const stopPollMilliseconds = 50;
11
+ const appOutputCharacters = 4_000;
12
+ function readyTimeoutMilliseconds() {
13
+ const override = Number(process.env.PR_EVIDENCE_READY_TIMEOUT_MS);
14
+ return override > 0 ? override : defaultReadyTimeoutMilliseconds;
15
+ }
16
+ /** The HTTP status from `url`, or null when nothing answered. */
17
+ export async function probeUrl(url, signal) {
18
+ const cancellation = new AbortController();
19
+ const cancel = () => cancellation.abort(signal?.reason);
20
+ const timeout = setTimeout(() => cancellation.abort(), probeTimeoutMilliseconds);
21
+ timeout.unref();
22
+ signal?.addEventListener("abort", cancel, { once: true });
23
+ if (signal?.aborted)
24
+ cancel();
25
+ try {
26
+ const response = await fetch(url, {
27
+ signal: cancellation.signal,
28
+ redirect: "manual",
29
+ });
30
+ await response.body?.cancel();
31
+ return response.status;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ finally {
37
+ clearTimeout(timeout);
38
+ signal?.removeEventListener("abort", cancel);
39
+ }
40
+ }
41
+ function readProcessStartTime(processId) {
42
+ try {
43
+ const startTime = execFileSync("ps", ["-o", "lstart=", "-p", String(processId)], {
44
+ encoding: "utf8",
45
+ stdio: ["ignore", "pipe", "ignore"],
46
+ }).trim();
47
+ return startTime === "" ? null : startTime;
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ function readAppOutput(logPath) {
54
+ if (!existsSync(logPath))
55
+ return "";
56
+ const descriptor = openSync(logPath, "r");
57
+ try {
58
+ const size = fstatSync(descriptor).size;
59
+ const buffer = Buffer.alloc(Math.min(size, appOutputCharacters * 4));
60
+ const position = size - buffer.length;
61
+ let bytesRead = 0;
62
+ while (bytesRead < buffer.length) {
63
+ const count = readSync(descriptor, buffer, bytesRead, buffer.length - bytesRead, position + bytesRead);
64
+ if (count === 0)
65
+ break;
66
+ bytesRead += count;
67
+ }
68
+ return buffer.subarray(0, bytesRead).toString("utf8").slice(-appOutputCharacters);
69
+ }
70
+ finally {
71
+ closeSync(descriptor);
72
+ }
73
+ }
74
+ function isProcessGroupAlive(processGroupId) {
75
+ try {
76
+ process.kill(-processGroupId, 0);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ return error.code === "EPERM";
81
+ }
82
+ }
83
+ async function waitUntilReady(url, child, logPath, signal) {
84
+ const deadline = Date.now() + readyTimeoutMilliseconds();
85
+ let status = null;
86
+ while (true) {
87
+ signal.throwIfAborted();
88
+ if (child.exitCode !== null || child.signalCode !== null) {
89
+ const exit = child.signalCode === null ? `code ${child.exitCode}` : `signal ${child.signalCode}`;
90
+ throw new CliError("app_exited", `The start command exited with ${exit}. The command must stay in the foreground; detached apps it leaves behind are not managed.`, { appOutput: readAppOutput(logPath) });
91
+ }
92
+ if (status !== null && status < 500) {
93
+ return;
94
+ }
95
+ if (Date.now() >= deadline) {
96
+ throw new CliError("app_not_ready", `${url} was not ready within ${readyTimeoutMilliseconds() / 1000} seconds.`, { appOutput: readAppOutput(logPath) });
97
+ }
98
+ status = await probeUrl(url, signal);
99
+ if (status === null || status >= 500) {
100
+ await sleep(readyPollMilliseconds, undefined, { signal });
101
+ }
102
+ }
103
+ }
104
+ /**
105
+ * Starts the app in its own process group. `onStarted` runs as soon as the
106
+ * process exists, so it can be recorded and stopped even if readiness fails.
107
+ */
108
+ export async function startApp(command, options) {
109
+ const logDescriptor = openSync(options.logPath, "a");
110
+ const child = spawn("sh", ["-c", command], {
111
+ cwd: options.cwd,
112
+ detached: true,
113
+ stdio: ["ignore", logDescriptor, logDescriptor],
114
+ });
115
+ closeSync(logDescriptor);
116
+ const cancellation = new AbortController();
117
+ const interrupt = (signal) => cancellation.abort(new CliError("app_interrupted", `Startup interrupted by ${signal}.`));
118
+ const onInterrupt = () => interrupt("SIGINT");
119
+ const onTerminate = () => interrupt("SIGTERM");
120
+ process.on("SIGINT", onInterrupt);
121
+ process.on("SIGTERM", onTerminate);
122
+ let app;
123
+ try {
124
+ try {
125
+ await once(child, "spawn");
126
+ }
127
+ catch (error) {
128
+ throw new CliError("app_exited", `Could not launch the start command: ${command}. ${String(error)}`);
129
+ }
130
+ const processId = child.pid;
131
+ app = { processId, processStartTime: readProcessStartTime(processId) };
132
+ options.onStarted(app);
133
+ await waitUntilReady(options.readyUrl, child, options.logPath, cancellation.signal);
134
+ cancellation.signal.throwIfAborted();
135
+ child.unref();
136
+ }
137
+ catch (error) {
138
+ if (app) {
139
+ await stopApp(app);
140
+ options.onStopped();
141
+ }
142
+ throw cancellation.signal.aborted ? cancellation.signal.reason : error;
143
+ }
144
+ finally {
145
+ process.off("SIGINT", onInterrupt);
146
+ process.off("SIGTERM", onTerminate);
147
+ }
148
+ }
149
+ export function isAppRunning(app) {
150
+ if (!isProcessGroupAlive(app.processId)) {
151
+ return false;
152
+ }
153
+ const currentStartTime = readProcessStartTime(app.processId);
154
+ return currentStartTime === null || currentStartTime === app.processStartTime;
155
+ }
156
+ /** Stops the process group, and only if it is still the one that was started. */
157
+ export async function stopApp(app) {
158
+ if (!isAppRunning(app)) {
159
+ return false;
160
+ }
161
+ process.kill(-app.processId, "SIGTERM");
162
+ const deadline = Date.now() + stopGraceMilliseconds;
163
+ while (Date.now() < deadline) {
164
+ if (!isProcessGroupAlive(app.processId)) {
165
+ return true;
166
+ }
167
+ await sleep(stopPollMilliseconds);
168
+ }
169
+ process.kill(-app.processId, "SIGKILL");
170
+ return true;
171
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { finish } from "./commands/finish.js";
4
+ import { publish } from "./commands/publish.js";
5
+ import { setup } from "./commands/setup.js";
6
+ import { start } from "./commands/start.js";
7
+ import { stopLatestRunApp } from "./commands/stop.js";
8
+ import { CliError } from "./errors.js";
9
+ import { helperVersion } from "./packageInfo.js";
10
+ import { readRepoState } from "./repoState.js";
11
+ const failedCriteriaExitCode = 1;
12
+ const toolFailureExitCode = 2;
13
+ const commands = [
14
+ { usage: "setup [--agent claude|codex|cursor]...", description: "Install the skill and check prerequisites." },
15
+ { usage: "start [--url <url>] [--allow-dirty] [--skill-version <version>]", description: "Begin a run for the current commit, starting the configured app unless --url is given." },
16
+ { usage: "finish --results <file>", description: "Stop the app, record the results and build the GIF. Exits 1 if a criterion failed." },
17
+ { usage: "stop", description: "Abandon a run, stopping any app it started." },
18
+ { usage: "publish", description: "Prefer the checked-out commit's finished run, otherwise use this checkout's latest run, which must be finished; upload it and update the evidence comment on its PR." },
19
+ ];
20
+ function print(document) {
21
+ process.stdout.write(`${JSON.stringify(document, null, 2)}\n`);
22
+ }
23
+ async function runCommand(argv) {
24
+ const [command, ...commandArgs] = argv;
25
+ switch (command) {
26
+ case "--version":
27
+ case "-v":
28
+ return { version: helperVersion };
29
+ case undefined:
30
+ case "--help":
31
+ case "-h":
32
+ return { commands };
33
+ case "setup": {
34
+ const { values } = parseArgs({
35
+ args: commandArgs,
36
+ options: { agent: { type: "string", multiple: true, default: [] } },
37
+ });
38
+ return setup(values.agent);
39
+ }
40
+ case "start": {
41
+ const { values } = parseArgs({
42
+ args: commandArgs,
43
+ options: {
44
+ "allow-dirty": { type: "boolean", default: false },
45
+ url: { type: "string" },
46
+ "skill-version": { type: "string" },
47
+ },
48
+ });
49
+ return start({
50
+ repositoryPath: process.cwd(),
51
+ allowDirty: values["allow-dirty"],
52
+ url: values.url,
53
+ skillVersion: values["skill-version"],
54
+ });
55
+ }
56
+ case "finish": {
57
+ const { values } = parseArgs({
58
+ args: commandArgs,
59
+ options: { results: { type: "string" } },
60
+ });
61
+ if (values.results === undefined) {
62
+ throw new CliError("usage", "finish needs --results <file>.");
63
+ }
64
+ const outcome = await finish(process.cwd(), values.results);
65
+ if (outcome.result === "fail") {
66
+ process.exitCode = failedCriteriaExitCode;
67
+ }
68
+ return { ...outcome };
69
+ }
70
+ case "publish":
71
+ return publish(process.cwd());
72
+ case "stop":
73
+ return {
74
+ stopped: await stopLatestRunApp(readRepoState(process.cwd())),
75
+ };
76
+ default:
77
+ throw new CliError("unknown_command", `Unknown command: ${command}`);
78
+ }
79
+ }
80
+ function toCliError(error) {
81
+ if (error instanceof CliError) {
82
+ return error;
83
+ }
84
+ const isUsageError = String(error.code).startsWith("ERR_PARSE_ARGS");
85
+ return isUsageError
86
+ ? new CliError("usage", error.message)
87
+ : new CliError("unexpected_error", String(error));
88
+ }
89
+ try {
90
+ print({ ok: true, ...(await runCommand(process.argv.slice(2))) });
91
+ }
92
+ catch (error) {
93
+ const failure = toCliError(error);
94
+ print({
95
+ ok: false,
96
+ error: { code: failure.code, message: failure.message, ...failure.details },
97
+ });
98
+ process.exitCode = toolFailureExitCode;
99
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CliError } from "../errors.js";
4
+ import { findLatestRun, gifPathOf, listScreenshots, screenshotDirectoryOf, writeRunRecord, } from "../evidenceStore.js";
5
+ import { buildGif } from "../gifBuilder.js";
6
+ import { readRepoState } from "../repoState.js";
7
+ import { stopLatestRunApp } from "./stop.js";
8
+ function invalid(problem) {
9
+ return new CliError("results_invalid", `Results file: ${problem}`);
10
+ }
11
+ function parseCriterion(value, screenshots) {
12
+ const { description, result, screenshot, note } = (value ?? {});
13
+ if (typeof description !== "string" || description.trim() === "") {
14
+ throw invalid('every criterion needs a "description".');
15
+ }
16
+ if (result !== "pass" && result !== "fail") {
17
+ throw invalid(`"${description}" needs a result of "pass" or "fail".`);
18
+ }
19
+ if (note !== undefined && typeof note !== "string") {
20
+ throw invalid(`"${description}" has a note that is not a string.`);
21
+ }
22
+ if (screenshot === undefined) {
23
+ return { description, result, note };
24
+ }
25
+ if (typeof screenshot !== "string" || !screenshots.includes(screenshot)) {
26
+ throw invalid(`"${description}" names screenshot ${screenshot}, which was not captured.`);
27
+ }
28
+ return { description, result, screenshot, note };
29
+ }
30
+ function parseResults(resultsPath, screenshots) {
31
+ let document;
32
+ try {
33
+ document = JSON.parse(readFileSync(resultsPath, "utf8"));
34
+ }
35
+ catch (cause) {
36
+ throw invalid(`could not read ${resultsPath}: ${String(cause)}`);
37
+ }
38
+ if (!Array.isArray(document?.criteria) || document.criteria.length === 0) {
39
+ throw invalid('"criteria" must list at least one criterion.');
40
+ }
41
+ const ticket = document.ticket ?? null;
42
+ if (ticket !== null && typeof ticket !== "string") {
43
+ throw invalid('"ticket" must be a string or null.');
44
+ }
45
+ return {
46
+ ticket,
47
+ criteria: document.criteria.map((criterion) => parseCriterion(criterion, screenshots)),
48
+ };
49
+ }
50
+ /** A GIF failure must not cost the run its evidence, so it is a warning here. */
51
+ function tryBuildGif(runDirectory, screenshots, warnings) {
52
+ if (screenshots.length === 0) {
53
+ return null;
54
+ }
55
+ const gifPath = gifPathOf(runDirectory);
56
+ try {
57
+ buildGif(screenshots.map((fileName) => join(screenshotDirectoryOf(runDirectory), fileName)), gifPath);
58
+ return gifPath;
59
+ }
60
+ catch (error) {
61
+ if (!(error instanceof CliError)) {
62
+ throw error;
63
+ }
64
+ warnings.push(`No GIF was built. ${error.message}`);
65
+ return null;
66
+ }
67
+ }
68
+ export async function finish(repositoryPath, resultsPath) {
69
+ const repoState = readRepoState(repositoryPath);
70
+ const run = findLatestRun(repoState);
71
+ if (run === null) {
72
+ throw new CliError("no_run", "There is no run to finish. Use start first.");
73
+ }
74
+ await stopLatestRunApp(repoState);
75
+ const screenshots = listScreenshots(run.directory);
76
+ const { ticket, criteria } = parseResults(resultsPath, screenshots);
77
+ const warnings = [];
78
+ const gifPath = tryBuildGif(run.directory, screenshots, warnings);
79
+ const outcome = {
80
+ result: criteria.every((criterion) => criterion.result === "pass") ? "pass" : "fail",
81
+ ticket,
82
+ criteria,
83
+ screenshots,
84
+ gifPath,
85
+ };
86
+ writeRunRecord(run.directory, { ...findLatestRun(repoState).record, outcome });
87
+ return { ...outcome, warnings };
88
+ }
@@ -0,0 +1,77 @@
1
+ import { join } from "node:path";
2
+ import { CliError } from "../errors.js";
3
+ import { commentMarker, renderEvidenceComment } from "../evidenceComment.js";
4
+ import { findLatestRun, findRunForCommit, screenshotDirectoryOf, } from "../evidenceStore.js";
5
+ import { assertSupportedHost, GitHubClient, readUploadToken, uploadsBaseUrl, } from "../github.js";
6
+ import { readRepoState } from "../repoState.js";
7
+ import { GitHubAttachmentUploader } from "../uploader.js";
8
+ async function requirePullRequest(github, branch, runDirectory) {
9
+ const pullRequest = branch === null ? null : await github.findOpenPullRequest(branch);
10
+ if (pullRequest === null) {
11
+ throw new CliError("no_pull_request", `No open PR for ${branch ?? "this detached commit"}. The evidence is saved; open a PR and run publish again.`, { runDirectory });
12
+ }
13
+ return pullRequest;
14
+ }
15
+ async function uploadScreenshots(uploader, runDirectory, screenshots) {
16
+ const urls = new Map();
17
+ for (const fileName of screenshots) {
18
+ urls.set(fileName, await uploader.upload(join(screenshotDirectoryOf(runDirectory), fileName)));
19
+ }
20
+ return urls;
21
+ }
22
+ /** The checked-out commit's finished run, otherwise this checkout's latest run. */
23
+ function chooseRun(repoState) {
24
+ const commitRun = findRunForCommit(repoState.repositoryKey, repoState.sha);
25
+ const run = commitRun?.record.outcome ? commitRun : findLatestRun(repoState);
26
+ if (run === null) {
27
+ throw new CliError("no_run", "There is no saved run to publish.");
28
+ }
29
+ return run;
30
+ }
31
+ export async function publish(repositoryPath) {
32
+ const { directory: runDirectory, record } = chooseRun(readRepoState(repositoryPath));
33
+ const { outcome, repository } = record;
34
+ if (outcome === undefined) {
35
+ throw new CliError("run_not_finished", "The latest run has no results. Use finish first.");
36
+ }
37
+ if (repository === null) {
38
+ throw new CliError("no_github_remote", "The origin remote is not a GitHub repository.");
39
+ }
40
+ assertSupportedHost(repository.host);
41
+ const token = readUploadToken(repository.host);
42
+ const github = new GitHubClient(repository, token);
43
+ const { repositoryId, viewerLogin } = await github.readRepositoryAccess();
44
+ const pullRequest = await requirePullRequest(github, record.branch, runDirectory);
45
+ const headDiffers = pullRequest.headSha !== record.sha;
46
+ if (headDiffers && !(await github.hasCommit(record.sha))) {
47
+ throw new CliError("commit_not_on_github", `The tested commit ${record.sha} is not on GitHub. The evidence is saved; push the commit and run publish again.`, { runDirectory });
48
+ }
49
+ const uploader = new GitHubAttachmentUploader({
50
+ uploadsBaseUrl: uploadsBaseUrl(repository.host),
51
+ token,
52
+ repositoryId,
53
+ host: repository.host,
54
+ });
55
+ // Everything is uploaded before the comment is touched, so a failed upload leaves the PR as it was.
56
+ const gifUrl = outcome.gifPath === null ? null : await uploader.upload(outcome.gifPath);
57
+ const screenshotUrls = await uploadScreenshots(uploader, runDirectory, outcome.screenshots);
58
+ const body = renderEvidenceComment({
59
+ repository,
60
+ record,
61
+ outcome,
62
+ screenshotUrls,
63
+ gifUrl,
64
+ headDiffers,
65
+ });
66
+ // Author is checked as well as the marker: anyone can post the marker, and
67
+ // adopting their comment would leave them able to edit the evidence.
68
+ const existingComment = await github.findComment(pullRequest.number, (comment) => comment.user?.login === viewerLogin && comment.body.startsWith(commentMarker));
69
+ const commentUrl = existingComment
70
+ ? await github.updateComment(existingComment.id, body)
71
+ : await github.createComment(pullRequest.number, body);
72
+ return {
73
+ pullRequest: { number: pullRequest.number, url: pullRequest.url },
74
+ commentUrl,
75
+ warnings: headDiffers ? [`The PR head differs from the tested commit ${record.sha}.`] : [],
76
+ };
77
+ }
@@ -0,0 +1,43 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { CliError } from "../errors.js";
5
+ import { helperVersion, readSkillTemplate } from "../packageInfo.js";
6
+ import { findMissingPrerequisites } from "../prerequisites.js";
7
+ const agents = [
8
+ { name: "claude", detectionDirectory: ".claude", skillsDirectory: ".claude/skills" },
9
+ { name: "codex", detectionDirectory: ".codex", skillsDirectory: ".agents/skills" },
10
+ { name: "cursor", detectionDirectory: ".cursor", skillsDirectory: ".cursor/skills" },
11
+ ];
12
+ function chooseAgents(requestedNames) {
13
+ if (requestedNames.length > 0) {
14
+ return requestedNames.map((name) => {
15
+ const agent = agents.find((candidate) => candidate.name === name);
16
+ if (agent === undefined) {
17
+ const supported = agents.map((candidate) => candidate.name).join(", ");
18
+ throw new CliError("usage", `Unknown agent "${name}". Supported: ${supported}.`);
19
+ }
20
+ return agent;
21
+ });
22
+ }
23
+ const detected = agents.filter((agent) => existsSync(join(homedir(), agent.detectionDirectory)));
24
+ if (detected.length === 0) {
25
+ throw new CliError("no_agent_found", "Found no Claude Code, Codex or Cursor in your home directory. Name one with --agent.");
26
+ }
27
+ return detected;
28
+ }
29
+ export function setup(requestedAgentNames) {
30
+ const skill = readSkillTemplate().replaceAll("{{version}}", helperVersion);
31
+ const installed = chooseAgents(requestedAgentNames).map((agent) => {
32
+ const path = join(homedir(), agent.skillsDirectory, "pr-evidence", "SKILL.md");
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ writeFileSync(path, skill);
35
+ process.stderr.write(`Installed the skill for ${agent.name}: ${path}\n`);
36
+ return { agent: agent.name, path };
37
+ });
38
+ const missingPrerequisites = findMissingPrerequisites();
39
+ for (const { name, fix } of missingPrerequisites) {
40
+ process.stderr.write(`Missing ${name}. ${fix}\n`);
41
+ }
42
+ return { installed, ready: missingPrerequisites.length === 0, missingPrerequisites };
43
+ }