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,139 @@
1
+ const MAIN = `proofed: check web, mobile and Electron scenarios with Kane CLI.
2
+
3
+ Usage
4
+ proofed check --json Run affected scenarios; spends Kane credits
5
+ proofed check --only <id> --json Run one scenario from proofed list
6
+ proofed check "<behavior>" --json Check a behavior no scenario covers
7
+ add --dry-run to any check Plan it with its credit estimate; free
8
+ proofed list --json Which scenarios a change touches, and their cost; free
9
+ proofed doctor --json Setup problems and fixes; check runs its own; free
10
+ proofed mcp Serve Proofed tools over stdio from the project root
11
+ proofed hook claude-stop Run affected checks when Claude Code is about to stop
12
+ proofed <command> --help All flags and JSON fields
13
+ proofed --version
14
+
15
+ Setup
16
+ Node 22.18+, Kane CLI signed in; Chrome for web and Electron, ffmpeg for clips.
17
+ Local mobile needs Apple Silicon macOS; cloud mobile needs a TestMu real-device plan.
18
+ Install: npm install -g proofed-cli | pnpm add -g proofed-cli | bun add -g proofed-cli
19
+ Without installing: npx proofed-cli | pnpm dlx proofed-cli | bunx proofed-cli
20
+ Update: npm install -g proofed-cli@latest.
21
+ Uninstall: npm uninstall -g proofed-cli.
22
+ App settings come from flags, env, .proofed/config.json, or the Proofed workflow.
23
+
24
+ Results
25
+ JSON stdout is one document; progress is on stderr, details in .proofed-out/.
26
+ Exit 0: passed or nothing to run; 1: failed; 2: not_checked or error; 3: setup/usage;
27
+ 130: interrupted. not_checked is not a pass. Fix error.fix for exit 3.
28
+ On failed, read reason and diagnosis, fix the cause, then run rerun.
29
+ failedCheck: "scenario_doubted" is Kane's opinion; review the scenario before editing it.
30
+ A first web run is estimated at 30 credits per scenario, 1 to 4 minutes.
31
+ Mobile/Electron cost is unknown without history. Web runs up to 3 at a time by default; other targets serially.
32
+ Cached passes cost nothing. Use --no-cache to run them again.
33
+ Use --no-retry when another paid attempt is forbidden.
34
+ Give checks at least 10 minutes; don't interrupt them.`;
35
+ const CHECK = `proofed check [text] [flags]
36
+
37
+ Runs the scenarios the local change touches with Kane and says what broke.
38
+ The local change: files that differ from the merge base with --base, committed or not, plus new
39
+ files git doesn't ignore. Nothing changed: nothing runs (exit 0). Not a git repo: every scenario runs.
40
+ With [text], Kane checks just that, e.g. proofed check "the cart total updates when I press +".
41
+
42
+ Which scenarios
43
+ --base <rev> Compare against this (default: origin/HEAD, origin/main, origin/master, main, master)
44
+ --only <id,id> Exactly these (ids from proofed list)
45
+ --all Every scenario
46
+ --scenarios <dir> Where they are (default .proofed/scenarios, env PROOFED_SCENARIOS)
47
+
48
+ Where the app is (flag, then env, then .proofed/config.json, then the Proofed workflow step)
49
+ --url <url> Where it runs (env PROOFED_URL), e.g. http://localhost:5173
50
+ --serve <cmd> Starts it when the URL doesn't answer; stopped at the end (env PROOFED_SERVE)
51
+ --build <cmd> Builds before --serve, or before mobile/Electron checks (env PROOFED_BUILD)
52
+ --install <cmd> Installs the app's dependencies before the build, when node_modules is
53
+ missing or older than package.json or the lockfile (env PROOFED_INSTALL;
54
+ default: the workflow's install, else the app's package manager)
55
+ --reuse With a build set, a URL that already answers stops the check (exit 3): it
56
+ may be an old build. --reuse tests what is running; its passes aren't cached
57
+ --serve-timeout <s> How long the URL gets to answer after --serve (default 60)
58
+
59
+ Target (flag, env, scenario, config, workflow, default)
60
+ --target <kind> web (default), ios, android or experimental desktop; filters scenario files
61
+ --execution <kind> local (default) or cloud (mobile only)
62
+ --app <path|APP…> Mobile artifact/APP ID or desktop executable
63
+ --device <name> Exact mobile device name
64
+ --os-version <v> Mobile OS version
65
+ --launch <cmd> Owned desktop launch command with remote debugging
66
+ --cdp-endpoint <url> Desktop browser CDP endpoint; requires launch, app or --reuse
67
+ Local mobile: Apple Silicon macOS. Cloud mobile: TestMu real-device automation plan.
68
+ Target env vars: PROOFED_TARGET, PROOFED_EXECUTION, PROOFED_APP, PROOFED_DEVICE,
69
+ PROOFED_OS_VERSION, PROOFED_LAUNCH, PROOFED_CDP_ENDPOINT.
70
+
71
+ Running
72
+ --dry-run Show what would run and the credit estimate; spends nothing
73
+ --no-cache Run scenarios whose pass is cached, too
74
+ --no-retry One attempt per scenario, including infrastructure errors and doubted checks
75
+ --concurrency <n> Web scenarios at a time (default 3, env PROOFED_CONCURRENCY); other targets serial
76
+ --headed Show Chrome
77
+ --out <dir> Clips, logs, cache and result.json (default .proofed-out, env PROOFED_OUT)
78
+ --verbose Also print Kane's steps and Chrome's log (always in <out>/run.log)
79
+ --json stdout gets one JSON document and nothing else
80
+
81
+ JSON (also written to <out>/result.json)
82
+ ok, exitCode, summary, counts {passed, failed, not_checked, error, skipped}, base, url,
83
+ changedFiles, out, dryRun, app ("started" | "reused" | null), credits, estimatedCredits, seconds, next, rerun (re-runs
84
+ everything that didn't pass),
85
+ skipped [{id, name, why}], scenarios [{id, name, file, outcome, cached, cachedAt, objective,
86
+ target, recordingNote, reason, notChecked ("nothing_asserted" | "scenario_doubted" |
87
+ "runs_disagreed" | "text_contradicted"), failedCheck ("scenario_doubted"),
88
+ diagnosis (Kane's opinion), suggestion,
89
+ failedStep, steps [{remark, failed}], pageError, clip {mp4, jpg}, kaneReport, credits, creditsSource ("kane_estimate"), accountBalance {before, after, debit},
90
+ estimatedCredits, seconds, rerun}]
91
+ failedCheck is only set on failed checks Kane blames on the scenario. suggestion gives the
92
+ conditional next step: if the app change was intended, update the scenario; otherwise fix the app.
93
+ credits is Kane’s estimate, not an attributed account debit.
94
+ First web estimate: 30 credits; mobile/Electron estimatedCredits is null without history.
95
+ accountBalance is the whole account debit; attribution to this scenario is unknown.
96
+ Interrupted runs can spend unreported credits.
97
+ Proofed couldn't run: {ok: false, exitCode: 3, error: {code, message, fix}}
98
+ Interrupted: the same shape with exitCode 130 and scenarios [...] for what had finished
99
+
100
+ Before anything is built, the Kane login is checked with TestMu (kane-cli balance, free): without
101
+ one the check stops with exit 3 and error.code "kane_not_signed_in"; with LT_USERNAME and
102
+ LT_ACCESS_KEY that TestMu rejects, error.code "kane_keys_rejected".
103
+
104
+ Exit codes: 0 passed, 1 failed, 2 not_checked or error, 3 couldn't run, 130 interrupted.`;
105
+ const LIST = `proofed list [flags]
106
+
107
+ Every scenario with its id, name, start URL and paths, whether the local change touches it, and
108
+ whether a pass of it is cached. A file that doesn't parse is shown with its error (exit 3).
109
+ Spends nothing. JSON includes selected and estimatedCredits per scenario, plus the total.
110
+ Untouched scenarios and cached passes cost zero; first web runs are estimated at 30 credits.
111
+ Mobile/Electron estimatedCredits is null without history.
112
+
113
+ Target flags and their environment variables: as for proofed check.
114
+ --base <rev> Compare against this (default: the remote's default branch)
115
+ --all Select every scenario for the cost estimate
116
+ --url <url> The app's URL, for the cache (default: as proofed check finds it)
117
+ --scenarios <dir> Default .proofed/scenarios
118
+ --out <dir> Where the cache is (default .proofed-out)
119
+ --json One JSON document: {ok, exitCode, base, url, estimatedCredits, scenarios [...], errors [{file, message}]}`;
120
+ const DOCTOR = `proofed doctor [flags]
121
+
122
+ Checks Node, git, the scenarios, Kane CLI (installed, signed in, credits left) and target setup.
123
+ Web checks include Chrome, optional ffmpeg and where the app is. Mobile checks inspect artifacts
124
+ and local tools/devices; desktop checks inspect CDP. Installs and launches nothing. Every
125
+ problem comes with the command or step that fixes it. Uses only Kane's free commands.
126
+ Exit 0 when proofed check can run, else 3.
127
+
128
+ Target flags and their environment variables: as for proofed check.
129
+ --url, --serve, --build, --install As for proofed check
130
+ --scenarios <dir> Default .proofed/scenarios
131
+ --json {ok, exitCode, checks [{name, status: ok | warn | fail, detail, fix}]}`;
132
+ const HELP = {
133
+ check: CHECK,
134
+ list: LIST,
135
+ doctor: DOCTOR,
136
+ mcp: "proofed mcp\n\nServe proofed_list, proofed_doctor and proofed_check over stdio from the project root.",
137
+ hook: "proofed hook claude-stop\n\nRead a Claude Code Stop event from stdin and run affected checks.",
138
+ };
139
+ export const helpText = (command) => command ? HELP[command] : MAIN;
@@ -1,14 +1,17 @@
1
+ import { readKaneVersion } from "../kane/kaneversion.js";
1
2
  // `proofed list`: every scenario, whether the local change touches it and whether a pass of it is
2
3
  // cached. Reads files and git only; spends nothing.
3
4
  import { join } from "node:path";
4
- import { CACHE_FILE, cacheKey, readCache } from "./cache.js";
5
- import { findBase, localChanges, mergeBaseOf } from "./changes.js";
5
+ import { CACHE_FILE, canReusePass, cacheKey, estimate, readCache } from "./cache.js";
6
+ import { findBase, localChanges, mergeBaseOf } from "../changes.js";
6
7
  import { outDirOf, scenariosDirOf, scenariosMissing } from "./check.js";
7
8
  import { colorOn, palette, since, textWidth, truncate } from "./render.js";
8
- import { errorDoc } from "./result.js";
9
- import { affectedBy, readScenarios } from "./scenarios.js";
10
- import { SetupError } from "./setuperror.js";
11
- import { isHttpUrl, resolveTarget } from "./target.js";
9
+ import { errorDoc } from "../report/result.js";
10
+ import { affectedBy, readScenarios } from "../scenarios.js";
11
+ import { SetupError } from "../setuperror.js";
12
+ import { isHttpUrl, resolveTarget, resolveScenarioTarget } from "../targets/target.js";
13
+ import { targetFilter } from "./targetfilter.js";
14
+ import { findKane } from "../which.js";
12
15
  export function list(flags, io) {
13
16
  const c = palette(colorOn(io.env, !!io.stdout.isTTY));
14
17
  try {
@@ -18,7 +21,7 @@ export function list(flags, io) {
18
21
  if (!(e instanceof SetupError))
19
22
  throw e;
20
23
  if (flags.json)
21
- io.stdout.write(`${JSON.stringify(errorDoc(e), null, 2)}\n`);
24
+ io.stdout.write(`${JSON.stringify(errorDoc(e))}\n`);
22
25
  else
23
26
  io.stderr.write(`${c.red("✗")} ${e.message}\n ${c.dim("Fix")} ${e.fix}\n`);
24
27
  return 3;
@@ -31,35 +34,44 @@ export function list(flags, io) {
31
34
  const base = findBase(io.cwd, flags.base);
32
35
  const changed = base.rev ? localChanges(io.cwd, base.rev) : undefined;
33
36
  const baseId = base.rev ? mergeBaseOf(io.cwd, base.rev) : "";
34
- const url = resolveTarget({ flags: { url: flags.url }, env: io.env, cwd: io.cwd }).url?.value;
37
+ const target = resolveTarget({ flags: { url: flags.url, build: flags.build }, env: io.env, cwd: io.cwd });
38
+ const url = target.url?.value;
39
+ const version = readKaneVersion(findKane(io.env).path ?? "kane-cli", io.env);
35
40
  const cache = readCache(join(outDirOf(flags, io), CACHE_FILE));
36
- const scenarios = loaded.scenarios.map((s) => {
41
+ const scenarios = loaded.scenarios.filter(targetFilter(flags, io)).map((s) => {
42
+ s = { ...s, resolvedTarget: resolveScenarioTarget(s, flags, io.env, io.cwd) };
37
43
  const hit = cache.passes[s.id];
38
- const cached = !!(hit && url && isHttpUrl(url) && changed && hit.key === cacheKey(s, new URL(s.url, url).href, changed, undefined, baseId));
44
+ const cached = !!(hit && canReusePass(s, target.build?.value) && (s.resolvedTarget.kind !== "web" || (url && isHttpUrl(url))) && changed && version !== "unknown" && hit.key === cacheKey(s, s.resolvedTarget.kind === "web" ? new URL(s.url, url).href : "", changed, undefined, baseId, version, target));
45
+ const touched = changed ? affectedBy([s], changed).length > 0 : null;
46
+ const selected = flags.all || (touched !== false && changed?.length !== 0);
39
47
  return {
48
+ target: s.resolvedTarget,
40
49
  id: s.id,
41
50
  name: s.name,
42
51
  file: s.file,
43
52
  url: s.url,
44
53
  paths: s.paths,
45
- touched: changed ? affectedBy([s], changed).length > 0 : null,
54
+ touched,
55
+ selected,
56
+ estimatedCredits: selected && !cached ? estimate(cache, s, version) : 0,
46
57
  cached,
47
58
  ...(cached && { cachedAt: hit.passedAt }),
48
59
  };
49
60
  });
50
61
  const exitCode = loaded.errors.length ? 3 : 0;
51
62
  if (flags.json) {
52
- const doc = { ok: exitCode === 0, exitCode, base: base.rev ?? null, changedFiles: changed?.length ?? null, url: url ?? null, scenarios, errors: loaded.errors };
53
- io.stdout.write(`${JSON.stringify(doc, null, 2)}\n`);
63
+ const doc = { ok: exitCode === 0, exitCode, base: base.rev ?? null, changedFiles: changed?.length ?? null, url: url ?? null, scenarios, errors: loaded.errors, estimatedCredits: scenarios.some((s) => s.estimatedCredits === null) ? null : scenarios.reduce((sum, s) => sum + (s.estimatedCredits ?? 0), 0) };
64
+ io.stdout.write(`${JSON.stringify(doc)}\n`);
54
65
  return exitCode;
55
66
  }
56
- const where = base.rev ? `changes against ${base.rev}: ${changed.length} file${changed.length === 1 ? "" : "s"}` : `${base.why}, so every scenario runs`;
67
+ const where = flags.all ? "all scenarios selected" : base.rev ? `changes against ${base.rev}: ${changed.length} file${changed.length === 1 ? "" : "s"}` : `${base.why}, so every scenario runs`;
57
68
  io.stdout.write(`${scenarios.length} scenario${scenarios.length === 1 ? "" : "s"} in ${dir}; ${where}.\n\n`);
58
69
  const rows = [
59
- ["ID", "NAME", "URL", "CHANGED", "CACHED", "PATHS"],
70
+ ["ID", "NAME", "TARGET", "URL", "CHANGED", "CACHED", "PATHS"],
60
71
  ...scenarios.map((s) => [
61
72
  s.id,
62
73
  s.name,
74
+ `${s.target.kind}/${s.target.execution}`,
63
75
  s.url,
64
76
  s.touched === null ? "?" : s.touched ? "yes" : "no",
65
77
  s.cachedAt ? `pass ${since(s.cachedAt)}` : "no",
@@ -1,70 +1,72 @@
1
+ import { checkedWhere, fixRefusal, targetScenarios } from "../fix/fixtarget.js";
2
+ import { configuredFixer } from "../fix/agent.js";
3
+ import { fixSetup } from "../fix/fixsetup.js";
4
+ import { providerOf } from "../fix/models.js";
1
5
  // Shared by the PR check (cli.ts) and the fix loop (fix.ts).
2
- import { execFileSync } from "node:child_process";
3
- import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { appendFileSync, writeFileSync } from "node:fs";
4
7
  import { join } from "node:path";
5
- import { editComment, listReports, minimize, postComment, publishClips, repoFromEnv, setStatus } from "./github.js";
6
- import { live } from "./live.js";
7
- import { log } from "./log.js";
8
- import { crashResult, findCrashes } from "./precheck.js";
9
- import { buildReport, outdated, postsNew } from "./report.js";
10
- import { nothingAsked } from "./requests.js";
11
- import { creditsOf, scenarioDoubted, runScenario } from "./run.js";
12
- import { FAILED_CHECK_ACTION, FAILED_CHECK_REASON, RUN_FILE } from "./runfile.js";
13
- import { affectedBy, loadScenariosOr } from "./scenarios.js";
14
- export const env = (name, fallback) => {
15
- const value = process.env[name]?.trim() || fallback;
16
- if (value === undefined)
17
- throw new Error(`Missing ${name}`);
18
- return value;
19
- };
20
- export function readEvent() {
21
- return process.env.GITHUB_EVENT_PATH ? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")) : {};
8
+ import { clipUrl, editComment, listReports, minimize, postComment, publishClips, setStatus } from "../github.js";
9
+ import { live } from "../report/live.js";
10
+ import { log } from "../log.js";
11
+ import { crashResult, findCrashes } from "../targets/precheck.js";
12
+ import { buildReport, outdated, postsNew } from "../report/report.js";
13
+ import { descriptionCheckNote } from "../action/requests.js";
14
+ import { runScenario } from "./run.js";
15
+ import { creditsOf, scenarioDoubted } from "../report/runresult.js";
16
+ import { FAILED_CHECK_ACTION, FAILED_CHECK_REASON, RUN_FILE } from "../report/runfile.js";
17
+ import { maskSecrets } from "../secrets.js";
18
+ import { SetupError } from "../setuperror.js";
19
+ import { timedAsync } from "../timing.js";
20
+ export function runConcurrency(env, explicit) {
21
+ const configured = env.PROOFED_CONCURRENCY?.trim();
22
+ const concurrency = explicit ?? (configured ? Number(configured) : 3);
23
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
24
+ const setting = explicit === undefined ? "PROOFED_CONCURRENCY" : "Concurrency";
25
+ throw new SetupError("concurrency_invalid", `${setting} must be a whole number of 1 or more.`, "Set PROOFED_CONCURRENCY to a positive integer or pass --concurrency.");
26
+ }
27
+ return concurrency;
22
28
  }
23
- export const ctx = () => {
24
- const token = process.env.GITHUB_TOKEN;
25
- return {
26
- repo: token && process.env.GITHUB_REPOSITORY ? repoFromEnv(token) : undefined,
27
- runUrl: process.env.GITHUB_RUN_ID
28
- ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
29
- : undefined,
30
- outDir: env("PROOFED_OUT", ".proofed-out"),
31
- };
32
- };
33
- export const changedFiles = (base, head = "HEAD") => execFileSync("git", ["diff", "--name-only", `${base}...${head}`], { encoding: "utf8" }).split("\n").filter(Boolean);
34
- // The base branch as the runner sees it (origin/main), so the diff and any scenarios read from it
35
- // are current even for a PR whose recorded base commit is weeks old. Falls back to that commit.
36
- export function baseRev(base) {
37
- try {
38
- execFileSync("git", ["rev-parse", "--verify", "--quiet", `origin/${base.ref}`], { stdio: "ignore" });
39
- return `origin/${base.ref}`;
29
+ // Web scenarios get their own Chrome and run side by side; native and desktop checks run serially.
30
+ // A start page that crashes while loading fails its scenarios without Kane (see precheck.ts).
31
+ export async function runAll(scenarios, outDir, requestedConcurrency, o = {}) {
32
+ const concurrency = runConcurrency(process.env, requestedConcurrency);
33
+ if (!o.preselected)
34
+ scenarios = targetScenarios(scenarios);
35
+ const baseUrl = o.baseUrl ?? process.env.PROOFED_URL ?? "";
36
+ if (!baseUrl && scenarios.some((s) => s.resolvedTarget.kind === "web"))
37
+ throw new Error("Missing PROOFED_URL for web scenarios");
38
+ live.track(scenarios);
39
+ if (!scenarios.some((s) => s.resolvedTarget.kind !== "web"))
40
+ return runGroup(scenarios, concurrency, outDir, baseUrl, o);
41
+ const groups = new Map();
42
+ for (const [index, scenario] of scenarios.entries()) {
43
+ const kind = scenario.resolvedTarget.kind;
44
+ const group = groups.get(kind) ?? [];
45
+ group.push({ scenario, index });
46
+ groups.set(kind, group);
40
47
  }
41
- catch {
42
- return base.sha;
48
+ const results = new Array(scenarios.length);
49
+ for (const [kind, group] of groups) {
50
+ const ran = await runGroup(group.map(({ scenario }) => scenario), kind === "web" ? concurrency : 1, outDir, baseUrl, o);
51
+ for (const [i, { index }] of group.entries())
52
+ results[index] = ran[i];
43
53
  }
54
+ return results;
44
55
  }
45
- export function pickScenarios({ changed, only, rev }) {
46
- const all = loadScenariosOr(env("PROOFED_SCENARIOS", ".proofed/scenarios"), rev);
47
- const selected = only?.length ? all.filter((s) => only.includes(s.id)) : changed ? affectedBy(all, changed) : all;
48
- return { selected, skipped: all.filter((s) => !selected.includes(s)).map((s) => s.name) };
49
- }
50
- // Every scenario gets its own Chrome, so they can run side by side; Kane is mostly waiting on its backend.
51
- // A start page that crashes while loading fails its scenarios without Kane (see precheck.ts).
52
- export async function runAll(scenarios, outDir, concurrency = Number(process.env.PROOFED_CONCURRENCY) || 3, o = {}) {
53
- const baseUrl = o.baseUrl ?? env("PROOFED_URL");
56
+ async function runGroup(scenarios, concurrency, outDir, baseUrl, o) {
54
57
  const emit = o.onEvent ?? (() => { });
55
58
  for (const s of scenarios)
56
59
  emit({ type: "waiting", id: s.id });
57
60
  const urlOf = (s) => new URL(s.url, baseUrl).href;
58
- live.track(scenarios);
59
61
  const checking = Date.now();
60
- const crashes = await findCrashes([...new Set(scenarios.map(urlOf))], outDir);
62
+ const crashes = await findCrashes([...new Set(scenarios.filter((s) => s.resolvedTarget.kind === "web").map(urlOf))], outDir);
61
63
  const checkSeconds = Math.round((Date.now() - checking) / 1000);
62
64
  const results = new Array(scenarios.length);
63
65
  let next = 0;
64
66
  const worker = async () => {
65
67
  for (let i = next++; i < scenarios.length; i = next++) {
66
68
  const scenario = scenarios[i];
67
- const crash = crashes.get(urlOf(scenario));
69
+ const crash = scenario.resolvedTarget.kind === "web" ? crashes.get(urlOf(scenario)) : undefined;
68
70
  if (crash) {
69
71
  log(`✗ ${scenario.name}: ${urlOf(scenario)} crashed while loading (${crash.error}); Kane not run`);
70
72
  const result = { ...crashResult(scenario, crash), seconds: checkSeconds };
@@ -76,13 +78,25 @@ export async function runAll(scenarios, outDir, concurrency = Number(process.env
76
78
  log(`▶ ${scenario.name}`);
77
79
  emit({ type: "started", id: scenario.id });
78
80
  const started = Date.now();
81
+ const kind = scenario.resolvedTarget.kind;
82
+ const mobile = kind === "ios" || kind === "android";
83
+ // Mobile runs have no browser recorder to publish their status and Kane steps.
84
+ if (mobile)
85
+ live.scenario(scenario.id, { status: "running", steps: [], startedAt: started });
79
86
  const result = await runScenario(scenario, {
80
87
  baseUrl,
81
88
  outDir,
82
89
  username: process.env.LT_USERNAME,
83
90
  accessKey: process.env.LT_ACCESS_KEY,
84
91
  headless: o.headless,
85
- onEvent: o.onEvent,
92
+ noRetry: o.noRetry,
93
+ onEvent: mobile ? (event) => {
94
+ if (event.type === "step")
95
+ live.step(event.id, event.step);
96
+ if (event.type === "retry")
97
+ live.scenario(event.id, { steps: [], startedAt: Date.now() });
98
+ emit(event);
99
+ } : o.onEvent,
86
100
  });
87
101
  const timed = { ...result, seconds: Math.round((Date.now() - started) / 1000) };
88
102
  results[i] = timed;
@@ -90,10 +104,18 @@ export async function runAll(scenarios, outDir, concurrency = Number(process.env
90
104
  emit({ type: "finished", id: scenario.id, result: timed });
91
105
  }
92
106
  };
93
- await Promise.all(Array.from({ length: Math.min(concurrency, scenarios.length) }, worker));
107
+ // Preserve the first error to occur while the other workers finish.
108
+ let failure;
109
+ const workers = Array.from({ length: Math.min(concurrency, scenarios.length) }, () => worker().catch((reason) => {
110
+ failure ??= { reason };
111
+ throw reason;
112
+ }));
113
+ await Promise.allSettled(workers);
114
+ if (failure)
115
+ throw failure.reason;
94
116
  return results;
95
117
  }
96
- export const isBroken = (r) => r.outcome === "failed" || r.outcome === "error";
118
+ export const isBroken = (r) => !descriptionCheckNote(r) && (r.outcome === "failed" || r.outcome === "error");
97
119
  // Posts the report as a new comment or edits the current one (postsNew). A new one retires the reports
98
120
  // before it: folded as outdated and left without anything that reads as the report. Neither step can
99
121
  // fail the run; the newest report is the one everything reads.
@@ -109,13 +131,13 @@ export async function putReport(repo, pr, body, notify) {
109
131
  return posted;
110
132
  }
111
133
  // The dashboard's copy of the run. Steps are capped like the comment's, so the file stays small.
112
- // A description that asked for nothing isn't in it, as it isn't in the comment's count.
134
+ // The dashboard counts the same scenarios as the comment.
113
135
  export function runFile({ sha, results, skipped, runUrl, fix }, clips) {
114
136
  return {
115
137
  sha,
116
138
  runUrl,
117
139
  skipped,
118
- scenarios: results.filter((r) => !nothingAsked(r)).map((r) => ({
140
+ scenarios: results.filter((r) => !descriptionCheckNote(r)).map((r) => ({
119
141
  id: r.scenario.id,
120
142
  name: r.scenario.name,
121
143
  outcome: r.outcome,
@@ -129,6 +151,8 @@ export function runFile({ sha, results, skipped, runUrl, fix }, clips) {
129
151
  .map((s) => ({ remark: s.remark.slice(0, 200), ...(s.status === "failed" && { failed: true }), ...(s.at !== undefined && { at: s.at }) })),
130
152
  clip: clips.get(r.scenario.id),
131
153
  credits: r.end?.credits_consumed === undefined ? undefined : creditsOf(r),
154
+ creditsSource: "kane_estimate",
155
+ accountBalance: r.accountBalance,
132
156
  seconds: r.seconds,
133
157
  })),
134
158
  fix: fix && {
@@ -142,7 +166,10 @@ export function runFile({ sha, results, skipped, runUrl, fix }, clips) {
142
166
  },
143
167
  };
144
168
  }
145
- export async function publish(input) {
169
+ export function publish(input) {
170
+ return timedAsync("publish", () => publishRun(input));
171
+ }
172
+ async function publishRun(input) {
146
173
  const { repo, pr, sha, results, skipped, runUrl, outDir, fix, asked, previous, written, requested = false } = input;
147
174
  const clips = new Map();
148
175
  let runKey;
@@ -155,27 +182,36 @@ export async function publish(input) {
155
182
  // A crash's screenshot comes without a video.
156
183
  return [...(clip.mp4 ? [file("gif", clip.gif), file("mp4", clip.mp4)] : []), file("jpg", clip.jpg)];
157
184
  });
158
- const urls = await publishClips(repo, files);
159
185
  for (const f of files)
160
- clips.set(f.id, { ...clips.get(f.id), [f.kind]: urls.get(f.path) });
161
- // In a commit of its own, after the clips: the file holds their links.
186
+ clips.set(f.id, { ...clips.get(f.id), [f.kind]: clipUrl(repo, f.path) });
187
+ // Links use the final branch paths, so the clips and their index can be committed together.
162
188
  const local = join(outDir, RUN_FILE);
163
189
  writeFileSync(local, JSON.stringify(runFile(input, clips)));
164
- await publishClips(repo, [{ path: `${prefix}/${RUN_FILE}`, local }]);
190
+ await publishClips(repo, [...files, { path: `${prefix}/${RUN_FILE}`, local }]);
165
191
  runKey = prefix;
166
192
  }
167
193
  const repoUrl = repo && `https://github.com/${repo.owner}/${repo.name}`;
194
+ const fixer = configuredFixer();
195
+ const counted = results.filter((r) => !descriptionCheckNote(r));
196
+ const refusal = process.env.PROOFED_FIX === "false" ? undefined : fixRefusal(counted.filter((r) => !r.requestUnavailable).map((r) => r.scenario), process.env.PROOFED_BUILD);
168
197
  const body = buildReport({
169
- sha, results, skipped, clips, runUrl, fixEnabled: process.env.PROOFED_FIX !== "false", fix, asked, previous, repoUrl, runKey, written,
198
+ sha, results, skipped, clips, runUrl, fixEnabled: process.env.PROOFED_FIX !== "false", fixer, fix, asked, previous, repoUrl, runKey, written,
199
+ fixSetup: refusal ? { note: refusal, comment: false } : fixSetup(providerOf(fixer.model)),
170
200
  });
171
201
  writeFileSync(join(outDir, "report.md"), body);
172
202
  writeFileSync(join(outDir, "results.json"), JSON.stringify(results, null, 2));
173
- if (process.env.GITHUB_STEP_SUMMARY)
174
- appendFileSync(process.env.GITHUB_STEP_SUMMARY, body);
203
+ try {
204
+ if (process.env.GITHUB_STEP_SUMMARY)
205
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, body);
206
+ }
207
+ catch (e) {
208
+ if (fix?.status !== "fixed")
209
+ throw e;
210
+ console.log(`Couldn't write the fix step summary: ${maskSecrets(String(e))}`);
211
+ }
175
212
  const broken = results.filter(isBroken);
176
- const failed = results.filter((r) => r.outcome === "failed");
177
- const passed = results.filter((r) => r.outcome === "passed");
178
- const counted = results.filter((r) => !nothingAsked(r));
213
+ const failed = counted.filter((r) => r.outcome === "failed");
214
+ const passed = counted.filter((r) => r.outcome === "passed");
179
215
  if (repo && pr) {
180
216
  // The end of a fix is news too, either way it went.
181
217
  const comment = await putReport(repo, pr, body, requested || !!fix);
@@ -187,8 +223,10 @@ export async function publish(input) {
187
223
  ? ["error", `Kane couldn't finish: ${names(broken)}`]
188
224
  : passed.length < counted.length
189
225
  ? ["success", `${passed.length} passed, ${counted.length - passed.length} not checked`]
190
- : ["success", `${counted.length} scenario(s) pass in Chrome`];
191
- await setStatus(repo, sha, state, description, comment.html_url);
226
+ : counted.length === 0
227
+ ? ["success", "No scenarios to report"]
228
+ : ["success", `${counted.length} scenario(s) pass ${checkedWhere(counted.map((r) => r.scenario))}`];
229
+ await setStatus(repo, sha, state, failed.length && refusal ? refusal : description, comment.html_url);
192
230
  }
193
231
  return broken;
194
232
  }
@@ -1,10 +1,10 @@
1
1
  // What `proofed check` shows while it runs and when it's done. In a terminal (LiveView): a header,
2
2
  // one line per scenario redrawn in place, then what broke. Anywhere else (PlainView), for coding
3
3
  // agents and logs: no escape codes and no redraw, one line per event, a heartbeat at least every 30
4
- // seconds, then the same details. Colour is drawn by hand; there are no runtime dependencies.
5
- import { FAILED_CHECK_REASON } from "./runfile.js";
6
- import { creditsOf } from "./run.js";
7
- import { outcomeOf } from "./result.js";
4
+ // seconds, then the same details. This view draws its own terminal colors.
5
+ import { FAILED_CHECK_REASON } from "../report/runfile.js";
6
+ import { creditsOf } from "../report/runresult.js";
7
+ import { outcomeOf } from "../report/result.js";
8
8
  // FORCE_COLOR=0 and NO_COLOR turn colour off, FORCE_COLOR=1 turns it on, even in a pipe.
9
9
  export function colorOn(env, isTTY) {
10
10
  const force = env.FORCE_COLOR;
@@ -53,7 +53,7 @@ export function truncate(s, max) {
53
53
  export const clock = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
54
54
  export const duration = (seconds) => (seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`);
55
55
  const num = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
56
- export const credits = (n) => n === 0 ? "no credits reported" : `${num(n)} credit${n === 1 ? "" : "s"}`;
56
+ export const credits = (n) => n === 0 ? "no credits reported" : `${num(n)} credit${n === 1 ? "" : "s"} (Kane estimate)`;
57
57
  // "14:05" today, "Nov 14 14:05" before.
58
58
  export function since(iso, now = Date.now()) {
59
59
  const d = new Date(iso);
@@ -64,6 +64,8 @@ export const GLYPH = { passed: "✓", failed: "✗", not_checked: "?", error: "!
64
64
  export const WORD = { passed: "passed", failed: "failed", not_checked: "not checked", error: "error" };
65
65
  const tint = (c, o) => ({ passed: c.green, failed: c.red, not_checked: c.yellow, error: c.magenta })[o];
66
66
  const NOT_CHECKED = {
67
+ runs_disagreed: "The two runs disagreed; the check is not confirmed.",
68
+ text_contradicted: "The page text contradicts Kane’s passing check.",
67
69
  nothing_asserted: 'Kane finished without asserting anything on the page. Make the scenario end in a concrete check ("Check that …").',
68
70
  scenario_doubted: "Kane thinks the scenario text is wrong, not the app. Read what it saw, then fix the scenario or the app.",
69
71
  };
@@ -84,6 +86,8 @@ export function details(d, c) {
84
86
  if (o === "error")
85
87
  field("Why", "Kane couldn't finish the run. It says nothing about the app; run it again.");
86
88
  field("Kane saw", d.reason);
89
+ if (d.accountBalance)
90
+ field("Account", `${d.accountBalance.before} → ${d.accountBalance.after} (${d.accountBalance.debit} credits debited across the account; attribution unknown)`);
87
91
  if (d.failedCheck)
88
92
  field("Why", FAILED_CHECK_REASON);
89
93
  field(d.failedCheck ? "Kane thinks" : "Diagnosis", d.diagnosis);
@@ -115,7 +119,7 @@ export function ending(doc, c) {
115
119
  const ranNow = doc.scenarios.some((d) => !d.cached);
116
120
  lines.push("", `${glyph} ${c.bold(tally)}${c.dim(` · ${ranNow ? credits(doc.credits) : "0 credits"} · ${duration(doc.seconds)}`)}`);
117
121
  if (ranNow)
118
- lines.push("Credits are Kane's report; balance may drop slightly more.");
122
+ lines.push("Credits are Kane estimates; account debit can be higher.");
119
123
  if (parts.length && doc.exitCode !== 0)
120
124
  lines.push(doc.summary);
121
125
  if (doc.rerun)
@@ -123,9 +127,12 @@ export function ending(doc, c) {
123
127
  return lines;
124
128
  }
125
129
  // "about 1 to 4 minutes per scenario, 3 at a time, so 2 to 8 minutes in all"
126
- export function timing(count, concurrency) {
127
- const rounds = Math.ceil(count / Math.max(1, concurrency));
128
- return `about 1 to 4 minutes per scenario, ${concurrency} at a time, so ${rounds} to ${rounds * 4} minutes in all`;
130
+ export function timing(run, concurrency) {
131
+ const web = run.filter((s) => (s.resolvedTarget?.kind ?? s.target ?? "web") === "web").length;
132
+ const native = run.length - web;
133
+ const rounds = Math.ceil(web / Math.max(1, concurrency)) + native;
134
+ const parallel = native ? (web ? `${concurrency} web at a time, other targets 1 at a time` : "1 at a time") : `${concurrency} at a time`;
135
+ return `about 1 to 4 minutes per scenario, ${parallel}, so ${rounds} to ${rounds * 4} minutes in all`;
129
136
  }
130
137
  // Where each scenario is, from the run's events.
131
138
  export class Board {
@@ -162,7 +169,7 @@ function planLines(p, c) {
162
169
  `${c.bold("Proofed")}${p.dryRun ? " (dry run)" : ""}: ${p.dryRun ? "would check" : "checking"} ${p.run.length} of ${p.total} scenario(s), ${p.selection}${p.url ? `, at ${p.url}` : ""}.`,
163
170
  ];
164
171
  if (p.run.length)
165
- lines.push(`Estimate: about ${num(p.estimate)} Kane credits.`);
172
+ lines.push(p.estimate === null ? "Estimate: unknown; Kane reports the cost of this target after its first run." : `Estimate: about ${num(p.estimate)} Kane credits.`);
166
173
  if (p.cached.length)
167
174
  lines.push(`Cached passes, 0 credits: ${p.cached.map((s) => s.name).join(", ")}.`);
168
175
  return lines;
@@ -200,7 +207,7 @@ export class PlainView {
200
207
  for (const l of planLines(p, this.c))
201
208
  this.line(l);
202
209
  if (p.run.length && !p.dryRun)
203
- this.line(`Time: ${timing(p.run.length, p.concurrency)}. Do not interrupt: let it finish.`);
210
+ this.line(`Time: ${timing(p.run, p.concurrency)}. Do not interrupt: let it finish.`);
204
211
  }
205
212
  info(s) {
206
213
  this.line(s);
@@ -218,7 +225,7 @@ export class PlainView {
218
225
  const at = (r) => clock(Math.round((this.now() - (r.startedAt ?? this.started)) / 1000));
219
226
  const running = this.board.running().map((r) => `${r.id} ${at(r)}${r.remark ? ` at "${truncate(r.remark, 80)}"` : ""}`);
220
227
  const waiting = this.board.rows.filter((r) => r.state === "waiting").map((r) => r.id);
221
- this.stamp(`still running: ${running.join("; ") || "starting Chrome"}${waiting.length ? `. Waiting: ${waiting.join(", ")}` : ""}`);
228
+ this.stamp(`still running: ${running.join("; ") || "starting target"}${waiting.length ? `. Waiting: ${waiting.join(", ")}` : ""}`);
222
229
  }
223
230
  event(e) {
224
231
  const row = this.board?.row(e.id);
@@ -287,13 +294,13 @@ export class LiveView {
287
294
  const c = this.c;
288
295
  const parts = [
289
296
  `${p.dryRun ? "dry run: " : ""}${p.run.length} of ${p.total} scenario${p.total === 1 ? "" : "s"}`,
290
- ...(p.run.length ? [`~${num(p.estimate)} credits`] : []),
297
+ ...(p.run.length ? [`~${(p.estimate === null ? "unknown" : num(p.estimate))} credits`] : []),
291
298
  p.selection,
292
299
  ...(p.url ? [p.url] : []),
293
300
  ];
294
301
  this.print(`${c.bold("proofed")} ${truncate(parts.join(" · "), this.width() - 10)}`);
295
302
  if (p.run.length && !p.dryRun)
296
- this.print(c.dim(truncate(timing(p.run.length, p.concurrency), this.width() - 1)));
303
+ this.print(c.dim(truncate(timing(p.run, p.concurrency), this.width() - 1)));
297
304
  }
298
305
  // Also ends a phase: what it printed is its outcome.
299
306
  info(s) {
@@ -419,7 +426,7 @@ export class LiveView {
419
426
  const t = clock(Math.round((this.now() - (r.startedAt ?? this.now())) / 1000));
420
427
  const n = name(w - 4 - t.length);
421
428
  const room = w - 2 - textWidth(n) - 2 - t.length - 2;
422
- const said = r.retry ? `retrying: ${r.retry}` : (r.remark ?? "starting Chrome");
429
+ const said = r.retry ? `retrying: ${r.retry}` : (r.remark ?? "starting target");
423
430
  const remark = room >= 6 ? ` ${(r.retry ? c.yellow : c.dim)(truncate(said, room))}` : "";
424
431
  return `${c.cyan(spin)} ${c.bold(n)} ${t}${remark}`;
425
432
  }