pr-evidence 0.1.1 → 0.2.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/README.md CHANGED
@@ -1,144 +1,69 @@
1
1
  # pr-evidence
2
2
 
3
- Test a branch in a real browser and post screenshots and a GIF as evidence on its pull request.
3
+ Your coding agent tests a branch in a real browser and posts each criterion it checked, with the screenshots that prove it, on its pull request.
4
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.
5
+ [![The evidence comment pr-evidence posted on a demo pull request: a passing result, a table of criteria and a section of screenshots for each criterion](https://github.com/debrine/pr-evidence/raw/main/docs/images/evidence-comment.png)](https://github.com/debrine/pr-evidence-demo/pull/1)
6
6
 
7
- The tool only reports. It never changes the code under test.
7
+ This comment was posted from a real run on [a demo pull request](https://github.com/debrine/pr-evidence-demo/pull/1) that fixes a double-clicked Save adding a note twice.
8
8
 
9
- Web apps only, on github.com and `*.ghe.com`. macOS and Linux.
9
+ ## How it works
10
10
 
11
- ## Install
11
+ 1. You ask your agent to gather evidence for the branch.
12
+ 2. It reads the diff, the PR description and the ticket, and proposes what to test. You approve or edit the list.
13
+ 3. It starts your app, drives a real browser against it, and judges each criterion with the screenshots that show it.
14
+ 4. You review the evidence, and one comment on the PR is created or updated.
12
15
 
13
- ```sh
14
- npx pr-evidence setup
15
- ```
16
+ <!-- TRANSCRIPT: replace with 10-15 lines trimmed from the showcase run -->
16
17
 
17
- This installs the skill at user level for each agent it finds, and tells you if a prerequisite is missing:
18
+ Each criterion gets its own section, with its note and screenshots. Passed criteria are collapsed. If a criterion fails, the comment says "Failed", marks that row "Fail" and shows that criterion's section open. The tool only reports. It never changes the code under test.
18
19
 
19
- | Agent | Skill location |
20
- | --- | --- |
21
- | Claude Code | `~/.claude/skills/pr-evidence` |
22
- | Codex | `~/.agents/skills/pr-evidence` |
23
- | Cursor | `~/.cursor/skills/pr-evidence` |
20
+ ## Quickstart
24
21
 
25
- Use `--agent claude`, `--agent codex` or `--agent cursor` to choose instead.
22
+ 1. Install the helper and the skill for your agents (Claude Code, Codex and Cursor):
26
23
 
27
- 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.
24
+ ```sh
25
+ npx pr-evidence setup
26
+ ```
28
27
 
29
- ## Configure a repo
28
+ On Windows, run `npx.cmd pr-evidence setup`. See [Windows](https://github.com/debrine/pr-evidence/blob/main/docs/windows.md).
30
29
 
31
- Commit a `.pr-evidence.yml`. Your agent offers to draft it the first time.
30
+ 2. Commit a `.pr-evidence.yml` saying how to start your app. Your agent offers to draft it the first time. The demo's is two lines:
32
31
 
33
- ```yaml
34
- start: npm run dev # starts the app
35
- readyUrl: http://localhost:3000 # answers once the app is up
36
- login: # optional: names of env vars, never the values
37
- usernameEnv: APP_TEST_USER
38
- passwordEnv: APP_TEST_PASSWORD
39
- ticketFolder: docs/tickets # optional: local Markdown tickets
40
- ```
32
+ ```yaml
33
+ start: node server.js
34
+ readyUrl: http://localhost:3000
35
+ ```
41
36
 
42
- 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.
37
+ 3. Push your branch and ask your agent:
43
38
 
44
- 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.
39
+ > Gather evidence for this branch.
45
40
 
46
- ### Apps with several processes
47
-
48
- If the app needs setup steps or more than one process, commit a wrapper script and point `start` at it, for example `start: ./scripts/evidence-start.sh`. Do the setup first, then stay in the foreground:
49
-
50
- ```sh
51
- #!/bin/sh
52
- set -e
53
- docker compose up -d --wait # services this tool will not stop
54
- npm run migrate
55
- npm run seed
56
- npm run start:api &
57
- npm run start:web &
58
- wait
59
- ```
60
-
61
- Set `readyUrl` to the part that answers last. The script has two minutes to reach it. The tool stops the script and the processes it keeps in the foreground or starts with `&`. It does not stop services that run on their own, such as those from `docker compose up -d`, so stop them with `docker compose down`. `wait` keeps the script running if only one of its processes dies, so a failure there shows up in the app rather than in `start`.
62
-
63
- For a one-off run, start the stack yourself and pass `--url`. You then own the app and stop it afterwards.
64
-
65
- ## Use it
66
-
67
- Ask your agent, for example:
41
+ ## Examples
68
42
 
69
43
  > Gather evidence for this branch.
70
44
 
71
- > Gather evidence for ABC-123 with --criteria "Saving twice does not create a duplicate".
72
-
73
- | Option | Effect |
74
- | --- | --- |
75
- | `--ticket <path or key>` | Use this ticket |
76
- | `--criteria "<text>"` | Add a criterion (repeatable) |
77
- | `--criteria-file <path>` | Add criteria from a file |
78
- | `--url <url>` | Test an app that is already running |
79
- | `--allow-dirty` | Run with uncommitted changes. The evidence is marked |
80
- | `--yes` | Skip the review before publishing |
81
-
82
- ## Logging in
83
-
84
- 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.
85
-
86
- The tool never uses your day-to-day browser profile.
87
-
88
- ## Before you publish
89
-
90
- - GitHub offers no supported way to delete an uploaded file, so check the screenshots before you approve them.
91
- - Use local or seeded data, not production.
92
- - Files uploaded to a private repo need repository access to view.
93
- - 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>`.
94
- - `start` warns if the commit is not the head of the open PR for the branch, or if it could not check, so you can stop before testing.
95
- - Push the tested commit first. Publishing refuses a commit that is not on GitHub, before uploading anything.
96
- - 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".
97
- - PRs from forks are not found.
98
- - Each person who publishes on a PR gets their own evidence comment, so nobody can edit another person's evidence.
99
-
100
- 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.
101
-
102
- 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.
103
-
104
- ## Helper commands
105
-
106
- 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.
107
-
108
- | Command | Purpose |
109
- | --- | --- |
110
- | `setup` | Install the skill and check prerequisites |
111
- | `start` | Begin a run for the current commit |
112
- | `finish --results <file>` | Stop the app, record results and build the GIF |
113
- | `stop` | Abandon a run |
114
- | `publish` | Publish saved evidence as described above |
115
-
116
- `finish` reports GIF encoding or size-limit failures as warnings and keeps the results and screenshots, with `gifPath: null`. Review those warnings before publishing.
117
-
118
- ## How the upload works
119
-
120
- 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.
121
-
122
- 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.
45
+ > Gather evidence for ABC-123.
123
46
 
124
- The upload contract follows [no-mistakes](https://github.com/kunchenguid/no-mistakes) (MIT).
47
+ > Gather evidence for this branch with --criteria "Saving twice does not create a duplicate".
125
48
 
126
- ## Development
49
+ > Gather evidence for this branch with --url https://my-branch.preview.example.com
127
50
 
128
- ```sh
129
- npm install
130
- npm test
131
- npm run typecheck
132
- ```
51
+ The options are listed in the [reference](https://github.com/debrine/pr-evidence/blob/main/docs/reference.md#options).
133
52
 
134
- To try a checkout, run `npm ci` and `npm run build`, then `node /absolute/path/to/pr-evidence/dist/cli.js setup`. Run helper commands from the Git repository being tested. The installed skill invokes `npx`, so it always uses the published release.
53
+ ## Requirements
135
54
 
136
- 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.
55
+ - Node 20 or later
56
+ - Git. On Windows, [Git for Windows](https://git-scm.com/download/win)
57
+ - The [GitHub CLI](https://cli.github.com), logged in with `gh auth login`
58
+ - A web app, with its repository on github.com or `*.ghe.com`
137
59
 
138
- ## Releasing
60
+ It runs on macOS, Linux and Windows.
139
61
 
140
- After `npm publish`, the registry can list the new version before its tarball is available. Until it is, `npx` fails with `could not determine executable to run`, and the tarball URL returns 404. For `0.1.0` this took about 8 minutes. Wait for this to succeed before testing the release:
62
+ ## Learn more
141
63
 
142
- ```sh
143
- curl -fsI "$(npm view pr-evidence@<version> dist.tarball)"
144
- ```
64
+ - [Configuration](https://github.com/debrine/pr-evidence/blob/main/docs/configuration.md): the config file, apps with several processes, testing a running app, logging in
65
+ - [Windows](https://github.com/debrine/pr-evidence/blob/main/docs/windows.md): setup, Git for Windows and how processes are stopped
66
+ - [Publishing](https://github.com/debrine/pr-evidence/blob/main/docs/publishing.md): what to check first, where evidence is kept, worktrees, how the upload works
67
+ - [Reference](https://github.com/debrine/pr-evidence/blob/main/docs/reference.md): options, helper commands and prerequisites
68
+ - [Upgrading from 0.1](https://github.com/debrine/pr-evidence/blob/main/docs/upgrading.md)
69
+ - [Contributing](https://github.com/debrine/pr-evidence/blob/main/CONTRIBUTING.md)
package/dist/appRunner.js CHANGED
@@ -1,13 +1,10 @@
1
- import { execFileSync, spawn } from "node:child_process";
2
- import { once } from "node:events";
3
1
  import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
4
2
  import { setTimeout as sleep } from "node:timers/promises";
5
3
  import { CliError } from "./errors.js";
4
+ import { launchProcess, stopProcess, } from "./processControl.js";
6
5
  const defaultReadyTimeoutMilliseconds = 120_000;
7
6
  const readyPollMilliseconds = 250;
8
7
  const probeTimeoutMilliseconds = 2_000;
9
- const stopGraceMilliseconds = 5_000;
10
- const stopPollMilliseconds = 50;
11
8
  const appOutputCharacters = 4_000;
12
9
  function readyTimeoutMilliseconds() {
13
10
  const override = Number(process.env.PR_EVIDENCE_READY_TIMEOUT_MS);
@@ -38,18 +35,6 @@ export async function probeUrl(url, signal) {
38
35
  signal?.removeEventListener("abort", cancel);
39
36
  }
40
37
  }
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
38
  function readAppOutput(logPath) {
54
39
  if (!existsSync(logPath))
55
40
  return "";
@@ -71,23 +56,17 @@ function readAppOutput(logPath) {
71
56
  closeSync(descriptor);
72
57
  }
73
58
  }
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) {
59
+ async function waitUntilReady(url, app, logPath, signal) {
84
60
  const deadline = Date.now() + readyTimeoutMilliseconds();
85
61
  let status = null;
86
62
  while (true) {
87
63
  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) });
64
+ const exitStatus = app.exitStatus();
65
+ if (exitStatus !== null) {
66
+ const exitDescription = exitStatus.signal === null
67
+ ? `code ${exitStatus.exitCode}`
68
+ : `signal ${exitStatus.signal}`;
69
+ throw new CliError("app_exited", `The start command exited with ${exitDescription}. The command must stay in the foreground; detached apps it leaves behind are not managed.`, { appOutput: readAppOutput(logPath) });
91
70
  }
92
71
  if (status !== null && status < 500) {
93
72
  return;
@@ -102,17 +81,10 @@ async function waitUntilReady(url, child, logPath, signal) {
102
81
  }
103
82
  }
104
83
  /**
105
- * Starts the app in its own process group. `onStarted` runs as soon as the
84
+ * Starts the app and waits until it is ready. `onStarted` runs as soon as the
106
85
  * process exists, so it can be recorded and stopped even if readiness fails.
107
86
  */
108
87
  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
88
  const cancellation = new AbortController();
117
89
  const interrupt = (signal) => cancellation.abort(new CliError("app_interrupted", `Startup interrupted by ${signal}.`));
118
90
  const onInterrupt = () => interrupt("SIGINT");
@@ -121,22 +93,15 @@ export async function startApp(command, options) {
121
93
  process.on("SIGTERM", onTerminate);
122
94
  let app;
123
95
  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);
96
+ app = await launchProcess(command, { cwd: options.cwd, logPath: options.logPath });
97
+ options.onStarted(app.identity);
98
+ await waitUntilReady(options.readyUrl, app, options.logPath, cancellation.signal);
134
99
  cancellation.signal.throwIfAborted();
135
- child.unref();
100
+ app.release();
136
101
  }
137
102
  catch (error) {
138
103
  if (app) {
139
- await stopApp(app);
104
+ await stopProcess(app.identity);
140
105
  options.onStopped();
141
106
  }
142
107
  throw cancellation.signal.aborted ? cancellation.signal.reason : error;
@@ -146,26 +111,3 @@ export async function startApp(command, options) {
146
111
  process.off("SIGTERM", onTerminate);
147
112
  }
148
113
  }
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 CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "node:util";
3
+ import { browser } from "./commands/browser.js";
3
4
  import { finish } from "./commands/finish.js";
4
5
  import { publish } from "./commands/publish.js";
5
6
  import { setup } from "./commands/setup.js";
@@ -11,9 +12,10 @@ import { readRepoState } from "./repoState.js";
11
12
  const failedCriteriaExitCode = 1;
12
13
  const toolFailureExitCode = 2;
13
14
  const commands = [
14
- { usage: "setup [--agent claude|codex|cursor]...", description: "Install the skill and check prerequisites." },
15
+ { usage: "setup [--agent claude|codex|cursor]...", description: "Install the helper and the skill, and check prerequisites." },
15
16
  { 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: "browser [--headed] <chrome-devtools-axi arguments>", description: "Run chrome-devtools-axi on this repo's dedicated browser profile. Prints its output, not JSON, and exits with its exit code." },
18
+ { usage: "finish --results <file>", description: "Stop the app and record the results. Exits 1 if a criterion failed." },
17
19
  { usage: "stop", description: "Abandon a run, stopping any app it started." },
18
20
  { 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
21
  ];
@@ -86,8 +88,22 @@ function toCliError(error) {
86
88
  ? new CliError("usage", error.message)
87
89
  : new CliError("unexpected_error", String(error));
88
90
  }
91
+ async function main(argv) {
92
+ const [command, ...commandArgs] = argv;
93
+ if (command === "browser") {
94
+ // Only a leading --headed is the helper's, so that every later argument reaches chrome-devtools-axi as written.
95
+ const headed = commandArgs[0] === "--headed";
96
+ process.exitCode = await browser({
97
+ repositoryPath: process.cwd(),
98
+ headed,
99
+ args: headed ? commandArgs.slice(1) : commandArgs,
100
+ });
101
+ return;
102
+ }
103
+ print({ ok: true, ...(await runCommand(argv)) });
104
+ }
89
105
  try {
90
- print({ ok: true, ...(await runCommand(process.argv.slice(2))) });
106
+ await main(process.argv.slice(2));
91
107
  }
92
108
  catch (error) {
93
109
  const failure = toCliError(error);
@@ -0,0 +1,62 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { constants } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { browserProfileDirectoryOf } from "../evidenceStore.js";
7
+ import { readRepoState } from "../repoState.js";
8
+ /**
9
+ * The JS entry point of the pinned chrome-devtools-axi, as its manifest names it.
10
+ * PR_EVIDENCE_BROWSER_CLI_PATH lets tests put a fake entry point in its place.
11
+ */
12
+ function browserCliPath() {
13
+ const testOverride = process.env.PR_EVIDENCE_BROWSER_CLI_PATH;
14
+ if (testOverride !== undefined) {
15
+ return testOverride;
16
+ }
17
+ const manifestPath = createRequire(import.meta.url).resolve("chrome-devtools-axi/package.json");
18
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
19
+ return join(dirname(manifestPath), manifest.bin["chrome-devtools-axi"]);
20
+ }
21
+ /**
22
+ * Pins the browser to this repo's dedicated profile and session. The removed variables
23
+ * would otherwise attach it to the developer's own Chrome and their real sessions.
24
+ */
25
+ function isolatedEnvironment(repositoryKey, headed) {
26
+ const environment = { ...process.env };
27
+ delete environment.CHROME_DEVTOOLS_AXI_AUTO_CONNECT;
28
+ delete environment.CHROME_DEVTOOLS_AXI_BROWSER_URL;
29
+ delete environment.CHROME_DEVTOOLS_AXI_MCP_SERVER_URL;
30
+ environment.CHROME_DEVTOOLS_AXI_USER_DATA_DIR = browserProfileDirectoryOf(repositoryKey);
31
+ environment.CHROME_DEVTOOLS_AXI_SESSION =
32
+ `pr-evidence-${repositoryKey.replace(/[^A-Za-z0-9_-]/g, "-")}`.slice(0, 64);
33
+ if (headed) {
34
+ environment.CHROME_DEVTOOLS_AXI_HEADED = "1";
35
+ }
36
+ return environment;
37
+ }
38
+ /** The exit code a shell would report for a process that ended this way. */
39
+ function exitCodeOf(code, signal) {
40
+ if (code !== null) {
41
+ return code;
42
+ }
43
+ return 128 + (signal === null ? 0 : constants.signals[signal]);
44
+ }
45
+ /**
46
+ * Runs chrome-devtools-axi with these arguments and resolves to its exit code. Its
47
+ * output is passed straight through, because the agent reads it directly.
48
+ *
49
+ * It runs on this Node without a shell, so that no argument, which can hold text from
50
+ * the app under test, is ever read by one.
51
+ */
52
+ export function browser({ repositoryPath, headed, args }) {
53
+ const { repositoryKey } = readRepoState(repositoryPath);
54
+ return new Promise((resolveExitCode, reject) => {
55
+ const child = spawn(process.execPath, [browserCliPath(), ...args], {
56
+ env: isolatedEnvironment(repositoryKey, headed),
57
+ stdio: "inherit",
58
+ });
59
+ child.on("error", reject);
60
+ child.on("close", (code, signal) => resolveExitCode(exitCodeOf(code, signal)));
61
+ });
62
+ }
@@ -1,31 +1,50 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readFileSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError } from "../errors.js";
4
- import { findLatestRun, gifPathOf, listScreenshots, screenshotDirectoryOf, writeRunRecord, } from "../evidenceStore.js";
5
- import { buildGif } from "../gifBuilder.js";
4
+ import { findLatestRun, listScreenshots, screenshotDirectoryOf, writeRunRecord, } from "../evidenceStore.js";
6
5
  import { readRepoState } from "../repoState.js";
6
+ import { imageSizeProblem } from "../uploader.js";
7
7
  import { stopLatestRunApp } from "./stop.js";
8
8
  function invalid(problem) {
9
9
  return new CliError("results_invalid", `Results file: ${problem}`);
10
10
  }
11
- function parseCriterion(value, screenshots) {
12
- const { description, result, screenshot, note } = (value ?? {});
11
+ function parseScreenshotList(description, value, captured) {
12
+ if (!Array.isArray(value)) {
13
+ throw invalid(`"${description}" needs "screenshots", a list of file names that may be empty.`);
14
+ }
15
+ for (const [index, fileName] of value.entries()) {
16
+ if (typeof fileName !== "string") {
17
+ throw invalid(`"${description}" has a screenshot that is not a file name: ${JSON.stringify(fileName)}.`);
18
+ }
19
+ if (!captured.includes(fileName)) {
20
+ throw invalid(`"${description}" names screenshot ${fileName}, which was not captured.`);
21
+ }
22
+ if (value.indexOf(fileName) !== index) {
23
+ throw invalid(`"${description}" lists screenshot ${fileName} more than once.`);
24
+ }
25
+ }
26
+ return value;
27
+ }
28
+ function parseCriterion(value, captured) {
29
+ const { description, result, screenshots, note, screenshot } = (value ?? {});
13
30
  if (typeof description !== "string" || description.trim() === "") {
14
31
  throw invalid('every criterion needs a "description".');
15
32
  }
33
+ if (screenshot !== undefined) {
34
+ throw invalid(`"${description}" uses "screenshot", which was replaced. Use screenshots: [...] instead.`);
35
+ }
16
36
  if (result !== "pass" && result !== "fail") {
17
37
  throw invalid(`"${description}" needs a result of "pass" or "fail".`);
18
38
  }
19
39
  if (note !== undefined && typeof note !== "string") {
20
40
  throw invalid(`"${description}" has a note that is not a string.`);
21
41
  }
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 };
42
+ return {
43
+ description,
44
+ result,
45
+ screenshots: parseScreenshotList(description, screenshots, captured),
46
+ note,
47
+ };
29
48
  }
30
49
  function parseResults(resultsPath, screenshots) {
31
50
  let document;
@@ -47,24 +66,24 @@ function parseResults(resultsPath, screenshots) {
47
66
  criteria: document.criteria.map((criterion) => parseCriterion(criterion, screenshots)),
48
67
  };
49
68
  }
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;
69
+ /** Catches a screenshot GitHub would refuse now, before the developer reviews the run. */
70
+ function assertPublishable(runDirectory, screenshots) {
71
+ for (const fileName of screenshots) {
72
+ const sizeProblem = imageSizeProblem(statSync(join(screenshotDirectoryOf(runDirectory), fileName)).size);
73
+ if (sizeProblem !== null) {
74
+ throw new CliError("screenshot_invalid", `Screenshot ${fileName} cannot be published: ${sizeProblem}.`);
63
75
  }
64
- warnings.push(`No GIF was built. ${error.message}`);
65
- return null;
66
76
  }
67
77
  }
78
+ /** Evidence gaps don't fail the run, but the developer should judge them before publishing. */
79
+ function missingEvidenceWarnings(criteria) {
80
+ const uncited = criteria.filter((criterion) => criterion.screenshots.length === 0);
81
+ if (uncited.length === 0) {
82
+ return [];
83
+ }
84
+ const names = uncited.map((criterion) => `"${criterion.description}"`).join(", ");
85
+ return [`These criteria cite no screenshots, so the comment shows no proof for them: ${names}.`];
86
+ }
68
87
  export async function finish(repositoryPath, resultsPath) {
69
88
  const repoState = readRepoState(repositoryPath);
70
89
  const run = findLatestRun(repoState);
@@ -74,15 +93,13 @@ export async function finish(repositoryPath, resultsPath) {
74
93
  await stopLatestRunApp(repoState);
75
94
  const screenshots = listScreenshots(run.directory);
76
95
  const { ticket, criteria } = parseResults(resultsPath, screenshots);
77
- const warnings = [];
78
- const gifPath = tryBuildGif(run.directory, screenshots, warnings);
96
+ assertPublishable(run.directory, screenshots);
79
97
  const outcome = {
80
98
  result: criteria.every((criterion) => criterion.result === "pass") ? "pass" : "fail",
81
99
  ticket,
82
100
  criteria,
83
101
  screenshots,
84
- gifPath,
85
102
  };
86
103
  writeRunRecord(run.directory, { ...findLatestRun(repoState).record, outcome });
87
- return { ...outcome, warnings };
104
+ return { ...outcome, warnings: missingEvidenceWarnings(criteria) };
88
105
  }
@@ -37,6 +37,10 @@ export async function publish(repositoryPath) {
37
37
  if (repository === null) {
38
38
  throw new CliError("no_github_remote", "The origin remote is not a GitHub repository.");
39
39
  }
40
+ // Runs finished before screenshots were listed per criterion have no lists to lay out.
41
+ if (outcome.criteria.some((criterion) => !Array.isArray(criterion.screenshots))) {
42
+ throw new CliError("run_outdated", "This run was finished by an earlier version of pr-evidence. Run it again to publish it.", { runDirectory });
43
+ }
40
44
  assertSupportedHost(repository.host);
41
45
  const token = readUploadToken(repository.host);
42
46
  const github = new GitHubClient(repository, token);
@@ -53,14 +57,12 @@ export async function publish(repositoryPath) {
53
57
  host: repository.host,
54
58
  });
55
59
  // 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
60
  const screenshotUrls = await uploadScreenshots(uploader, runDirectory, outcome.screenshots);
58
61
  const body = renderEvidenceComment({
59
62
  repository,
60
63
  record,
61
64
  outcome,
62
65
  screenshotUrls,
63
- gifUrl,
64
66
  headDiffers,
65
67
  });
66
68
  // Author is checked as well as the marker: anyone can post the marker, and
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { CliError } from "../errors.js";
5
+ import { installHelper, removeOldHelperVersions } from "../helperInstall.js";
5
6
  import { helperVersion, readSkillTemplate } from "../packageInfo.js";
6
7
  import { findMissingPrerequisites } from "../prerequisites.js";
7
8
  const agents = [
@@ -26,18 +27,29 @@ function chooseAgents(requestedNames) {
26
27
  }
27
28
  return detected;
28
29
  }
30
+ function skillPathOf(agent) {
31
+ return join(homedir(), agent.skillsDirectory, "pr-evidence", "SKILL.md");
32
+ }
29
33
  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");
34
+ const chosenAgents = chooseAgents(requestedAgentNames);
35
+ const helperPath = installHelper();
36
+ const skill = readSkillTemplate()
37
+ .replaceAll("{{version}}", helperVersion)
38
+ // A function, because a `$` in the home directory would otherwise be read as a replacement pattern.
39
+ .replaceAll("{{helper}}", () => `node "${helperPath}"`);
40
+ // Every existing skill moves too, because removing old versions would otherwise strand it.
41
+ const agentsToUpdate = agents.filter((agent) => chosenAgents.includes(agent) || existsSync(skillPathOf(agent)));
42
+ const installed = agentsToUpdate.map((agent) => {
43
+ const path = skillPathOf(agent);
33
44
  mkdirSync(dirname(path), { recursive: true });
34
45
  writeFileSync(path, skill);
35
46
  process.stderr.write(`Installed the skill for ${agent.name}: ${path}\n`);
36
47
  return { agent: agent.name, path };
37
48
  });
49
+ removeOldHelperVersions();
38
50
  const missingPrerequisites = findMissingPrerequisites();
39
51
  for (const { name, fix } of missingPrerequisites) {
40
52
  process.stderr.write(`Missing ${name}. ${fix}\n`);
41
53
  }
42
- return { installed, ready: missingPrerequisites.length === 0, missingPrerequisites };
54
+ return { helperPath, installed, ready: missingPrerequisites.length === 0, missingPrerequisites };
43
55
  }