proofed-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/report.js ADDED
@@ -0,0 +1,328 @@
1
+ import { MARKER, OLD_MARKER } from "./github.js";
2
+ import { BLANK_PAGE, FAILED_CHECK_ACTION, FAILED_CHECK_REASON, runMarker } from "./runfile.js";
3
+ import { describeFixer } from "./models.js";
4
+ import { nothingAsked } from "./requests.js";
5
+ import { creditsOf, scenarioDoubted, unchecked } from "./run.js";
6
+ const DATA_RE = /<!-- proofed:data (.*?) -->/s;
7
+ export const FIX_BOX = "Fix with Claude";
8
+ const COMMENT_LIMIT = 65_536;
9
+ const HISTORY_SIZE = 8;
10
+ const MAX_STEPS = 30;
11
+ const MAX_STEP = 200;
12
+ export function readReportData(body) {
13
+ const raw = DATA_RE.exec(body)?.[1];
14
+ if (!raw)
15
+ return undefined;
16
+ try {
17
+ return JSON.parse(raw);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ // A push of the very commit the report is about: the Proofed app pushing Claude's fix, which the fix
24
+ // run checked and reported before it ended. Any other push brings a new commit, and a /proofed
25
+ // comment always runs, whatever the commit.
26
+ export const alreadyReported = (action, headSha, report) => action === "synchronize" && report?.sha === headSha;
27
+ export const fixRequested = (body) => body.includes(`- [x] **${FIX_BOX}**`);
28
+ export const WORKING = "⏳ **Claude is working on a fix**";
29
+ // JSON inside an HTML comment: "--" would end the comment early, so escape it.
30
+ export const dataComment = (data) => `<!-- proofed:data ${JSON.stringify(data).replaceAll("--", "\\u002d\\u002d")} -->`;
31
+ const STATES = { failed: "failing", error: "blocked", passed: "passing", fixed: "passing", unsure: "passing" };
32
+ // Reports from before `open` was kept name only the failures.
33
+ export function outcomeOf(data) {
34
+ const last = data.history?.at(-1);
35
+ const state = last?.sha === data.sha ? STATES[last.state] : data.failures.length > 0 ? "failing" : "passing";
36
+ return { state, open: [...(data.open ?? data.failures.map((f) => f.id))].sort() };
37
+ }
38
+ // GitHub notifies on a new comment, not on an edit. So a report is posted anew when someone should hear
39
+ // of it: the first report, a run a person asked for or a fix that ended (`notify`), or an outcome that
40
+ // changed. A push that finds the same as the current report only updates it.
41
+ export function postsNew(current, next, notify) {
42
+ if (notify || current === undefined)
43
+ return true;
44
+ const was = readReportData(current);
45
+ const now = readReportData(next);
46
+ if (!was || !now)
47
+ return true;
48
+ // A fix's report keeps its before and after: the next commit gets its own.
49
+ if (was.sha !== now.sha && was.history?.at(-1)?.state === "fixed")
50
+ return true;
51
+ const [a, b] = [outcomeOf(was), outcomeOf(now)];
52
+ return a.state !== b.state || a.open.join("\n") !== b.open.join("\n");
53
+ }
54
+ const LIVE_LINES = new RegExp(`\\n\\n(?:- \\[[ x]\\] \\*\\*${FIX_BOX}\\*\\*|${WORKING.replaceAll("*", "\\*")})[^\\n]*`, "g");
55
+ // A report a newer one replaced: without the fix box, so nobody ticks a stale one, or a "working" line
56
+ // that would never end, and with a marker that nothing reads as the PR's report.
57
+ export const outdated = (body) => body.replaceAll(MARKER, OLD_MARKER).replace(LIVE_LINES, "");
58
+ // A re-run on the same commit replaces its entry. Re-checking a commit Claude pushed keeps it a fix.
59
+ export function addRun(history = [], run) {
60
+ const last = history.at(-1);
61
+ if (last?.sha !== run.sha)
62
+ return [...history, run].slice(-HISTORY_SIZE);
63
+ const state = last.state === "fixed" && run.state === "passed" ? "fixed" : run.state;
64
+ return [...history.slice(0, -1), { sha: run.sha, state }].slice(-HISTORY_SIZE);
65
+ }
66
+ const quote = (text = "") => text
67
+ .trim()
68
+ .split("\n")
69
+ .map((l) => `> ${l}`)
70
+ .join("\n");
71
+ const short = (sha) => sha.slice(0, 7);
72
+ // Kane's and Claude's words on one line, cut to `max` characters.
73
+ const oneLine = (text = "", max = 300) => {
74
+ const line = text.replace(/\s+/g, " ").trim();
75
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
76
+ };
77
+ // Inside <details> and tables GitHub would take "<Cart>" for a tag and drop it.
78
+ const html = (text) => text.replaceAll("<", "&lt;");
79
+ const cell = (text) => html(oneLine(text)).replaceAll("|", "\\|");
80
+ const code = (text) => `\`${oneLine(text).replaceAll("`", "'")}\``;
81
+ const commitRef = (sha, url) => (url ? `[\`${short(sha)}\`](${url})` : `\`${short(sha)}\``);
82
+ function clip(links, width = 720) {
83
+ if (!links?.gif)
84
+ return "";
85
+ const video = links.mp4 ? `\n\n[Watch as video](${links.mp4})` : "";
86
+ return `\n\n<img src="${links.gif}" width="${width}" alt="Kane's run in the browser">${video}`;
87
+ }
88
+ // Only a still and no recording: the screenshot of a page that crashed on load (precheck.ts).
89
+ const isScreenshot = (links) => !!links?.jpg && !links.gif && !links.mp4;
90
+ const SCREENSHOT_ALT = "What a user sees on opening the page";
91
+ function screenshot(links, url) {
92
+ if (!isScreenshot(links))
93
+ return "";
94
+ return `\n\n<img src="${links.jpg}" width="720" alt="${SCREENSHOT_ALT}">\n\n<sub>This is what a user sees on opening ${code(url)}.</sub>`;
95
+ }
96
+ // The before/after table needs the video and a picture; the GIF only stands in for a missing still.
97
+ function storedClip(links) {
98
+ if (!links?.mp4 && !links?.jpg && !links?.gif)
99
+ return undefined;
100
+ return links.jpg ? { mp4: links.mp4, jpg: links.jpg } : { mp4: links.mp4, gif: links.gif };
101
+ }
102
+ function still(links) {
103
+ const src = links?.jpg ?? links?.gif;
104
+ if (!src)
105
+ return "";
106
+ const img = `<img src="${src}" width="360" alt="${isScreenshot(links) ? SCREENSHOT_ALT : "Kane's run in the browser"}">`;
107
+ return links?.mp4 ? `<a href="${links.mp4}">${img}</a>` : img;
108
+ }
109
+ // The last `keep` steps Kane finished, each cut to MAX_STEP characters.
110
+ function kaneSteps(steps, keep = MAX_STEPS) {
111
+ const done = steps.filter((s) => s.status !== "running" && s.remark);
112
+ const from = Math.max(done.length - keep, 0);
113
+ return {
114
+ from: from + 1,
115
+ steps: done.slice(from).map((s) => ({ failed: s.status === "failed", text: oneLine(s.remark, MAX_STEP) })),
116
+ };
117
+ }
118
+ function stepList(steps) {
119
+ const { from, steps: kept } = kaneSteps(steps);
120
+ if (kept.length === 0)
121
+ return "";
122
+ const items = kept.map((s, i) => `${from + i}. ${s.failed ? `**✗ ${html(s.text)}**` : html(s.text)}`);
123
+ return `\n\n<details><summary>Kane's steps</summary>\n\n${items.join("\n")}\n\n</details>`;
124
+ }
125
+ function attemptList(fix) {
126
+ const tries = fix.tries ?? [];
127
+ if (tries.length < 2)
128
+ return "";
129
+ const items = tries.map((t, i) => `${i + 1}. ${html(oneLine([t.summary, t.result].filter(Boolean).join(" ")))}`);
130
+ return `\n\n<details><summary>${tries.length} attempts</summary>\n\n${items.join("\n")}\n\n</details>`;
131
+ }
132
+ function whatChanged(fix) {
133
+ const files = fix.changes ?? [];
134
+ const listed = files.slice(0, 5).map((f) => `\`${f.file}\` (+${f.added} −${f.removed})`).join(", ");
135
+ const more = files.length > 5 ? ` and ${files.length - 5} more` : "";
136
+ const text = [listed && `${listed}${more}.`, fix.summary].filter(Boolean).join(" ");
137
+ return text ? `\n\n**What changed:** ${text}` : "";
138
+ }
139
+ function writtenSection(written, results, clips) {
140
+ if (written.status === "failed")
141
+ return "Proofed tried to add scenarios for this app's main flows, but the scenarios couldn't be written this time.";
142
+ const kept = written.kept.flatMap(({ id, about }) => results.filter((r) => r.scenario.id === id).map((r) => ({ r, about })));
143
+ const dropped = written.dropped.map((d) => `- **${html(d.name)}**: ${html(oneLine(d.why, 200))}`).join("\n");
144
+ if (kept.length === 0) {
145
+ return dropped
146
+ ? `Claude wrote ${written.dropped.length === 1 ? "a scenario" : `${written.dropped.length} scenarios`} for this app, but Kane didn't see ${written.dropped.length === 1 ? "it" : "any of them"} pass, so none were added:\n\n${dropped}`
147
+ : "Claude didn't find a flow it could write a scenario for without guessing, so none were added.";
148
+ }
149
+ const folder = kept[0].r.scenario.file.split("/").slice(0, -1).join("/");
150
+ const commit = written.commit ? ` in ${commitRef(written.commit, written.commitUrl)}` : "";
151
+ const intro = `**Claude wrote ${kept.length === 1 ? "a scenario" : `${kept.length} scenarios`} for this app**, and Proofed added ${kept.length === 1 ? "it" : "them"} to this PR${commit}. ` +
152
+ `Kane ran each one in Chrome and saw it pass. They are plain Markdown in \`${folder}/\`: edit or delete them like any other file.`;
153
+ const items = kept.map(({ r, about }) => `**✓ ${r.scenario.name}** · \`${r.scenario.file.split("/").at(-1)}\`<br>${html(oneLine(about, 200))}${clip(clips.get(r.scenario.id), 560)}`);
154
+ const droppedNote = dropped ? `\n\nDropped, since Kane didn't see ${written.dropped.length === 1 ? "it" : "them"} pass:\n\n${dropped}` : "";
155
+ return `${intro}\n\n${items.join("\n\n")}${droppedNote}`;
156
+ }
157
+ // The commit, the fixer and what changed are said once, above all the repaired scenarios.
158
+ // A page that crashed on load has its screenshot as the still and the browser's error under it
159
+ // (precheck.ts keeps the error as the diagnosis). Reports from before screenshots have only the error;
160
+ // with a still on one side only, it goes above that side's text instead of in a half-empty row.
161
+ function beforeAfter({ before, after }, beforeSha, sha, links) {
162
+ const stills = [still(before.clip), still(links)];
163
+ const confirmed = after.end?.summary?.trim() || after.end?.reason?.trim() || "Passes.";
164
+ const consoleError = before.reason === BLANK_PAGE && before.diagnosis ? `<br><br>${code(before.diagnosis).replaceAll("|", "\\|")}` : "";
165
+ const texts = [`✗ ${cell(before.reason || before.diagnosis || "Failed.")}${consoleError}`, `✓ ${cell(confirmed)}`];
166
+ const both = stills.every(Boolean);
167
+ const rows = [
168
+ `| Before · \`${short(beforeSha)}\` | After · \`${short(sha)}\` |`,
169
+ "|---|---|",
170
+ ...(both ? [`| ${stills.join(" | ")} |`] : []),
171
+ `| ${texts.map((t, i) => (!both && stills[i] ? `${stills[i]}<br>${t}` : t)).join(" | ")} |`,
172
+ ];
173
+ return `#### ✓ ${after.scenario.name}\n\n${rows.join("\n")}`;
174
+ }
175
+ const MARKS = { failed: "✗", passed: "✓", fixed: "✓ fixed", error: "⚠", unsure: "? not confirmed" };
176
+ function historyLine(history, repoUrl) {
177
+ return history
178
+ .map((h) => `${repoUrl ? `[${short(h.sha)}](${repoUrl}/commit/${h.sha})` : short(h.sha)} ${MARKS[h.state]}`)
179
+ .join(" → ");
180
+ }
181
+ // When the comment doesn't fit, Kane's step lists go first (the TestMu report has them too),
182
+ // then the steps kept for the fixer.
183
+ const FITS = [
184
+ { stepList: true, storedSteps: MAX_STEPS },
185
+ { stepList: false, storedSteps: MAX_STEPS },
186
+ { stepList: false, storedSteps: 10 },
187
+ { stepList: false, storedSteps: 0 },
188
+ ];
189
+ export function buildReport(input) {
190
+ let body = "";
191
+ for (const fit of FITS) {
192
+ body = compose(input, fit);
193
+ if (body.length <= COMMENT_LIMIT)
194
+ break;
195
+ }
196
+ return body;
197
+ }
198
+ function compose({ sha, results: all, skipped, clips, runUrl, fixEnabled, fix, asked, previous, repoUrl, runKey, written }, { stepList: withSteps, storedSteps }) {
199
+ const unasked = all.filter(nothingAsked);
200
+ const results = all.filter((r) => !nothingAsked(r));
201
+ const failed = results.filter((r) => r.outcome === "failed");
202
+ const errored = results.filter((r) => r.outcome === "error");
203
+ const unsure = results.filter((r) => r.outcome === "unsure");
204
+ const passed = results.filter((r) => r.outcome === "passed");
205
+ const credits = all.reduce((sum, r) => sum + creditsOf(r), written?.credits ?? 0);
206
+ const repaired = fix?.status === "fixed" && previous
207
+ ? passed.flatMap((after) => {
208
+ const before = previous.failures.find((f) => f.id === after.scenario.id);
209
+ return before ? [{ before, after }] : [];
210
+ })
211
+ : [];
212
+ const isRepaired = (r) => repaired.some((x) => x.after === r);
213
+ const isWritten = (r) => written?.status === "written" && written.kept.some((k) => k.id === r.scenario.id);
214
+ const headline = results.length === 0
215
+ ? "This PR doesn't touch the files of any scenario, so there was nothing to run."
216
+ : failed.length > 0
217
+ ? `**${failed.length} of ${results.length}** scenarios broke on this PR.`
218
+ : errored.length > 0
219
+ ? `Kane couldn't finish ${errored.length} of ${results.length} scenarios. Nothing points at the code yet.`
220
+ : unsure.length > 0
221
+ ? passed.length > 0
222
+ ? `**${passed.length} of ${results.length}** scenarios pass in a real browser; ${unsure.length} ${unsure.length === 1 ? "wasn't" : "weren't"} checked.`
223
+ : results.length === 1
224
+ ? "The affected scenario wasn't checked."
225
+ : `None of the ${results.length} affected scenarios were checked.`
226
+ : results.length === 1
227
+ ? "The affected scenario passes in a real browser."
228
+ : `All ${results.length} affected scenarios pass in a real browser.`;
229
+ const sections = [`${MARKER}\n### Proofed\n\n${headline}`];
230
+ if (results.length >= 4) {
231
+ const tag = (r) => r.outcome === "error"
232
+ ? ": couldn't finish"
233
+ : unchecked(r)
234
+ ? ": not checked"
235
+ : r.outcome === "unsure"
236
+ ? ": the test may be wrong"
237
+ : isRepaired(r)
238
+ ? ": fixed"
239
+ : "";
240
+ const mark = (r) => (r.outcome === "failed" ? "✗" : r.outcome === "passed" ? "✓" : "⚠");
241
+ sections.push([...failed, ...errored, ...unsure, ...passed].map((r) => `- ${mark(r)} ${r.scenario.name}${tag(r)}`).join("\n"));
242
+ }
243
+ if (written)
244
+ sections.push(writtenSection(written, passed, clips));
245
+ if (fix?.status === "fixed") {
246
+ const commit = fix.commit ? ` in ${commitRef(fix.commit, fix.commitUrl)}` : "";
247
+ sections.push(`**Fixed${commit}** by ${describeFixer(fix)}, after ${fix.attempts} attempt${fix.attempts > 1 ? "s" : ""}.${whatChanged(fix)}${attemptList(fix)}`);
248
+ }
249
+ else if (fix?.status === "gave-up") {
250
+ sections.push(`**Tried ${fix.attempts} times with ${describeFixer(fix)} and couldn't make it pass.** Nothing was pushed. Last attempt: ${fix.summary}` +
251
+ attemptList(fix));
252
+ }
253
+ if (fix && previous) {
254
+ for (const r of repaired)
255
+ sections.push(beforeAfter(r, previous.sha, sha, clips.get(r.after.scenario.id)));
256
+ }
257
+ for (const r of failed) {
258
+ const reason = r.end?.reason ?? "";
259
+ const diagnosis = r.end?.verdict?.root_cause ?? r.end?.summary ?? "";
260
+ // A page that crashed on load never reached Kane: the error is the browser's, not Kane's reading.
261
+ const seen = r.pageError
262
+ ? `\n\n**Browser console error:** ${code(r.pageError)}`
263
+ : scenarioDoubted(r)
264
+ ? `\n\n${FAILED_CHECK_REASON}\n\n**Kane's opinion:** ${diagnosis}\n\n${FAILED_CHECK_ACTION}`
265
+ : diagnosis && diagnosis !== reason
266
+ ? `\n\n**What Kane saw:** ${diagnosis}`
267
+ : "";
268
+ sections.push(`#### ✗ ${r.scenario.name}\n\n${quote(reason)}${clip(clips.get(r.scenario.id)) || screenshot(clips.get(r.scenario.id), r.scenario.url)}` +
269
+ seen +
270
+ (withSteps ? stepList(r.steps) : "") +
271
+ (r.end?.test_url ? `\n\n[Kane's step-by-step report](${r.end.test_url})` : ""));
272
+ }
273
+ if (failed.length > 0 && fixEnabled && fix?.status !== "gave-up") {
274
+ sections.push(`- [ ] **${FIX_BOX}** — Claude Code gets the failure, the steps and the diff, pushes a fix to this branch, and Proofed checks again.`);
275
+ }
276
+ for (const r of errored) {
277
+ sections.push(`#### ⚠ ${r.scenario.name}: Kane couldn't finish, even after a retry\n\n${quote(r.error)}` +
278
+ clip(clips.get(r.scenario.id), 560) +
279
+ `\n\nThis is about the test run, not your code. Re-run the check to try again.`);
280
+ }
281
+ for (const r of unsure) {
282
+ sections.push((unchecked(r)
283
+ ? `#### ⚠ ${r.scenario.name}: not checked\n\n${quote(r.end?.reason)}\n\nKane called it a pass, but none of its steps checked the page, so this says nothing about the code either way.`
284
+ : `#### ⚠ ${r.scenario.name}: the test may be wrong, not the code\n\n${quote(r.end?.reason)}` +
285
+ (r.end?.verdict?.suggestion ? `\n\n**Kane suggests:** ${r.end.verdict.suggestion}` : "")) +
286
+ clip(clips.get(r.scenario.id), 560));
287
+ }
288
+ const others = passed.filter((r) => !isRepaired(r) && !isWritten(r));
289
+ if (others.length > 0) {
290
+ const items = others.map((r) => `**✓ ${r.scenario.name}**${clip(clips.get(r.scenario.id), 560)}`).join("\n\n");
291
+ sections.push(`<details><summary>✓ Passed: ${others.map((r) => r.scenario.name).join(", ")}</summary>\n\n${items}\n\n</details>`);
292
+ }
293
+ if (skipped.length > 0)
294
+ sections.push(`<sub>Not affected by this diff: ${skipped.join(", ")}</sub>`);
295
+ if (unasked.length > 0)
296
+ sections.push("<sub>The PR description didn't name anything Kane could check in the browser.</sub>");
297
+ const state = failed.length > 0 ? "failed" : errored.length > 0 ? "error" : fix?.status === "fixed" ? "fixed" : unsure.length > 0 ? "unsure" : "passed";
298
+ const history = addRun(previous?.history, { sha, state });
299
+ const open = [...failed, ...errored, ...unsure].map((r) => r.scenario.id);
300
+ // Not kept for the fixer: its final check would only spend credits finding nothing to check again.
301
+ const rerun = asked?.filter((s) => !unasked.some((r) => r.scenario.id === s.id));
302
+ const data = {
303
+ sha,
304
+ ...(rerun?.length && { asked: rerun }),
305
+ failures: failed.map((r) => ({
306
+ id: r.scenario.id,
307
+ name: r.scenario.name,
308
+ file: r.scenario.file,
309
+ objective: r.scenario.objective,
310
+ reason: r.end?.reason ?? "",
311
+ diagnosis: r.end?.verdict?.root_cause ?? r.end?.summary ?? "",
312
+ ...(scenarioDoubted(r) && { failedCheck: "scenario_doubted" }),
313
+ steps: kaneSteps(r.steps, storedSteps).steps.map((s) => `${s.failed ? "✗" : "·"} ${s.text}`),
314
+ clip: storedClip(clips.get(r.scenario.id)),
315
+ })),
316
+ history,
317
+ ...(open.length && { open }),
318
+ };
319
+ const footer = [`Run by Kane CLI on ${short(sha)}`, credits > 0 && `${Math.round(credits)} credits`, runUrl && `[logs](${runUrl})`]
320
+ .filter(Boolean)
321
+ .join(" · ");
322
+ const canFix = failed.length > 0 && fixEnabled;
323
+ const hint = canFix
324
+ ? "Comment <code>/proofed</code> to check again or <code>/proofed fix</code> to have Claude fix it."
325
+ : "Comment <code>/proofed</code> to check again.";
326
+ const lines = [footer, history.length > 1 && historyLine(history, repoUrl), hint].filter(Boolean).join("<br>");
327
+ return `${sections.join("\n\n")}\n\n<sub>${lines}</sub>\n${dataComment(data)}${runKey ? `\n${runMarker(runKey)}` : ""}`;
328
+ }
@@ -0,0 +1,58 @@
1
+ import { isEffort, parseModel } from "./models.js";
2
+ // "/proofed" in a PR comment re-runs the check, which also gives a PR opened before Proofed was
3
+ // added its first run. "/proofed <what to check>" has Kane check just that. A slash command,
4
+ // not "@proofed": that name belongs to someone else on GitHub and would mention them.
5
+ const COMMAND = /(?:^|\s)\/proofed\b([\s\S]*)/i;
6
+ export function parseCommand(comment) {
7
+ const match = COMMAND.exec(comment);
8
+ return match ? match[1].trim() : undefined;
9
+ }
10
+ // "/proofed fix [model] [effort]" has Claude fix the broken scenarios, with that model this once.
11
+ // Only the first line counts, so a note under the command doesn't become part of the model name.
12
+ export function parseFix(command) {
13
+ const words = (command.split("\n")[0] ?? "").trim().split(/\s+/).filter(Boolean);
14
+ if (words[0]?.toLowerCase() !== "fix")
15
+ return undefined;
16
+ const rest = words.slice(1);
17
+ const last = rest.at(-1)?.toLowerCase() ?? "";
18
+ const effort = isEffort(last) ? last : undefined;
19
+ const modelWords = effort ? rest.slice(0, -1) : rest;
20
+ if (modelWords.length === 0)
21
+ return { effort };
22
+ const choice = parseModel(modelWords);
23
+ return "error" in choice ? choice : { model: choice.model, effort };
24
+ }
25
+ // What the PR description asks to have checked. HTML comments (PR templates) are dropped, and a
26
+ // long description is a changelog rather than a request, so it's left alone.
27
+ export function descriptionRequest(body) {
28
+ const text = (body ?? "").replace(/<!--[\s\S]*?-->/g, "").trim();
29
+ return text && text.length <= 1500 ? text : undefined;
30
+ }
31
+ // Any short description becomes a request, and many ask for nothing ("Will be closed, not merged.").
32
+ // Left to itself Kane then improvises: it signs in, ends up on GitHub's OAuth page, and the report
33
+ // says the test may be wrong. A /proofed comment is always a request, so it gets no such way out.
34
+ const MAY_ASK_NOTHING = "If the text above doesn't describe something a user can see or do in this app, stop right away " +
35
+ "without clicking anything: there is nothing to check. Never sign in, and never leave the app's own pages to get there.";
36
+ // The description asked for nothing Kane could check: not a result of the PR, only a line under the report.
37
+ export const nothingAsked = (r) => r.scenario.id === "asked-in-description" && r.outcome === "unsure";
38
+ const NAMES = {
39
+ description: "What the PR description asks",
40
+ comment: "What the /proofed comment asks",
41
+ terminal: "What you asked to check",
42
+ };
43
+ // "terminal": `proofed check "<text>"`, run by a person or a coding agent on their own machine.
44
+ export function askedScenario(where, text) {
45
+ return {
46
+ id: where === "terminal" ? "asked" : `asked-in-${where}`,
47
+ file: "",
48
+ name: NAMES[where],
49
+ paths: [],
50
+ url: "/",
51
+ objective: (where === "terminal"
52
+ ? `The developer of this app asked for this to be checked:\n\n${text}\n\n`
53
+ : `The author of this pull request asked for this to be checked:\n\n${text}\n\n`) +
54
+ "Open the app and check exactly that in the browser, the way a user would. It passes only if what they " +
55
+ "asked about actually works; the page loading is not enough." +
56
+ (where === "description" ? ` ${MAY_ASK_NOTHING}` : ""),
57
+ };
58
+ }
package/dist/result.js ADDED
@@ -0,0 +1,135 @@
1
+ // The result of `proofed check` as one JSON document: what `--json` prints, what <out>/result.json
2
+ // holds, and what the terminal views draw from. Its names are the CLI's contract with coding agents.
3
+ import { resolve } from "node:path";
4
+ import { creditsOf, scenarioDoubted, unchecked } from "./run.js";
5
+ import { FAILED_CHECK_ACTION } from "./runfile.js";
6
+ export const outcomeOf = (r) => (r.outcome === "unsure" ? "not_checked" : r.outcome);
7
+ // Shell-safe as typed.
8
+ export const quote = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
9
+ // The same check again, as it was asked for.
10
+ export const sameCommand = (ctx, selection = ctx.selection) => ["proofed check", ...(ctx.text !== undefined ? [quote(ctx.text)] : selection ? [selection] : []), ...ctx.flags].join(" ");
11
+ export function rerunCommand(ids, ctx) {
12
+ const what = ctx.text !== undefined ? quote(ctx.text) : `--only ${ids.join(",")}`;
13
+ return ["proofed check", what, ...ctx.flags].join(" ");
14
+ }
15
+ const round = (n) => Math.round(n * 100) / 100;
16
+ const names = (docs) => docs.map((d) => d.name).join(", ");
17
+ export function scenarioDoc(item, ctx) {
18
+ const { scenario: s } = item;
19
+ const head = { id: s.id, name: s.name, ...(s.file && { file: s.file }) };
20
+ const rerun = rerunCommand([s.id], ctx);
21
+ if ("estimate" in item) {
22
+ return { ...head, outcome: "would_run", cached: false, objective: s.objective, steps: [], credits: 0, estimatedCredits: item.estimate, rerun };
23
+ }
24
+ if ("cached" in item) {
25
+ const { passedAt, seconds, clip } = item.cached;
26
+ return {
27
+ ...head,
28
+ outcome: "passed",
29
+ cached: true,
30
+ cachedAt: passedAt,
31
+ objective: s.objective,
32
+ steps: [],
33
+ ...(clip && { clip }),
34
+ credits: 0,
35
+ ...(seconds !== undefined && { seconds }),
36
+ rerun,
37
+ };
38
+ }
39
+ const r = item.result;
40
+ const outcome = outcomeOf(r);
41
+ const verdict = r.end?.verdict;
42
+ const failedStep = r.steps.findLast((step) => step.status === "failed")?.remark;
43
+ const reason = outcome === "passed" ? r.end?.summary || r.end?.reason : r.end?.reason || r.error;
44
+ return {
45
+ ...head,
46
+ outcome,
47
+ cached: false,
48
+ objective: s.objective,
49
+ ...(reason && { reason }),
50
+ ...(outcome === "not_checked" && { notChecked: unchecked(r) ? "nothing_asserted" : "scenario_doubted" }),
51
+ ...(outcome !== "passed" && verdict?.root_cause && { diagnosis: verdict.root_cause }),
52
+ ...(scenarioDoubted(r) && { failedCheck: "scenario_doubted" }),
53
+ ...(scenarioDoubted(r) ? { suggestion: FAILED_CHECK_ACTION } : outcome !== "passed" && verdict?.suggestion && { suggestion: verdict.suggestion }),
54
+ ...(outcome !== "passed" && failedStep && { failedStep }),
55
+ steps: r.steps
56
+ .filter((step) => step.status !== "running" && step.remark)
57
+ .slice(-30)
58
+ .map((step) => ({ remark: step.remark.slice(0, 200), ...(step.status === "failed" && { failed: true }) })),
59
+ ...(r.pageError && { pageError: r.pageError }),
60
+ ...(r.clip && { clip: { ...(r.clip.mp4 && { mp4: resolve(r.clip.mp4) }), jpg: resolve(r.clip.jpg) } }),
61
+ credits: round(creditsOf(r)),
62
+ ...(r.seconds !== undefined && { seconds: r.seconds }),
63
+ rerun,
64
+ };
65
+ }
66
+ export const exitCodeOf = (counts) => (counts.failed > 0 ? 1 : counts.not_checked + counts.error > 0 ? 2 : 0);
67
+ export function buildDoc(input) {
68
+ const scenarios = input.items.map((item) => scenarioDoc(item, input.rerun));
69
+ const of = (o) => scenarios.filter((d) => d.outcome === o);
70
+ const counts = {
71
+ passed: of("passed").length,
72
+ failed: of("failed").length,
73
+ not_checked: of("not_checked").length,
74
+ error: of("error").length,
75
+ skipped: input.skipped.length,
76
+ };
77
+ const exitCode = exitCodeOf(counts);
78
+ const broken = scenarios.filter((d) => d.outcome !== "passed" && d.outcome !== "would_run");
79
+ const rerun = rerunCommand(broken.map((d) => d.id), input.rerun);
80
+ const cached = scenarios.filter((d) => d.cached).length;
81
+ const estimatedCredits = round(input.estimatedCredits);
82
+ let summary;
83
+ let next;
84
+ if (input.idle) {
85
+ ({ summary, next } = input.idle);
86
+ }
87
+ else if (input.dryRun) {
88
+ const would = of("would_run").length;
89
+ summary = `Would run ${would} scenario(s) for about ${estimatedCredits} credits${cached ? `; ${cached} cached pass(es) cost nothing` : ""}`;
90
+ next = would ? `Run it for real: ${sameCommand(input.rerun)}` : "Nothing would run.";
91
+ }
92
+ else if (counts.failed > 0) {
93
+ summary = `${counts.failed} of ${scenarios.length} broke: ${names(of("failed"))}`;
94
+ next = scenarios.some((d) => d.failedCheck)
95
+ ? `${FAILED_CHECK_ACTION} Then run: ${rerun}`
96
+ : `Fix the failed scenarios, then run: ${rerun}`;
97
+ }
98
+ else if (counts.error > 0) {
99
+ summary = `Kane couldn't finish: ${names(of("error"))}${counts.not_checked ? `; not checked: ${names(of("not_checked"))}` : ""}`;
100
+ next = `Run them again: ${rerun}`;
101
+ }
102
+ else if (counts.not_checked > 0) {
103
+ summary = `${counts.passed} passed, ${counts.not_checked} not checked: ${names(of("not_checked"))}`;
104
+ next = `Not checked is not a pass. Make the scenario end in a concrete check, or tell the user why Kane doubts it, then run: ${rerun}`;
105
+ }
106
+ else {
107
+ summary = `${counts.passed} of ${scenarios.length} passed${cached ? ` (${cached} cached)` : ""}`;
108
+ next = "Nothing to fix.";
109
+ }
110
+ return {
111
+ ok: exitCode === 0,
112
+ exitCode,
113
+ summary,
114
+ ...(input.dryRun && { dryRun: true }),
115
+ counts,
116
+ base: input.base,
117
+ changedFiles: input.changedFiles,
118
+ url: input.url,
119
+ app: input.app ?? null,
120
+ credits: round(scenarios.reduce((sum, d) => sum + d.credits, 0)),
121
+ estimatedCredits,
122
+ seconds: input.seconds,
123
+ scenarios,
124
+ skipped: input.skipped,
125
+ next,
126
+ ...(broken.length > 0 && { rerun }),
127
+ out: input.out,
128
+ };
129
+ }
130
+ export const errorDoc = (e, exitCode = 3, scenarios) => ({
131
+ ok: false,
132
+ exitCode,
133
+ error: { code: e.code, message: e.message, fix: e.fix },
134
+ ...(scenarios && { scenarios }),
135
+ });