proofed-cli 0.1.3 → 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.
Files changed (65) hide show
  1. package/README.md +176 -122
  2. package/dist/action/requests.js +130 -0
  3. package/dist/{server.js → action/server.js} +17 -3
  4. package/dist/changes.js +7 -1
  5. package/dist/{args.js → check/args.js} +31 -3
  6. package/dist/check/cache.js +89 -0
  7. package/dist/{check.js → check/check.js} +86 -40
  8. package/dist/{doctor.js → check/doctor.js} +55 -19
  9. package/dist/check/help.js +139 -0
  10. package/dist/{list.js → check/list.js} +27 -15
  11. package/dist/{pipeline.js → check/pipeline.js} +106 -68
  12. package/dist/{render.js → check/render.js} +22 -15
  13. package/dist/check/run.js +277 -0
  14. package/dist/check/targetfilter.js +10 -0
  15. package/dist/check/textcheck.js +162 -0
  16. package/dist/env.js +6 -0
  17. package/dist/fix/agent.js +21 -0
  18. package/dist/fix/claude.js +30 -0
  19. package/dist/fix/codex.js +71 -0
  20. package/dist/fix/fixsetup.js +76 -0
  21. package/dist/fix/fixtarget.js +48 -0
  22. package/dist/fix/models.js +67 -0
  23. package/dist/github.js +62 -14
  24. package/dist/integrations/claude-stop.js +104 -0
  25. package/dist/integrations/cli.js +63 -0
  26. package/dist/integrations/mcp.js +130 -0
  27. package/dist/kane/creditmeter.js +104 -0
  28. package/dist/kane/kane.js +131 -0
  29. package/dist/kane/kaneauth.js +84 -0
  30. package/dist/kane/kaneversion.js +13 -0
  31. package/dist/paths.js +32 -0
  32. package/dist/process.js +65 -0
  33. package/dist/proofed.js +34 -16
  34. package/dist/{live.js → report/live.js} +1 -1
  35. package/dist/{livefile.js → report/livefile.js} +1 -1
  36. package/dist/{report.js → report/report.js} +105 -125
  37. package/dist/report/reportdata.js +120 -0
  38. package/dist/{result.js → report/result.js} +12 -7
  39. package/dist/{runfile.js → report/runfile.js} +2 -2
  40. package/dist/report/runresult.js +5 -0
  41. package/dist/scenarios.js +41 -19
  42. package/dist/secrets.js +74 -0
  43. package/dist/{cdp.js → targets/cdp.js} +20 -6
  44. package/dist/targets/chrome.js +98 -0
  45. package/dist/{clip.js → targets/clip.js} +21 -11
  46. package/dist/{precheck.js → targets/precheck.js} +53 -20
  47. package/dist/targets/preparetarget.js +350 -0
  48. package/dist/{recorder.js → targets/recorder.js} +154 -19
  49. package/dist/{serve.js → targets/serve.js} +9 -13
  50. package/dist/{target.js → targets/target.js} +42 -7
  51. package/dist/targets/targetchecks.js +139 -0
  52. package/dist/timing.js +25 -0
  53. package/dist/types.js +1 -0
  54. package/dist/which.js +26 -13
  55. package/docs/cli.md +370 -0
  56. package/package.json +10 -5
  57. package/dist/cache.js +0 -48
  58. package/dist/chrome.js +0 -77
  59. package/dist/help.js +0 -133
  60. package/dist/kane.js +0 -75
  61. package/dist/kaneauth.js +0 -48
  62. package/dist/models.js +0 -44
  63. package/dist/requests.js +0 -58
  64. package/dist/run.js +0 -173
  65. /package/dist/{deps.js → targets/deps.js} +0 -0
@@ -0,0 +1,277 @@
1
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { assertSnapshots, expectedText, textContradiction } from "./textcheck.js";
4
+ import { stopping } from "../children.js";
5
+ import { prepareTarget } from "../targets/preparetarget.js";
6
+ import { resolveScenarioTarget } from "../targets/target.js";
7
+ import { makeClip } from "../targets/clip.js";
8
+ import { live } from "../report/live.js";
9
+ import { NOT_SIGNED_IN } from "../kane/kaneauth.js";
10
+ import { log as logLine } from "../log.js";
11
+ import { runKane } from "../kane/kane.js";
12
+ import { NOTHING_CHECKED } from "../report/runfile.js";
13
+ import { scenarioDoubted } from "../report/runresult.js";
14
+ import { startRecorder } from "../targets/recorder.js";
15
+ import { checkScenarioId } from "../scenarios.js";
16
+ import { maskSecrets } from "../secrets.js";
17
+ import { timedAsync } from "../timing.js";
18
+ // Kane's --timeout counts active time; the wall-clock limit leaves a minute on top, as the defaults do.
19
+ const kaneTimeouts = (s) => s.timeoutMinutes ? { timeoutSeconds: s.timeoutMinutes * 60, wallTimeoutSeconds: s.timeoutMinutes * 60 + 60 } : {};
20
+ // Failures of the browser plumbing rather than of the app: the run is retried, never reported as a bug.
21
+ const INFRA = /Screenshot failed|TimeoutError|TargetClosedError|has been closed|ECONNREFUSED|ECONNRESET|socket hang up|Project and folder must be configured/i;
22
+ // What Kane said when it left without a verdict. Kane puts the cause on an "error:" line and its
23
+ // hints after it, so the last lines alone can start in the middle of a hint.
24
+ const NOTICE = /^\s*(?:Skill update available|Update available)\b/i;
25
+ export function kaneError(stderr) {
26
+ const lines = stderr.trim().split("\n").filter((l) => l.trim() && !NOTICE.test(l));
27
+ const cause = lines.findLast((l) => /^\s*(?:error|fatal)\b/i.test(l));
28
+ return cause ? cause.trim().replace(/^(?:error|fatal):\s*/i, "") : lines.slice(-5).join("\n");
29
+ }
30
+ // A run cut off by the wall-clock limit. A cloud mobile run that never started a step was still
31
+ // waiting for TestMu to hand over a device, which it does with no error while that model is busy.
32
+ export function cutOffReason(stderr, target, stepsStarted, seconds = 360) {
33
+ const minutes = Math.round(seconds / 60);
34
+ if ((target.kind === "ios" || target.kind === "android") && target.execution === "cloud" && !stepsStarted) {
35
+ const device = [target.device, target.os_version && `${target.kind === "ios" ? "iOS" : "Android"} ${target.os_version}`].filter(Boolean).join(", ") || target.kind;
36
+ return `TestMu gave Kane no real device (${device}) within ${minutes} minutes; that model may be busy. Pick another from kane-cli devices list --target ${target.kind} --remote.`;
37
+ }
38
+ const last = stderr.trim().split("\n").filter((l) => l.trim() && !NOTICE.test(l)).at(-1)?.trim();
39
+ return `Kane stopped responding and the run was cut off after ${minutes} minutes${last ? `; Kane's last line: ${last}` : ""}`;
40
+ }
41
+ // Words of what the run checked last: the quoted expectation of a failed check, or the values
42
+ // Kane read off the page when it passed. The clip ends zoomed on the element that holds them.
43
+ const STOP = new Set(["that", "this", "with", "from", "have", "after", "then", "should", "shows", "page", "into", "when", "each", "there", "them", "than", "what", "which", "only", "also", "visible", "displayed"]);
44
+ export function focusWords(end) {
45
+ const text = end.status === "passed"
46
+ ? Object.values(end.final_state ?? {})
47
+ .filter((v) => typeof v === "string" && !v.startsWith("http"))
48
+ .join(" ")
49
+ : (/["“«]([^"”»]+)["”»]/.exec(end.reason ?? "")?.[1] ?? "");
50
+ const words = (text.toLowerCase().replace(/[‘’]/g, "'").match(/[\p{L}\p{Sc}\d][\p{L}\p{N}\p{Sc}.,%'-]*/gu) ?? [])
51
+ .map((w) => w.replace(/[.,]+$/, ""))
52
+ .filter((w) => (/\d/.test(w) ? w.length >= 2 : w.length >= 4) && !STOP.has(w));
53
+ return [...new Set(words)];
54
+ }
55
+ // Each step's remark starts with its kind ("navigate: …", "wait: …", "analyze: …", "assert: …").
56
+ // Only an assert compares the page with what the scenario expects.
57
+ const checked = (steps) => steps.some((s) => s.status === "done" && /^assert:/i.test(s.remark));
58
+ // A later successful result for the same step supersedes a failed attempt at that step.
59
+ const failedAssert = (steps) => steps.findLast((s, i) => s.status === "failed" && /^assert:/i.test(s.remark) && !steps.slice(i + 1).some((later) => later.step === s.step && later.status === "done"));
60
+ function reconciledEnd(end, steps) {
61
+ const failed = end?.status === "passed" && failedAssert(steps);
62
+ return failed && end ? { ...end, status: "failed", reason: failed.remark } : end;
63
+ }
64
+ export function outcomeOf(end, steps) {
65
+ // A vague objective lets Kane open the page, wait, and call that a pass.
66
+ if (end?.status === "passed")
67
+ return failedAssert(steps) ? "failed" : checked(steps) ? "passed" : "unsure";
68
+ if (end?.status !== "failed" || INFRA.test(end.reason ?? ""))
69
+ return "error";
70
+ // An unresolved false assertion is a failure even when Kane blames the scenario.
71
+ return end.verdict?.family === "automation_bug" && !failedAssert(steps) ? "unsure" : "failed";
72
+ }
73
+ const RECHECK = "the check failed, but Kane blames the scenario; running it once more to be sure";
74
+ // Kane is good at reaching a goal, so on its own it routes around a broken button (a key press, another
75
+ // link) and passes. A user who clicks the button and gets the wrong screen has found a bug.
76
+ const NO_WORKAROUNDS = "Do each step once, the way it is described. If a click or a key press does something other than what " +
77
+ "the step expects, the check fails: don't retry it, and don't reach the goal another way (other " +
78
+ "buttons, links, keyboard shortcuts, typing the URL). Waiting for a slow page to load is fine.";
79
+ export function kaneObjective(objective) {
80
+ return `${objective}\n\n${NO_WORKAROUNDS}`;
81
+ }
82
+ export async function runScenario(scenario, o) {
83
+ checkScenarioId(scenario.id);
84
+ let earlier = 0;
85
+ const again = (last, why) => {
86
+ earlier += last.end?.credits_consumed ?? 0;
87
+ logLine(`[${scenario.id}] ${why}`);
88
+ o.onEvent?.({ type: "retry", id: scenario.id, error: why });
89
+ return runOnce(scenario, o);
90
+ };
91
+ const settle = async (result) => {
92
+ for (let i = 2; i <= (o.noRetry ? 1 : o.attempts ?? 2) && result.outcome === "error" && !result.notSignedIn && !stopping(); i++) {
93
+ result = await again(result, result.error ?? "infra error");
94
+ }
95
+ return result;
96
+ };
97
+ let result = await settle(await runOnce(scenario, o));
98
+ // Kane gives the same verdict for a wrong value all over the app and for a page it misread (a
99
+ // heading that is there, reported as not visible). A wrong value is wrong again on a second
100
+ // run; a misreading rarely is. Disagreement leaves the check unconfirmed.
101
+ if (!o.noRetry && scenarioDoubted(result) && !stopping()) {
102
+ const first = result;
103
+ result = await settle(await again(result, RECHECK));
104
+ if (result.outcome === "passed") {
105
+ result = { ...result, outcome: "unsure", notChecked: "runs_disagreed", end: { ...result.end, reason: `The two runs disagreed. First run failed: ${first.end?.reason ?? "check failed"} Second run passed: ${result.end?.reason ?? "check passed"}` } };
106
+ }
107
+ }
108
+ return earlier ? { ...result, earlierCredits: earlier } : result;
109
+ }
110
+ async function runOnce(scenario, o) {
111
+ const log = (line) => {
112
+ try {
113
+ logLine(`[${scenario.id}] ${line}`);
114
+ }
115
+ catch { /* An unwritable output directory can break both the recording and the log. */ }
116
+ };
117
+ const logRecordingFailure = (what, error) => log(`${what} failed: ${String(error)}`);
118
+ const name = JSON.stringify(maskSecrets(scenario.id));
119
+ const kaneRun = (options) => timedAsync(`Kane scenario ${name}`, () => runKane(options));
120
+ const dir = join(o.outDir, scenario.id);
121
+ rmSync(dir, { recursive: true, force: true });
122
+ mkdirSync(dir, { recursive: true });
123
+ let prepared;
124
+ const target = scenario.resolvedTarget ?? resolveScenarioTarget(scenario, {}, process.env, process.cwd());
125
+ try {
126
+ prepared = await prepareTarget(target, { dir, url: target.kind === "web" ? new URL(scenario.url, o.baseUrl).href : undefined, headless: o.headless });
127
+ }
128
+ catch (e) {
129
+ return { scenario, outcome: "error", steps: [], end: undefined, clip: undefined, error: String(e) };
130
+ }
131
+ let stills;
132
+ const timeouts = kaneTimeouts(scenario);
133
+ try {
134
+ const recorder = prepared.recorder;
135
+ if (!recorder) {
136
+ let nativeClip;
137
+ const stopNative = () => {
138
+ const native = prepared.native;
139
+ if (native)
140
+ return nativeClip ??= timedAsync(`clip encode ${name}`, () => native.stop());
141
+ };
142
+ const kane = await kaneRun({ onEnd: () => { void stopNative()?.catch(() => { }); }, objective: kaneObjective(scenario.objective), ...timeouts, kaneArgs: prepared.kaneArgs, rawFile: join(dir, "kane.ndjson"), username: o.username, accessKey: o.accessKey, onStep: (step) => o.onEvent?.({ type: "step", id: scenario.id, step }) });
143
+ let recordingNote = prepared.metadata.recordingNote;
144
+ const clip = await stopNative()?.catch((e) => { recordingNote = `Native recording failed: ${String(e)}`; return undefined; });
145
+ const end = reconciledEnd(kane.end, kane.steps);
146
+ const outcome = outcomeOf(kane.end, kane.steps);
147
+ try {
148
+ writeFileSync(join(dir, "metadata.json"), JSON.stringify({ ...prepared.metadata, recordingNote }));
149
+ }
150
+ catch (e) {
151
+ logRecordingFailure("recording metadata", e);
152
+ }
153
+ const error = kane.timedOut
154
+ ? cutOffReason(kane.stderr, target, kane.steps.length > 0, timeouts.wallTimeoutSeconds)
155
+ : end?.reason || (end ? `Kane ended with status ${end.status}` : kaneError(kane.stderr) || "Kane exited without run_end");
156
+ return {
157
+ scenario, outcome, accountBalance: kane.accountBalance,
158
+ steps: kane.steps.map((s) => ({ ...s, ...(prepared.native && { at: Math.max(0, Date.parse(s.ts) / 1000 - prepared.native.started) }) })),
159
+ end, clip, recordingNote,
160
+ ...(outcome === "error" && { error }),
161
+ ...(!end && { notSignedIn: NOT_SIGNED_IN.test(kane.stderr) }),
162
+ };
163
+ }
164
+ live.scenario(scenario.id, { status: "running", steps: [], startedAt: Date.now() });
165
+ // A still for each click or typing with the cursor on it: the frame from just before it, or a
166
+ // new screenshot when there is none to use. Between actions, one every couple of seconds.
167
+ const still = (action) => {
168
+ if (live.on())
169
+ void recorder.snapshot().then((s) => s && live.frame(scenario.id, s, action));
170
+ };
171
+ recorder.onAction = (before) => {
172
+ if (before)
173
+ live.frame(scenario.id, before, true);
174
+ else
175
+ still(true);
176
+ };
177
+ stills = setInterval(() => still(false), 2000);
178
+ let focus = Promise.resolve(undefined);
179
+ const controller = new AbortController();
180
+ recorder.onUnexpectedPage = () => controller.abort();
181
+ if (recorder.unexpectedPage)
182
+ controller.abort();
183
+ const expected = target.kind === "web" ? expectedText(scenario.objective) : { check: "", literals: [], quoted: false };
184
+ const asserted = assertSnapshots(expected, () => recorder.visibleText());
185
+ const kane = await kaneRun({
186
+ signal: controller.signal,
187
+ objective: kaneObjective(scenario.objective), ...timeouts,
188
+ kaneArgs: prepared.kaneArgs,
189
+ rawFile: join(dir, "kane.ndjson"),
190
+ username: o.username,
191
+ accessKey: o.accessKey,
192
+ onStep: (s) => {
193
+ asserted.step(s);
194
+ live.step(scenario.id, s);
195
+ o.onEvent?.({ type: "step", id: scenario.id, step: s });
196
+ if (s.status !== "running" && s.remark)
197
+ log(`${s.status === "failed" ? "✗" : "·"} ${s.remark}`);
198
+ },
199
+ onEnd: (end) => (focus = recorder.locate(focusWords(end)).catch(() => undefined)),
200
+ });
201
+ clearInterval(stills);
202
+ // Drop the blank about:blank frames from before Kane's first navigation.
203
+ const start = Date.parse(kane.steps[0]?.ts ?? "") / 1000 || 0;
204
+ // The page reads and focus locator use the connection that stop() closes.
205
+ const assertedText = await asserted.text();
206
+ let focusRect = await focus;
207
+ const frames = target.kind === "web" ? recorder.frames.filter((f) => f.time >= start) : recorder.frames;
208
+ if (!frames.length && target.kind === "web" && !stopping()) {
209
+ log(`No frames selected after Kane's first step (${start}); received ${recorder.frames.length} screencast frames, last at ${recorder.frames.at(-1)?.time ?? "n/a"}`);
210
+ // The live stills are dashboard-only. Take a screenshot before closing the recorder.
211
+ const capture = Promise.withResolvers();
212
+ const timeout = setTimeout(() => capture.reject(new Error("Timed out capturing the page")), 10_000).unref();
213
+ const frame = await Promise.race([recorder.captureFrame(), capture.promise]).catch((e) => logRecordingFailure("clip screenshot", e));
214
+ clearTimeout(timeout);
215
+ if (frame) {
216
+ frames.push(frame);
217
+ // The screencast's focus rectangle may be from a different tab.
218
+ focusRect = undefined;
219
+ }
220
+ else {
221
+ // A screencast frame can arrive while we're waiting for the screenshot.
222
+ frames.push(...recorder.frames.filter((f) => f.time >= start));
223
+ }
224
+ if (!frames.length)
225
+ log("clip skipped: no usable frame or visible page screenshot");
226
+ }
227
+ const verdict = reconciledEnd(kane.end, kane.steps);
228
+ const contradiction = verdict?.status === "passed" ? textContradiction(expected, assertedText) : undefined;
229
+ const outcome = recorder.unexpectedPage ? "error" : contradiction ? "unsure" : outcomeOf(kane.end, kane.steps);
230
+ // Kane left without a verdict: all it said goes to the log, where the cause can be read later.
231
+ if (!kane.end)
232
+ log(`Kane exited with code ${kane.exitCode} and no verdict${kane.timedOut ? " (cut off by Proofed's time limit)" : ""}. Its stderr:\n${kane.stderr.trim() || "(empty)"}`);
233
+ // Kane's reason for such a pass is "Objective completed"; the report, the run file and the fixer show ours.
234
+ const end = verdict && outcome === "unsure" && verdict.status === "passed" ? { ...verdict, reason: contradiction ?? NOTHING_CHECKED } : verdict;
235
+ log(`→ ${outcome}${end?.reason ? `: ${end.reason}` : ""} (${frames.length} frames)`);
236
+ const error = recorder.unexpectedPage ? "Experimental desktop attach failed: Kane opened another page instead of using the chosen renderer" : kane.timedOut
237
+ ? cutOffReason(kane.stderr, target, kane.steps.length > 0, timeouts.wallTimeoutSeconds)
238
+ : (end?.reason || (end ? `Kane ended with status ${end.status}` : kaneError(kane.stderr) || "Kane exited without run_end"));
239
+ // A step starts when Kane announces it (the "running" event), not when it reports it done.
240
+ const announced = new Map(kane.steps.filter((s) => s.status === "running").map((s) => [s.step, s.ts]));
241
+ const marks = kane.steps.map((s) => Date.parse(announced.get(s.step) ?? s.ts) / 1000);
242
+ const recordingNote = !frames.length && recorder.frameWriteError
243
+ ? `Could not write screencast frames (${String(recorder.frameWriteError)})`
244
+ : undefined;
245
+ const made = await timedAsync(`clip encode ${name}`, async () => {
246
+ const { actions } = recorder.stop();
247
+ if (recordingNote) {
248
+ log(recordingNote);
249
+ return undefined;
250
+ }
251
+ const film = { frames, actions, focus: focusRect };
252
+ writeFileSync(join(dir, "film.json"), JSON.stringify(film));
253
+ const endpoint = prepared.montage ? await prepared.montage() : prepared.clipEndpoint;
254
+ return makeClip({ ...film, marks, endpoint }, join(dir, "clip"));
255
+ }).catch((e) => {
256
+ logRecordingFailure("clip", e);
257
+ return undefined;
258
+ });
259
+ const clip = made && { mp4: made.mp4, gif: made.gif, jpg: made.jpg };
260
+ return {
261
+ scenario,
262
+ accountBalance: kane.accountBalance,
263
+ ...(contradiction && { notChecked: "text_contradicted" }),
264
+ outcome,
265
+ steps: kane.steps.map((s, i) => ({ ...s, at: made?.marks[i] })),
266
+ end,
267
+ clip,
268
+ ...(recordingNote && { recordingNote }),
269
+ ...(outcome === "error" && { error }),
270
+ ...(!kane.end && NOT_SIGNED_IN.test(kane.stderr) && { notSignedIn: true }),
271
+ };
272
+ }
273
+ finally {
274
+ clearInterval(stills);
275
+ await prepared.cleanup().catch((e) => logRecordingFailure("target cleanup", e));
276
+ }
277
+ }
@@ -0,0 +1,10 @@
1
+ import { readConfig, readWorkflow, resolveScenarioTarget } from "../targets/target.js";
2
+ export function targetFilter(flags, { env, cwd }) {
3
+ const requested = flags.target ?? env.PROOFED_TARGET?.trim();
4
+ if (!requested)
5
+ return () => true;
6
+ // Validate the selector independently of execution settings for the selected scenarios.
7
+ const { kind } = resolveScenarioTarget({}, { target: requested, execution: "local" }, env, cwd);
8
+ const fallback = readConfig(cwd).target ?? readWorkflow(cwd)?.inputs.target ?? "web";
9
+ return (scenario) => (scenario.target ?? fallback) === kind;
10
+ }
@@ -0,0 +1,162 @@
1
+ const NEGATION = /\b(?:not|no|never|none|nothing|without|longer|cannot|neither|nor|hidden|gone|absent|missing|empty|removed|disappears?|disappeared)\b|n['’]t\b/i;
2
+ const QUOTED = /"([^"]+)"|“([^”]+)”|(?<![\p{L}\p{N}])'([^']+)'(?![\p{L}\p{N}])|‘([^’]+)’(?![\p{L}\p{N}])/gu;
3
+ const TRANSITION_SOURCE = /\b(?:chang(?:e[sd]?|ing)|go(?:es|ing)?|went|switch(?:es|ed|ing)?|transition(?:s|ed|ing)?|mov(?:e[sd]?|ing)|updat(?:e[sd]?|ing))\s+from\s+(?:either\s+)?\u0000\d+\u0000(?:\s+or\s+\u0000\d+\u0000)*(?=\s+to\s+)/gi;
4
+ // A comma-separated list ending in "or" is one group of alternatives.
5
+ const ALTERNATIVE_LIST = /\u0000\d+\u0000(?:\s*,\s*\u0000\d+\u0000)+\s*,?\s*or\s+\u0000\d+\u0000/gi;
6
+ // "list" alone is left out: in "Todo list contains Buy milk" it is a noun.
7
+ const VERB = /(?<=\s)(?:contains?|shows?|lists|includes?)(?=\s)/gi;
8
+ // Words of a description rather than of a label: "the cart", "Buy milk in the list", "now Free".
9
+ const DESCRIPTIVE = new Set(("the a an this that these those no one two three four five six seven eight nine ten each every all some any both several many its their his her it they them there " +
10
+ "is are was were be been has have had and or but in on under beside next below above with without at after before again now still only then also which who when where while should must can will would visible displayed shown listed").split(" "));
11
+ // "Recent orders section" is a heading plus a description of it; which part the page shows is a guess.
12
+ const UI_NOUN = /^(?:section|list|page|panel|menu|heading|title|table|card|dialog|modal|button|field|tab|link|row|column|item|option|entry|entries|result|label|message|area|bar|sidebar|header|footer|toolbar|form|input|output|box|badge|banner|toast|tooltip|popup|view|screen|window|icon|image|chart|grid|tile|chip|cell)s?$/i;
13
+ function onScreen(phrase) {
14
+ const words = phrase.split(/\s+/);
15
+ // One capitalised word after "Check that" is as often a description ("Cart", "Sidebar") as a label.
16
+ return /^\p{Lu}/u.test(phrase) && words.length >= 2 && words.length <= 6 && !/[,;:()[\]{}]/.test(phrase) &&
17
+ !words.some((w) => DESCRIPTIVE.has(w.toLowerCase())) && !UI_NOUN.test(words.at(-1));
18
+ }
19
+ export function expectedText(objective) {
20
+ const lines = objective.trim().split("\n").map((l) => l.trim().replace(/\s*Stop after this (?:check|assertion)\.?$/i, "")).filter(Boolean);
21
+ const quotes = [];
22
+ const masked = (lines.at(-1) ?? "").replace(/^(?:\d+[.)]|[-*])\s+/, "").replace(QUOTED, (...m) => `\u0000${quotes.push(m.slice(1, 5).find((s) => s !== undefined)) - 1}\u0000`);
23
+ const sentence = masked.split(/(?<=[.!?])\s+/).at(-1) ?? "";
24
+ const restore = (s) => s.replace(/\u0000(\d+)\u0000/g, (_, i) => `"${quotes[Number(i)]}"`);
25
+ const check = restore(sentence);
26
+ const body = /^(?:Check|Assert|Verify|Confirm|Ensure)(?: that)?\s+(.+?)\.?$/i.exec(sentence)?.[1];
27
+ if (!body || NEGATION.test(body))
28
+ return { check, literals: [], quoted: false };
29
+ const finalState = body.replace(TRANSITION_SOURCE, "").replace(ALTERNATIVE_LIST, (list) => list.replace(/,\s*(?:or\s+)?/gi, " or "));
30
+ const literalGroups = [];
31
+ let previousEnd = 0;
32
+ for (const match of finalState.matchAll(/\u0000(\d+)\u0000/g)) {
33
+ const literal = quotes[Number(match[1])].trim().replace(/[.,]+$/, "");
34
+ const previous = literalGroups.at(-1);
35
+ if (literal) {
36
+ if (previous && /^\s*(?:,\s*)?or\s+$/i.test(finalState.slice(previousEnd, match.index)))
37
+ previous.push(literal);
38
+ else
39
+ literalGroups.push([literal]);
40
+ }
41
+ previousEnd = literal ? match.index + match[0].length : 0;
42
+ }
43
+ if (literalGroups.length) {
44
+ const literals = [...new Set(literalGroups.flat())];
45
+ return { check, literals, quoted: true, ...(literalGroups.some((group) => group.length > 1) && { literalGroups }) };
46
+ }
47
+ const verbs = [...body.matchAll(VERB)];
48
+ if (verbs.length !== 1)
49
+ return { check, literals: [], quoted: false };
50
+ const at = verbs[0].index;
51
+ return { check, literals: [body.slice(0, at), body.slice(at + verbs[0][0].length)].map((s) => s.trim()).filter(onScreen), quoted: false };
52
+ }
53
+ // Lenient on purpose: whitespace, case, quote and dash styles, and how an element splits text.
54
+ const squash = (text) => text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[‘’ʼ]/g, "'").replace(/[“”«»„]/g, '"').replace(/[‐‑‒–—―−]/g, "-").replace(/\s+/gu, "");
55
+ export function textContradiction(expected, text) {
56
+ if (text === undefined)
57
+ return;
58
+ const captures = (typeof text === "string" ? [text] : text).map(squash);
59
+ const groups = expected.literalGroups ?? expected.literals.map((literal) => [literal]);
60
+ const missing = groups.filter((group) => !group.some((literal) => captures.some((capture) => capture.includes(squash(literal))))).flat();
61
+ if (!missing.length)
62
+ return;
63
+ const reason = `Proofed could not confirm Kane's pass: the page text had no ${missing.map((s) => JSON.stringify(s)).join(" or ")} when Kane made its final check.`;
64
+ return expected.quoted ? reason : `${reason} The words were taken as on-screen text from the unquoted check ${JSON.stringify(expected.check)}; quote the exact text the page should show to say what to compare.`;
65
+ }
66
+ // Read the page when Kane starts an assert and when it reports it done. A literal is missing only
67
+ // if it is absent from both reads of the same page. After the last action, prefer an assert that
68
+ // names the expected text. If Kane paraphrased or translated it, use its last completed assert.
69
+ export function assertSnapshots(expected, read) {
70
+ let chosen;
71
+ let announced;
72
+ return {
73
+ step(s) {
74
+ if (!expected.literals.length)
75
+ return;
76
+ if (!/^assert:/i.test(s.remark)) {
77
+ // Retain evidence across read-only analysis. An action or wait can change the page.
78
+ if (!/^analyze:/i.test(s.remark)) {
79
+ chosen = undefined;
80
+ announced = undefined;
81
+ }
82
+ return;
83
+ }
84
+ if (s.status === "running") {
85
+ announced = s.step;
86
+ const remark = squash(s.remark);
87
+ const names = expected.literals.every((literal) => remark.includes(squash(literal)));
88
+ if (names || !chosen?.names || chosen.step === s.step)
89
+ chosen = { step: s.step, names, reads: [read()] };
90
+ }
91
+ else if (announced !== s.step || (chosen?.step === s.step && s.status === "failed")) {
92
+ chosen = undefined;
93
+ }
94
+ else if (chosen?.step === s.step && chosen.reads.length === 1) {
95
+ chosen.reads.push(read());
96
+ }
97
+ },
98
+ async text() {
99
+ const [start, end] = await Promise.all(chosen?.reads ?? []);
100
+ if (start && end && start.session === end.session && start.document === end.document && start.href === end.href) {
101
+ return [start.text, end.text];
102
+ }
103
+ },
104
+ };
105
+ }
106
+ // Executed in the owned page. Text the DOM can't show (a canvas, a video, a plugin, a cross-origin
107
+ // frame, a closed shadow root) may hold the claimed words, so a page with any of them can't
108
+ // contradict. Images and icons can: their alt and labels are read, the pixels are not. A frame
109
+ // that is still loading shows the empty about:blank it started with, so it counts as unreadable.
110
+ export const VISIBLE_TEXT = `(() => {
111
+ let complete = true;
112
+ const parts = [document.title];
113
+ const text = [];
114
+ const read = (node) => {
115
+ if (node.nodeType === Node.TEXT_NODE) {
116
+ const parent = node.assignedSlot || node.parentElement || node.parentNode?.host;
117
+ if (!parent || parent.ownerDocument.defaultView.getComputedStyle(parent).visibility !== 'visible') return;
118
+ const range = node.ownerDocument.createRange();
119
+ range.selectNodeContents(node);
120
+ if ([...range.getClientRects()].some((rect) => rect.width > 0 && rect.height > 0)) text.push(node.data);
121
+ return;
122
+ }
123
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
124
+ const el = node;
125
+ const view = el.ownerDocument.defaultView;
126
+ const style = view.getComputedStyle(el);
127
+ if (style.display === 'none' || (style.display !== 'contents' && style.opacity === '0') || style.contentVisibility === 'hidden') return;
128
+ if (el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})) {
129
+ const tag = el.localName;
130
+ if (['canvas', 'video', 'object', 'embed'].includes(tag)) {
131
+ const r = el.getBoundingClientRect();
132
+ if (r.width > 1 && r.height > 1) complete = false;
133
+ }
134
+ if ((tag === 'input' && !['hidden', 'password'].includes(el.type)) || tag === 'textarea') parts.push(el.value, el.placeholder);
135
+ if (tag === 'select') parts.push(...[...el.selectedOptions].map((o) => o.text));
136
+ if (tag === 'img' || tag === 'area' || (tag === 'input' && el.type === 'image')) parts.push(el.alt);
137
+ if (tag === 'svg') parts.push(...[...el.querySelectorAll('title')].map((t) => t.textContent));
138
+ parts.push(el.getAttribute('aria-label'), el.getAttribute('title'));
139
+ for (const pseudo of ['::before', '::after']) {
140
+ const pseudoStyle = view.getComputedStyle(el, pseudo);
141
+ const content = pseudoStyle.content;
142
+ if (!content || content === 'none' || content === 'normal' || pseudoStyle.display === 'none' || pseudoStyle.visibility !== 'visible' || pseudoStyle.opacity === '0') continue;
143
+ if (/counter/.test(content)) complete = false;
144
+ parts.push(content.replace(/attr\\(([\\w-]+)\\)/g, (_, name) => JSON.stringify(el.getAttribute(name) || '')).match(/"(?:[^"\\\\]|\\\\.)*"/g)?.map((s) => { try { return JSON.parse(s); } catch { return s.slice(1, -1); } }).join('') ?? '');
145
+ }
146
+ if (!el.shadowRoot && view.customElements.get(tag)) complete = false;
147
+ if (tag === 'iframe') {
148
+ try {
149
+ const doc = el.contentDocument, src = el.getAttribute('src');
150
+ const loading = !doc || doc.readyState !== 'complete' || (src && !/^about:/i.test(src) && doc.URL === 'about:blank');
151
+ if (!loading && doc.documentElement) read(doc.documentElement); else complete = false;
152
+ }
153
+ catch { complete = false; }
154
+ }
155
+ }
156
+ // Visit the rendered children, including slotted nodes and direct shadow text.
157
+ const slotted = el.localName === 'slot' ? el.assignedNodes?.() : undefined;
158
+ for (const child of slotted?.length ? slotted : (el.shadowRoot || el).childNodes) read(child);
159
+ };
160
+ read(document.documentElement);
161
+ return complete ? [text.join(''), ...parts].filter(Boolean).join('\\n') : null;
162
+ })()`;
package/dist/env.js ADDED
@@ -0,0 +1,6 @@
1
+ export const env = (name, fallback) => {
2
+ const value = process.env[name]?.trim() || fallback;
3
+ if (value === undefined)
4
+ throw new Error(`Missing ${name}`);
5
+ return value;
6
+ };
@@ -0,0 +1,21 @@
1
+ import { askClaude } from "./claude.js";
2
+ import { askCodex } from "./codex.js";
3
+ import { DEFAULT_FIXER, providerOf, resolveFixer } from "./models.js";
4
+ import { maskSecrets } from "../secrets.js";
5
+ export function configuredFixer() {
6
+ const provider = process.env.PROOFED_PROVIDER;
7
+ const useLegacyModel = provider?.trim().toLowerCase() !== "codex";
8
+ const fixer = resolveFixer({
9
+ provider,
10
+ model: process.env.PROOFED_MODEL || (useLegacyModel ? process.env.PROOFED_CLAUDE_MODEL : undefined),
11
+ effort: process.env.PROOFED_EFFORT || process.env.PROOFED_CLAUDE_EFFORT,
12
+ }, DEFAULT_FIXER);
13
+ if ("error" in fixer)
14
+ throw new Error(fixer.error);
15
+ return fixer;
16
+ }
17
+ // The answer goes into the PR, the commit message and the dashboard.
18
+ export function askAgent(prompt, options) {
19
+ const answer = providerOf(options.model) === "codex" ? askCodex(prompt, options) : askClaude(prompt, options);
20
+ return answer.ok ? { ...answer, text: maskSecrets(answer.text) } : { ...answer, message: maskSecrets(answer.message) };
21
+ }
@@ -0,0 +1,30 @@
1
+ import { executableCommand } from "../process.js";
2
+ // One headless Claude Code run, for the fixer (fix.ts) and for the setup PR's scenarios (generate.ts).
3
+ import { spawnSync } from "node:child_process";
4
+ import { withoutJobSecrets } from "../secrets.js";
5
+ export function askClaude(prompt, o) {
6
+ const command = executableCommand("claude", ["-p", prompt, "--output-format", "json", "--permission-mode", o.permissionMode ?? "acceptEdits", "--max-turns", String(o.maxTurns ?? 40),
7
+ "--model", o.model, "--effort", o.effort,
8
+ ...(o.tools ? ["--tools", o.tools.join(",")] : []),
9
+ "--allowedTools", o.allowedTools.join(",")]);
10
+ const run = spawnSync(command.file, command.args,
11
+ // Its Bash runs the app's build, which may need the rest of the environment.
12
+ { windowsHide: true, env: withoutJobSecrets(process.env, ["CLAUDE_CODE_OAUTH_TOKEN"]), encoding: "utf8", maxBuffer: 50 * 1024 * 1024, timeout: o.timeoutMs, killSignal: "SIGKILL" });
13
+ if (run.error && "code" in run.error && run.error.code === "ETIMEDOUT") {
14
+ return { ok: false, message: `Claude Code didn't finish within ${Math.round((o.timeoutMs ?? 0) / 60_000)} minutes` };
15
+ }
16
+ let parsed = {};
17
+ try {
18
+ parsed = JSON.parse(run.stdout);
19
+ }
20
+ catch {
21
+ // No JSON at all: Claude Code itself failed to start.
22
+ }
23
+ const text = parsed.result?.trim() ?? "";
24
+ // Usage limits and API errors come back as is_error with the message in `result`.
25
+ if (parsed.api_error_status === 404)
26
+ return { ok: false, message: `the model \`${o.model}\` isn't available to this Claude account` };
27
+ if (run.status !== 0 || parsed.is_error)
28
+ return { ok: false, message: text || run.stderr?.trim() || "Claude Code failed" };
29
+ return { ok: true, text };
30
+ }
@@ -0,0 +1,71 @@
1
+ import { executableCommand } from "../process.js";
2
+ import { pathValue } from "../which.js";
3
+ // One headless Codex run, shared by the fixer and scenario writer.
4
+ import { spawnSync } from "node:child_process";
5
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ export function askCodex(prompt, o) {
9
+ const dir = mkdtempSync(join(tmpdir(), "proofed-codex-"));
10
+ try {
11
+ const output = join(dir, "answer.txt");
12
+ // Keep job tokens and unrelated provider keys out of the agent process.
13
+ const env = Object.fromEntries(["PATH", "PATHEXT", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "USER", "TMPDIR", "TMP", "TEMP", "SystemRoot", "CODEX_HOME", "CODEX_API_KEY"]
14
+ .flatMap((name) => pathValue(process.env, name) === undefined ? [] : [[name, pathValue(process.env, name)]]));
15
+ // Codex has no equivalent of Claude's per-command/per-path tool allowlist. The sandbox
16
+ // limits writes, blocks network and protects .git; the prompt restricts shell use to
17
+ // reading code and the build. fix.ts/generate.ts undo edits outside their allowed files.
18
+ // Ignore personal config/rules instead of inheriting personal MCP servers and permission overrides.
19
+ const command = executableCommand("codex", [
20
+ "exec", "--ignore-user-config", "--ignore-rules", "--ephemeral", "--color", "never",
21
+ "--sandbox", "workspace-write", "-c", 'approval_policy="never"',
22
+ "-c", "sandbox_workspace_write.network_access=false",
23
+ "-c", 'shell_environment_policy.inherit="none"',
24
+ "-c", `shell_environment_policy.set.PATH=${JSON.stringify(env.PATH ?? "/usr/bin:/bin")}`,
25
+ "-c", "sandbox_workspace_write.exclude_slash_tmp=true",
26
+ "-c", "sandbox_workspace_write.exclude_tmpdir_env_var=true",
27
+ "-c", `model_reasoning_effort=${JSON.stringify(o.effort)}`,
28
+ "--model", o.model, "--json", "--output-last-message", output, "-",
29
+ ], env);
30
+ const run = spawnSync(command.file, command.args, {
31
+ windowsHide: true, input: prompt, cwd: o.cwd, env, encoding: "utf8", maxBuffer: 50 * 1024 * 1024,
32
+ timeout: o.timeoutMs ?? 10 * 60_000, killSignal: "SIGKILL",
33
+ });
34
+ if (run.error) {
35
+ if ("code" in run.error && run.error.code === "ETIMEDOUT")
36
+ return { ok: false, message: `Codex didn't finish within ${Math.round((o.timeoutMs ?? 600_000) / 60_000)} minutes` };
37
+ return { ok: false, message: `Codex couldn't start: ${run.error.message}. Install @openai/codex and run codex login.` };
38
+ }
39
+ const errors = [];
40
+ let failed = false;
41
+ for (const line of run.stdout.split("\n")) {
42
+ try {
43
+ const event = JSON.parse(line);
44
+ if (event.type === "turn.failed")
45
+ failed = true;
46
+ if (event.type === "error" || event.type === "turn.failed")
47
+ errors.push(event.error?.message || event.message || "Codex turn failed");
48
+ }
49
+ catch { /* CLI diagnostics are not always JSON. */ }
50
+ }
51
+ const detail = [...errors, run.stderr.trim()].filter(Boolean).join("\n");
52
+ if (run.status !== 0 || failed) {
53
+ if (/usage limit|rate.limit|quota|429/i.test(detail))
54
+ return { ok: false, message: `Codex usage limit reached. Try again after it resets. ${detail}` };
55
+ if (/model.*(?:not found|does not exist|not supported|not available|unavailable|unknown)|unknown model|model_not_found/i.test(detail))
56
+ return { ok: false, message: `The model \`${o.model}\` isn't available to this Codex account. ${detail}` };
57
+ if (/not logged|unauthorized|401|authentication|api.key|sign.in|login required/i.test(detail))
58
+ return { ok: false, message: `Codex isn't logged in. Run codex login, or provide CODEX_API_KEY. ${detail}` };
59
+ return { ok: false, message: detail || "Codex failed without an error message" };
60
+ }
61
+ let text = "";
62
+ try {
63
+ text = readFileSync(output, "utf8").trim();
64
+ }
65
+ catch { /* No final message. */ }
66
+ return text ? { ok: true, text } : { ok: false, message: "Codex finished without a final answer" };
67
+ }
68
+ finally {
69
+ rmSync(dir, { recursive: true, force: true });
70
+ }
71
+ }