proofed-cli 0.1.3 → 0.2.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.
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 +388 -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 +371 -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
@@ -1,20 +1,34 @@
1
1
  // Proofed's server, as the action talks to it: the job proves which repository it runs in with the
2
2
  // OIDC token GitHub gives a job that has `id-token: write` (site/src/worker/actions.ts checks it).
3
+ export function proofedServer(server) {
4
+ const url = new URL(server);
5
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) {
6
+ throw new Error("The Proofed server needs HTTPS outside localhost");
7
+ }
8
+ return url;
9
+ }
3
10
  // Set when the workflow names a Proofed server and may ask GitHub for an OIDC token.
4
11
  export const serverUrl = () => {
5
12
  const { ACTIONS_ID_TOKEN_REQUEST_URL: url, ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer, PROOFED_SERVER: server } = process.env;
6
- return url && bearer && server ? server : undefined;
13
+ if (!url || !bearer || !server)
14
+ return undefined;
15
+ try {
16
+ return proofedServer(server).href;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
7
21
  };
8
22
  // GitHub's tokens last five minutes; one is reused for four.
9
23
  const TOKEN_LASTS = 4 * 60_000;
10
24
  let token;
11
- export async function oidcToken() {
25
+ export async function oidcToken(signal = AbortSignal.timeout(10_000)) {
12
26
  if (token && Date.now() - token.at < TOKEN_LASTS)
13
27
  return token.value;
14
28
  const { ACTIONS_ID_TOKEN_REQUEST_URL: url = "", ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer } = process.env;
15
29
  const request = new URL(url);
16
30
  request.searchParams.set("audience", "proofed");
17
- const oidc = await fetch(request, { headers: { authorization: `bearer ${bearer}` } });
31
+ const oidc = await fetch(request, { headers: { authorization: `bearer ${bearer}` }, signal });
18
32
  const { value } = oidc.ok ? (await oidc.json()) : {};
19
33
  if (!value)
20
34
  throw new Error(`GitHub gave no OIDC token (${oidc.status})`);
package/dist/changes.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { gitPath } from "./paths.js";
1
2
  // What the local change is, for `proofed check`: every file that differs between the merge base
2
3
  // with the base branch and the working tree (committed, staged or not) plus new files git doesn't
3
4
  // ignore. A coding agent's edits are usually uncommitted, so the PR check's base...HEAD isn't enough.
@@ -15,6 +16,11 @@ const tries = (fn) => {
15
16
  return undefined;
16
17
  }
17
18
  };
19
+ export const changedFiles = (base, head = "HEAD") => git(process.cwd(), "diff", "--name-only", "--no-renames", "-z", `${base}...${head}`).split("\0").filter(Boolean);
20
+ // Use the runner's current remote-tracking commit for both the diff and fallback scenarios.
21
+ export function baseRev(base) {
22
+ return tries(() => git(process.cwd(), "rev-parse", "--verify", "--quiet", `refs/remotes/origin/${base.ref}^{commit}`)) ?? base.sha;
23
+ }
18
24
  export const BASES = ["origin/HEAD", "origin/main", "origin/master", "main", "master"];
19
25
  // The remote's default branch as origin/HEAD names it, else the usual names.
20
26
  export function findBase(cwd, asked) {
@@ -55,5 +61,5 @@ export function localChanges(cwd, base) {
55
61
  ...names(git(root, "diff", "--name-only", "--no-renames", "-z", mergeBaseOf(cwd, base))),
56
62
  ...names(git(root, "ls-files", "--others", "--exclude-standard", "--full-name", "-z")),
57
63
  ]);
58
- return [...files].map((f) => relative(here, join(root, f))).sort();
64
+ return [...files].map((f) => gitPath(relative(here, join(root, f)))).sort();
59
65
  }
@@ -8,7 +8,17 @@ const COMMON = {
8
8
  scenarios: { type: "string" },
9
9
  out: { type: "string" },
10
10
  };
11
+ const TARGET = {
12
+ "target": { type: "string" },
13
+ "execution": { type: "string" },
14
+ "app": { type: "string" },
15
+ "device": { type: "string" },
16
+ "os-version": { type: "string" },
17
+ "launch": { type: "string" },
18
+ "cdp-endpoint": { type: "string" },
19
+ };
11
20
  const APP = {
21
+ ...TARGET,
12
22
  url: { type: "string" },
13
23
  serve: { type: "string" },
14
24
  build: { type: "string" },
@@ -23,14 +33,17 @@ export const FLAGS = {
23
33
  all: { type: "boolean" },
24
34
  "dry-run": { type: "boolean" },
25
35
  "no-cache": { type: "boolean" },
36
+ "no-retry": { type: "boolean" },
26
37
  headed: { type: "boolean" },
27
38
  reuse: { type: "boolean" },
28
39
  concurrency: { type: "string" },
29
40
  "serve-timeout": { type: "string" },
30
41
  verbose: { type: "boolean" },
31
42
  },
32
- list: { ...COMMON, base: { type: "string" }, url: { type: "string" } },
43
+ list: { ...COMMON, ...TARGET, base: { type: "string" }, all: { type: "boolean" }, url: { type: "string" } },
33
44
  doctor: { ...COMMON, ...APP },
45
+ mcp: { help: COMMON.help },
46
+ hook: { help: COMMON.help },
34
47
  };
35
48
  export const COMMANDS = Object.keys(FLAGS);
36
49
  const isCommand = (word) => Object.hasOwn(FLAGS, word);
@@ -92,7 +105,8 @@ function parseFlags(command, args) {
92
105
  ? `proofed ${command} has no ${t.rawName}; it belongs to proofed ${elsewhere[0]}.`
93
106
  : `Unknown flag ${t.rawName} for proofed ${command}. Did you mean: ${closest(t.rawName, known)}?`);
94
107
  }
95
- if (type === "string" && (t.value === undefined || (t.inlineValue !== true && t.value.startsWith("--")))) {
108
+ const needsNonblank = t.name === "target" || t.name === "execution";
109
+ if (type === "string" && (t.value === undefined || (needsNonblank && !t.value.trim()) || (t.inlineValue !== true && t.value.startsWith("--")))) {
96
110
  throw new UsageError(`${t.rawName} needs a value, e.g. ${t.rawName} ${EXAMPLES[t.name] ?? "<value>"}`);
97
111
  }
98
112
  if (type === "boolean" && t.inlineValue)
@@ -121,6 +135,13 @@ function parseFlags(command, args) {
121
135
  help: on("help"),
122
136
  scenarios: str("scenarios"),
123
137
  out: str("out"),
138
+ target: str("target"),
139
+ execution: str("execution"),
140
+ app: str("app"),
141
+ device: str("device"),
142
+ os_version: str("os-version"),
143
+ launch: str("launch"),
144
+ cdp_endpoint: str("cdp-endpoint"),
124
145
  url: str("url"),
125
146
  serve: str("serve"),
126
147
  build: str("build"),
@@ -130,6 +151,7 @@ function parseFlags(command, args) {
130
151
  all: on("all"),
131
152
  dryRun: on("dry-run"),
132
153
  noCache: on("no-cache"),
154
+ noRetry: on("no-retry"),
133
155
  headed: on("headed"),
134
156
  reuse: on("reuse"),
135
157
  verbose: on("verbose"),
@@ -137,8 +159,14 @@ function parseFlags(command, args) {
137
159
  serveTimeout: count("serve-timeout"),
138
160
  };
139
161
  const text = positionals.join(" ").trim() || undefined;
140
- if (text && command !== "check")
162
+ if (command === "hook") {
163
+ if (!flags.help && (positionals.length !== 1 || text !== "claude-stop")) {
164
+ throw new UsageError("Expected proofed hook claude-stop.");
165
+ }
166
+ }
167
+ else if (text && command !== "check") {
141
168
  throw new UsageError(`proofed ${command} takes no text. To have Kane check it: proofed check "${text}"`);
169
+ }
142
170
  if (flags.only && flags.all)
143
171
  throw new UsageError("Use either --only or --all, not both.");
144
172
  if (text && (flags.only || flags.all))
@@ -0,0 +1,89 @@
1
+ import { matchesPath } from "../paths.js";
2
+ // Passes Proofed doesn't pay for twice. A coding agent runs the check again after each fix, and a
3
+ // scenario it didn't touch would cost another 20 to 30 credits to come out the same. A pass stays
4
+ // good while its scenario file, its start URL, the commit the change is measured from and the
5
+ // changed files in its `paths` (every changed file, when it has none) stay as they were. Only
6
+ // passes are kept; everything else runs again.
7
+ import { createHash } from "node:crypto";
8
+ import { readFileSync, writeFileSync, lstatSync, readlinkSync, readdirSync, statSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ export const CACHE_FILE = "cache.json";
11
+ // The demo-store runs reported 27 to 30 credits without accounting for the balance change.
12
+ export const DEFAULT_CREDITS = 30;
13
+ export function readCache(file) {
14
+ try {
15
+ const data = JSON.parse(readFileSync(file, "utf8"));
16
+ if (data.version === 1)
17
+ return { version: 1, passes: data.passes ?? {}, last: data.last ?? {} };
18
+ }
19
+ catch {
20
+ // Missing or unreadable: start over, the worst case is paying for a run again.
21
+ }
22
+ return { version: 1, passes: {}, last: {} };
23
+ }
24
+ export const writeCache = (file, cache) => writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`);
25
+ // Web runs have a known typical cost; native and desktop targets have none until their first run.
26
+ export const estimate = (cache, s, kaneVersion) => cache.last[historyKey(s, kaneVersion)]?.credits ?? ((s.resolvedTarget?.kind ?? "web") === "web" ? DEFAULT_CREDITS : null);
27
+ // The changed files a scenario depends on.
28
+ export const relevantChanges = (s, changed) => s.paths.length ? changed.filter((f) => s.paths.some((glob) => matchesPath(f, glob))) : changed;
29
+ const readOrUndefined = (file) => {
30
+ try {
31
+ return readFileSync(file);
32
+ }
33
+ catch {
34
+ return undefined; // Deleted in the change.
35
+ }
36
+ };
37
+ // `base`: the commit the change is measured from (mergeBaseOf).
38
+ export function cacheKey(s, startUrl, changed, read = readOrUndefined, base = "", kaneVersion = "", service) {
39
+ const hash = createHash("sha256");
40
+ // Length-prefixed, so no two different lists of parts hash the same.
41
+ const add = (part) => hash.update(`${typeof part === "string" ? Buffer.byteLength(part) : part.length}:`).update(part);
42
+ add(read(s.file) ?? s.objective);
43
+ add(startUrl);
44
+ if (s.resolvedTarget) {
45
+ const { sources, ...target } = s.resolvedTarget;
46
+ add(JSON.stringify(target));
47
+ add(kaneVersion);
48
+ if ("app" in target && target.app && !/^APP[\w-]+$/.test(target.app)) {
49
+ const digest = (file, appRoot = false) => {
50
+ try {
51
+ let stat = lstatSync(file);
52
+ if (stat.isSymbolicLink()) {
53
+ add(readlinkSync(file));
54
+ if (!appRoot)
55
+ return;
56
+ // Follow the app path itself. Links inside the artifact remain leaves.
57
+ stat = statSync(file);
58
+ }
59
+ if (stat.isDirectory())
60
+ for (const name of readdirSync(file).sort()) {
61
+ add(name);
62
+ digest(join(file, name));
63
+ }
64
+ else
65
+ add(readFileSync(file));
66
+ }
67
+ catch {
68
+ add("missing");
69
+ }
70
+ };
71
+ digest(target.app, true);
72
+ }
73
+ }
74
+ if (service && (s.resolvedTarget?.kind ?? s.target ?? "web") === "web" && (service.build || service.install)) {
75
+ add(JSON.stringify([service.build?.value, service.install?.value]));
76
+ }
77
+ add(base);
78
+ for (const file of relevantChanges(s, changed).toSorted()) {
79
+ add(file);
80
+ add(read(file) ?? "\0deleted");
81
+ }
82
+ return hash.digest("hex");
83
+ }
84
+ export function historyKey(s, version) {
85
+ return cacheKey({ ...s, file: "", paths: [], objective: s.id }, "", [], () => undefined, "", version);
86
+ }
87
+ // A configured native build must run before we know its artifact. Looking up the old artifact's
88
+ // pass first can skip the rebuild altogether, even when the fixer changed a file outside paths.
89
+ export const canReusePass = (s, build) => (s.resolvedTarget?.kind ?? s.target ?? "web") === "web" || !build?.trim();
@@ -4,22 +4,25 @@
4
4
  // as one JSON document with --json.
5
5
  import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
6
6
  import { join, resolve } from "node:path";
7
- import { CACHE_FILE, DEFAULT_CREDITS, cacheKey, estimate, readCache, writeCache } from "./cache.js";
8
- import { findBase, localChanges, mergeBaseOf, repoRoot } from "./changes.js";
9
- import { killChildren, stopChildren } from "./children.js";
10
- import { findChrome } from "./chrome.js";
11
- import { KEYS_FIX, kaneLogin, LOGIN_FIX } from "./kaneauth.js";
12
- import { setLog } from "./log.js";
13
- import { runAll } from "./pipeline.js";
7
+ import { CACHE_FILE, canReusePass, DEFAULT_CREDITS, cacheKey, historyKey, estimate, readCache, writeCache } from "./cache.js";
8
+ import { findBase, localChanges, mergeBaseOf, repoRoot } from "../changes.js";
9
+ import { killChildren, stopChildren } from "../children.js";
10
+ import { findChrome } from "../targets/chrome.js";
11
+ import { KEYS_FIX, kaneLogin, LOGIN_FIX } from "../kane/kaneauth.js";
12
+ import { setLog } from "../log.js";
13
+ import { runAll, runConcurrency } from "./pipeline.js";
14
14
  import { colorOn, LiveView, PlainView } from "./render.js";
15
- import { askedScenario } from "./requests.js";
16
- import { buildDoc, errorDoc, quote, sameCommand, scenarioDoc } from "./result.js";
17
- import { creditsOf } from "./run.js";
18
- import { affectedBy, readScenarios } from "./scenarios.js";
19
- import { answers, startApp } from "./serve.js";
20
- import { SetupError } from "./setuperror.js";
21
- import { isHttpUrl, resolveTarget } from "./target.js";
22
- import { findKane } from "./which.js";
15
+ import { askedScenario } from "../action/requests.js";
16
+ import { buildDoc, errorDoc, quote, sameCommand, scenarioDoc } from "../report/result.js";
17
+ import { creditsOf } from "../report/runresult.js";
18
+ import { affectedBy, readScenarios } from "../scenarios.js";
19
+ import { answers, buildApp, startApp } from "../targets/serve.js";
20
+ import { SetupError } from "../setuperror.js";
21
+ import { isHttpUrl, resolveTarget, resolveScenarioTarget } from "../targets/target.js";
22
+ import { targetFilter } from "./targetfilter.js";
23
+ import { readKaneVersion } from "../kane/kaneversion.js";
24
+ import { targetChecks } from "../targets/targetchecks.js";
25
+ import { findKane } from "../which.js";
23
26
  export const RESULT_FILE = "result.json";
24
27
  export const outDirOf = (flags, io) => resolve(io.cwd, flags.out || io.env.PROOFED_OUT?.trim() || ".proofed-out");
25
28
  export const scenariosDirOf = (flags, io) => flags.scenarios || io.env.PROOFED_SCENARIOS?.trim() || ".proofed/scenarios";
@@ -57,6 +60,13 @@ const fromNote = (s) => (s.from.startsWith("--") ? "" : ` (url from ${s.from})`)
57
60
  // the same way. Not --no-cache or --dry-run: those were about this run.
58
61
  function rerunFlags(flags) {
59
62
  const pass = [
63
+ ["--target", flags.target],
64
+ ["--execution", flags.execution],
65
+ ["--app", flags.app],
66
+ ["--device", flags.device],
67
+ ["--os-version", flags.os_version],
68
+ ["--launch", flags.launch],
69
+ ["--cdp-endpoint", flags.cdp_endpoint],
60
70
  ["--url", flags.url],
61
71
  ["--serve", flags.serve],
62
72
  ["--build", flags.build],
@@ -67,7 +77,7 @@ function rerunFlags(flags) {
67
77
  ["--out", flags.out],
68
78
  ["--concurrency", flags.concurrency?.toString()],
69
79
  ];
70
- const on = [flags.reuse && "--reuse", flags.headed && "--headed", flags.json && "--json"].filter((f) => !!f);
80
+ const on = [flags.reuse && "--reuse", flags.noRetry && "--no-retry", flags.headed && "--headed", flags.json && "--json"].filter((f) => !!f);
71
81
  return [...pass.flatMap(([name, v]) => (v ? [`${name} ${quote(v)}`] : [])), ...on];
72
82
  }
73
83
  export async function check(flags, text, io, view = makeView(flags, io)) {
@@ -81,7 +91,7 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
81
91
  ensureOut(out);
82
92
  writeFileSync(join(out, RESULT_FILE), `${JSON.stringify(doc, null, 2)}\n`);
83
93
  if (flags.json)
84
- io.stdout.write(`${JSON.stringify(doc, null, 2)}\n`);
94
+ io.stdout.write(`${JSON.stringify(doc)}\n`);
85
95
  };
86
96
  // Ctrl-C (or a kill) mid-run: Kane, every Chrome and the app go first, then the exit.
87
97
  // The run that was going ends on its own once Kane is killed; its result is dropped, the
@@ -119,7 +129,7 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
119
129
  }
120
130
  else if (doc.dryRun) {
121
131
  for (const d of doc.scenarios)
122
- view.info(`${d.cached ? "cached: " : "would run:"} ${d.id} (${d.name})${d.cached ? "" : `, about ${Math.round((d.estimatedCredits ?? 0) * 100) / 100} credits`}`);
132
+ view.info(`${d.cached ? "cached: " : "would run:"} ${d.id} (${d.name})${d.cached ? "" : `, ${d.estimatedCredits === null ? "unknown" : Math.round((d.estimatedCredits ?? 0) * 100) / 100} credits`}`);
123
133
  view.info(`${doc.summary}. Dry run: nothing ran, no credits spent.`);
124
134
  view.info(doc.next);
125
135
  view.close();
@@ -173,7 +183,11 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
173
183
  let skipped;
174
184
  let selection;
175
185
  if (text) {
176
- selected = [askedScenario("terminal", text)];
186
+ // A scenario's id or name as the text would otherwise pay for a vague check of those words.
187
+ const named = all.find((s) => [s.id, s.name].some((n) => n.toLowerCase() === text.trim().toLowerCase()));
188
+ if (named)
189
+ throw new SetupError("text_is_scenario", `"${text}" is the scenario ${named.id} in ${dir}, not a behavior to check.`, `Run that scenario: proofed check --only ${named.id}. Or describe the behavior in words: proofed check "<what to check>".`);
190
+ selected = [askedScenario("terminal", text, resolveScenarioTarget({}, flags, io.env, io.cwd))];
177
191
  skipped = all.map((s) => ({ id: s.id, name: s.name, why: "only your text is checked" }));
178
192
  selection = "your text";
179
193
  }
@@ -206,34 +220,51 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
206
220
  return buildDoc({ ...common, items: [], skipped, url: null, idle: { summary, next: `Nothing to check. To run every scenario anyway: ${sameCommand(rerun, "--all")}` } });
207
221
  }
208
222
  }
223
+ if (!text) {
224
+ const matches = targetFilter(flags, io);
225
+ const incompatible = selected.filter((s) => !matches(s));
226
+ if (flags.only && incompatible.length)
227
+ throw new SetupError("target_selection", "--only contains scenarios incompatible with --target", "Select ids with the requested target.");
228
+ skipped.push(...incompatible.map((s) => ({ id: s.id, name: s.name, why: "different target" })));
229
+ selected = selected.filter(matches);
230
+ }
231
+ selected = selected.map((s) => ({ ...s, resolvedTarget: resolveScenarioTarget(s, flags, io.env, io.cwd) }));
209
232
  const target = resolveTarget({ flags: { url: flags.url, serve: flags.serve, build: flags.build, install: flags.install }, env: io.env, cwd: io.cwd });
210
233
  const url = target.url?.value;
211
- if (url !== undefined && !isHttpUrl(url)) {
234
+ if (selected.some((s) => s.resolvedTarget.kind === "web") && url !== undefined && !isHttpUrl(url)) {
212
235
  throw new SetupError("url_invalid", `"${url}" (${target.url.from}) is not an http(s) URL.`, "Pass a full URL, e.g. --url http://localhost:5173");
213
236
  }
214
237
  const baseId = base?.rev ? mergeBaseOf(io.cwd, base.rev) : "";
215
238
  let appState;
239
+ const concurrency = runConcurrency(io.env, flags.concurrency);
240
+ const kane = findKane(io.env);
241
+ const kaneVersion = kane.path ? readKaneVersion(kane.path, io.env) : "unknown";
216
242
  const cacheFile = join(out, CACHE_FILE);
217
243
  const cache = readCache(cacheFile);
218
244
  const keys = new Map();
219
245
  const items = new Map();
220
246
  for (const s of selected) {
221
- if (s.file && url && changed && !flags.noCache) {
222
- const key = cacheKey(s, new URL(s.url, url).href, changed, undefined, baseId);
223
- keys.set(s.id, key);
224
- const hit = cache.passes[s.id];
225
- if (hit?.key === key)
247
+ const hit = cache.passes[s.id];
248
+ if (s.file && (s.resolvedTarget.kind !== "web" || url) && changed && (!flags.noCache || hit) && kaneVersion !== "unknown") {
249
+ const key = cacheKey(s, s.resolvedTarget.kind === "web" ? new URL(s.url, url).href : "", changed, undefined, baseId, kaneVersion, target);
250
+ // A forced check can replace or invalidate the matching pass it bypassed.
251
+ if (!flags.noCache || hit?.key === key)
252
+ keys.set(s.id, key);
253
+ if (!flags.noCache && (!flags.reuse || !target.build) && canReusePass(s, target.build?.value) && hit?.key === key) {
226
254
  items.set(s.id, { scenario: s, cached: hit });
255
+ }
227
256
  }
228
257
  if (!items.has(s.id))
229
- items.set(s.id, { scenario: s, estimate: s.file ? estimate(cache, s.id) : DEFAULT_CREDITS });
258
+ items.set(s.id, { scenario: s, estimate: estimate(cache, s, kaneVersion) });
230
259
  }
231
260
  const toRun = selected.filter((s) => "estimate" in items.get(s.id));
261
+ const needsHttp = toRun.some((s) => s.resolvedTarget.kind === "web");
232
262
  const cachedPasses = selected.flatMap((s) => {
233
263
  const item = items.get(s.id);
234
264
  return "cached" in item ? [{ id: s.id, name: s.name, cachedAt: item.cached.passedAt }] : [];
235
265
  });
236
- const estimatedCredits = toRun.reduce((sum, s) => sum + items.get(s.id).estimate, 0);
266
+ const estimates = toRun.map((s) => items.get(s.id).estimate);
267
+ const estimatedCredits = estimates.includes(null) ? null : estimates.reduce((sum, n) => sum + (n ?? 0), 0);
237
268
  const plan = {
238
269
  run: toRun,
239
270
  cached: cachedPasses,
@@ -241,7 +272,7 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
241
272
  selection,
242
273
  url,
243
274
  estimate: estimatedCredits,
244
- concurrency: flags.concurrency ?? (Number(io.env.PROOFED_CONCURRENCY) || 3),
275
+ concurrency,
245
276
  dryRun: flags.dryRun,
246
277
  };
247
278
  const showPlan = () => {
@@ -259,13 +290,12 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
259
290
  return docOf(selected.map((s) => items.get(s.id)));
260
291
  }
261
292
  // The cheap checks first: nothing starts unless Kane and Chrome are both there.
262
- const kane = findKane(io.env);
263
293
  if (!kane.path) {
264
294
  throw new SetupError("kane_missing", `Kane CLI not found (${kane.from}).`, io.env.KANE_CLI ? "Point KANE_CLI at the kane-cli binary, or unset it." : "npm install -g @testmuai/kane-cli, then kane-cli login");
265
295
  }
266
- if (!findChrome())
296
+ if (toRun.some((s) => ["web", "desktop"].includes(s.resolvedTarget.kind)) && !findChrome(io.env))
267
297
  throw new SetupError("chrome_missing", "Chrome not found.", "Install Google Chrome, or set CHROME_PATH to its binary.");
268
- if (!url) {
298
+ if (needsHttp && !url) {
269
299
  throw new SetupError("no_url", "Proofed doesn't know where the app runs.", `Pass --url http://localhost:5173 (and --serve "npm run dev" to have Proofed start it), set PROOFED_URL, or write .proofed/config.json: { "url": "http://localhost:5173", "serve": "npm run dev" }`);
270
300
  }
271
301
  const login = await kaneLogin(kane.path, io.env);
@@ -282,7 +312,7 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
282
312
  view.log(line);
283
313
  });
284
314
  showPlan();
285
- if (await answers(url)) {
315
+ if (needsHttp && await answers(url)) {
286
316
  // With a build configured, what answers was built from some earlier code, and a pass on it
287
317
  // would be a pass nobody saw.
288
318
  if (target.build && !flags.reuse) {
@@ -291,12 +321,12 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
291
321
  appState = "reused";
292
322
  view.info(`The app answers at ${url}; using it as it is${target.build ? " (--reuse: not rebuilt, passes are not cached)" : ""}.`);
293
323
  }
294
- else if (target.serve) {
324
+ else if (needsHttp && target.serve) {
295
325
  const logFile = join(out, "serve.log");
296
326
  writeFileSync(logFile, "");
297
327
  const t0 = Date.now();
298
328
  app = await startApp({
299
- url,
329
+ url: url,
300
330
  serve: target.serve.value,
301
331
  build: target.build?.value,
302
332
  install: target.install,
@@ -309,9 +339,20 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
309
339
  const from = [target.build && `build from ${target.build.from}`, `serve from ${target.serve.from}`].filter(Boolean).join(", ");
310
340
  view.info(`Started the app in ${Math.round((Date.now() - t0) / 1000)} s (${from}); its output is in ${logFile}`);
311
341
  }
312
- else {
342
+ else if (needsHttp) {
313
343
  throw new SetupError("app_not_reachable", `Nothing answers at ${url}${fromNote(target.url)}.`, `Start the app first, or pass the command that serves it: proofed check --serve "npm run dev"`);
314
344
  }
345
+ if (appState !== "started" && toRun.some((s) => s.resolvedTarget.kind !== "web") && (target.build || target.install)) {
346
+ await buildApp({ build: target.build?.value, install: target.install, cwd: target.dir, logFile: join(out, "build.log"), onPhase: (line) => view.phase(line) });
347
+ }
348
+ for (const s of toRun) {
349
+ if (s.resolvedTarget.kind !== "web" && keys.has(s.id))
350
+ keys.set(s.id, cacheKey(s, "", changed ?? [], undefined, baseId, kaneVersion));
351
+ const checks = await targetChecks(s.resolvedTarget, { env: io.env, launchPending: true });
352
+ const failed = checks.filter((c) => c.status === "fail");
353
+ if (failed.length)
354
+ throw new SetupError("target_not_ready", failed.map((c) => `${c.name}: ${c.detail}`).join("\n"), failed.map((c) => c.fix).join("\n"));
355
+ }
315
356
  view.start();
316
357
  const cacheable = !(appState === "reused" && target.build);
317
358
  const onEvent = (e) => {
@@ -320,11 +361,16 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
320
361
  return;
321
362
  finished.set(e.id, e.result);
322
363
  const key = keys.get(e.id);
323
- if (!key)
324
- return;
325
364
  if (e.result.end?.credits_consumed !== undefined)
326
- cache.last[e.id] = { credits: creditsOf(e.result) };
327
- if (e.result.outcome === "passed" && cacheable) {
365
+ cache.last[historyKey(selected.find((s) => s.id === e.id), kaneVersion)] = { credits: creditsOf(e.result) };
366
+ if (!key) {
367
+ // A forced failure invalidates the saved pass even when the version probe could not key it.
368
+ if (flags.noCache && kaneVersion === "unknown" && e.result.scenario.file && e.result.outcome !== "passed")
369
+ delete cache.passes[e.id];
370
+ writeCache(cacheFile, cache);
371
+ return;
372
+ }
373
+ if (e.result.outcome === "passed" && cacheable && (!flags.noCache || cache.passes[e.id]?.key === key)) {
328
374
  const clip = e.result.clip && { ...(e.result.clip.mp4 && { mp4: resolve(e.result.clip.mp4) }), jpg: resolve(e.result.clip.jpg) };
329
375
  cache.passes[e.id] = { key, passedAt: new Date().toISOString(), seconds: e.result.seconds, ...(clip && { clip }) };
330
376
  }
@@ -333,7 +379,7 @@ export async function check(flags, text, io, view = makeView(flags, io)) {
333
379
  }
334
380
  writeCache(cacheFile, cache);
335
381
  };
336
- const results = await runAll(toRun, out, plan.concurrency, { baseUrl: url, headless: !flags.headed, onEvent });
382
+ const results = await runAll(toRun, out, plan.concurrency, { baseUrl: url ?? "", headless: !flags.headed, noRetry: flags.noRetry, onEvent, preselected: true });
337
383
  // A login can run out between the login check and the runs; running the check again wouldn't help then either.
338
384
  if (results.some((r) => r.notSignedIn))
339
385
  throw notSignedIn("Kane CLI refused to run a scenario: it is not signed in. The scenarios it refused weren't checked.");
@@ -1,27 +1,31 @@
1
+ import { executableCommand } from "../process.js";
2
+ import { targetChecks } from "../targets/targetchecks.js";
1
3
  // `proofed doctor`: whether `proofed check` can run here, and the exact fix for what can't. It only
2
- // calls Kane's free commands (--version, balance); no run, no credits.
4
+ // calls Kane's free commands (--version, balance, doctor); no run, no credits.
3
5
  import { execFile } from "node:child_process";
4
6
  import { createRequire } from "node:module";
5
7
  import { promisify } from "node:util";
6
8
  import { DEFAULT_CREDITS } from "./cache.js";
7
9
  import { scenariosDirOf } from "./check.js";
8
- import { findBase } from "./changes.js";
9
- import { findChrome } from "./chrome.js";
10
- import { depsMissing, installCommand } from "./deps.js";
11
- import { KEYS_FIX, kaneLogin, LOGIN_FIX } from "./kaneauth.js";
10
+ import { findBase } from "../changes.js";
11
+ import { findChrome } from "../targets/chrome.js";
12
+ import { depsMissing, installCommand } from "../targets/deps.js";
13
+ import { KEYS_FIX, kaneLogin, LOGIN_FIX } from "../kane/kaneauth.js";
12
14
  import { colorOn, palette, stripAnsi } from "./render.js";
13
- import { readScenarios } from "./scenarios.js";
14
- import { answers } from "./serve.js";
15
- import { SetupError } from "./setuperror.js";
16
- import { isHttpUrl, resolveTarget } from "./target.js";
17
- import { findKane, findOnPath } from "./which.js";
15
+ import { readScenarios } from "../scenarios.js";
16
+ import { answers } from "../targets/serve.js";
17
+ import { SetupError } from "../setuperror.js";
18
+ import { isHttpUrl, resolveTarget, resolveScenarioTarget } from "../targets/target.js";
19
+ import { targetFilter } from "./targetfilter.js";
20
+ import { findKane, findOnPath } from "../which.js";
18
21
  const run = promisify(execFile);
19
22
  // The launcher's own gate, from bin/ next to both src/ and dist/.
20
- const { supported: nodeSupported, NEED: NODE_NEED } = createRequire(import.meta.url)("../bin/node-version.cjs");
23
+ const { supported: nodeSupported, NEED: NODE_NEED } = createRequire(import.meta.url)("../../bin/node-version.cjs");
21
24
  // Kane prints update notices around its answer; only the answer counts.
22
25
  async function kane(bin, args, env) {
23
26
  try {
24
- const { stdout, stderr } = await run(bin, args, { env, timeout: 20_000 });
27
+ const cmd = executableCommand(bin, args, env);
28
+ const { stdout, stderr } = await run(cmd.file, cmd.args, { env, windowsHide: true, timeout: 20_000 });
25
29
  return { ok: true, text: stripAnsi(`${stdout}\n${stderr}`) };
26
30
  }
27
31
  catch (e) {
@@ -29,6 +33,7 @@ async function kane(bin, args, env) {
29
33
  return { ok: false, text: stripAnsi(`${err.stdout ?? ""}\n${err.stderr ?? ""}`) };
30
34
  }
31
35
  }
36
+ export const ffmpegInstallHint = (platform = process.platform) => platform === "darwin" ? "brew install ffmpeg" : platform === "win32" ? "winget install Gyan.FFmpeg" : "sudo apt-get install ffmpeg";
32
37
  export async function doctorChecks(flags, io) {
33
38
  const checks = [];
34
39
  const add = (name, status, detail, fix) => checks.push({ name, status, detail, ...(fix && { fix }) });
@@ -54,6 +59,29 @@ export async function doctorChecks(flags, io) {
54
59
  add("Scenarios", "ok", `${loaded.scenarios.length} in ${dir}`);
55
60
  for (const e of loaded.errors)
56
61
  add("Scenario", "fail", `${e.file}: ${e.message}`, `Correct the frontmatter of ${e.file}: --- name, paths, url --- then the objective.`);
62
+ const targets = [];
63
+ let pendingBuild = false;
64
+ const setupFailure = (e) => {
65
+ if (!(e instanceof SetupError))
66
+ throw e;
67
+ add("Target", "fail", e.message, e.fix);
68
+ };
69
+ try {
70
+ pendingBuild = !!resolveTarget({ flags, env: io.env, cwd: io.cwd }).build;
71
+ const selected = loaded.scenarios.filter(targetFilter(flags, io));
72
+ for (const scenario of selected.length ? selected : [{}]) {
73
+ try {
74
+ targets.push(resolveScenarioTarget(scenario, flags, io.env, io.cwd));
75
+ }
76
+ catch (e) {
77
+ setupFailure(e);
78
+ }
79
+ }
80
+ }
81
+ catch (e) {
82
+ setupFailure(e);
83
+ }
84
+ const needsWeb = targets.some((t) => t.kind === "web");
57
85
  const found = findKane(io.env);
58
86
  if (!found.path) {
59
87
  add("Kane CLI", "fail", `not found (${found.from})`, io.env.KANE_CLI ? "Point KANE_CLI at the kane-cli binary, or unset it." : "npm install -g @testmuai/kane-cli");
@@ -71,20 +99,28 @@ export async function doctorChecks(flags, io) {
71
99
  add("Kane login", "ok", login.detail);
72
100
  const left = /credits:\s*([\d.,]+)/i.exec(login.balance ?? "")?.[1];
73
101
  if (login.state === "not_signed_in" || login.state === "keys_rejected") {
74
- add("Credits", "warn", "unknown until Kane accepts the login");
102
+ add("Credits", "warn", "unknown until Kane accepts the login", login.state === "keys_rejected" ? KEYS_FIX : LOGIN_FIX);
75
103
  }
76
104
  else if (left) {
77
105
  const n = Number(left.replace(/,/g, ""));
78
- add("Credits", n >= DEFAULT_CREDITS ? "ok" : "warn", `${Math.floor(n)} available; a first run is estimated at ${DEFAULT_CREDITS} credits`, n >= DEFAULT_CREDITS ? undefined : "Top up your TestMu account before running scenarios.");
106
+ add("Credits", n >= DEFAULT_CREDITS ? "ok" : "warn", `${Math.floor(n)} available; ${needsWeb ? `a first web run is estimated at ${DEFAULT_CREDITS} credits` : "the cost of a first mobile or desktop run is unknown"}`, n >= DEFAULT_CREDITS ? undefined : "Top up your TestMu account before running scenarios.");
79
107
  }
80
108
  else {
81
109
  add("Credits", "warn", "couldn't read the balance", "kane-cli balance");
82
110
  }
83
111
  }
84
- const chrome = findChrome();
85
- add("Chrome", chrome ? "ok" : "fail", chrome ?? "not found", chrome ? undefined : "Install Google Chrome, or set CHROME_PATH to its binary.");
112
+ for (const target of targets) {
113
+ for (const check of await targetChecks(target, { env: io.env, pendingBuild, launchPending: true }))
114
+ checks.push({ ...check, name: `${target.kind}: ${check.name}` });
115
+ }
116
+ if (targets.some((t) => ["web", "desktop"].includes(t.kind))) {
117
+ const chrome = findChrome(io.env);
118
+ add("Chrome", chrome ? "ok" : "fail", chrome ?? "not found", chrome ? undefined : "Install Google Chrome, or set CHROME_PATH to its binary.");
119
+ }
120
+ if (!needsWeb)
121
+ return checks;
86
122
  const ffmpeg = findOnPath("ffmpeg", io.env);
87
- add("ffmpeg", ffmpeg ? "ok" : "warn", ffmpeg ?? "not found: no clips, the verdicts still work", ffmpeg ? undefined : process.platform === "darwin" ? "brew install ffmpeg" : "sudo apt-get install ffmpeg");
123
+ add("ffmpeg", ffmpeg ? "ok" : "warn", ffmpeg ?? "not found: no clips, the verdicts still work", ffmpeg ? undefined : ffmpegInstallHint());
88
124
  try {
89
125
  const target = resolveTarget({ flags: { url: flags.url, serve: flags.serve, build: flags.build, install: flags.install }, env: io.env, cwd: io.cwd });
90
126
  const url = target.url;
@@ -114,7 +150,7 @@ export async function doctorChecks(flags, io) {
114
150
  else if (up)
115
151
  add("App", "ok", `${url.value} answers now`);
116
152
  else if (target.serve)
117
- add("App", "warn", `${url.value} doesn't answer now; proofed check starts it with the serve command`);
153
+ add("App", "ok", `not running, as expected: proofed check ${target.build ? "builds and starts" : "starts"} it at ${url.value}`);
118
154
  else
119
155
  add("App", "fail", `${url.value} doesn't answer and there is no serve command`, 'Start the app, or tell Proofed how: --serve "npm run dev", PROOFED_SERVE, or "serve" in .proofed/config.json');
120
156
  }
@@ -130,7 +166,7 @@ export async function doctor(flags, io) {
130
166
  const checks = await doctorChecks(flags, io);
131
167
  const exitCode = checks.some((c) => c.status === "fail") ? 3 : 0;
132
168
  if (flags.json) {
133
- io.stdout.write(`${JSON.stringify({ ok: exitCode === 0, exitCode, checks }, null, 2)}\n`);
169
+ io.stdout.write(`${JSON.stringify({ ok: exitCode === 0, exitCode, checks })}\n`);
134
170
  return exitCode;
135
171
  }
136
172
  const c = palette(colorOn(io.env, !!io.stdout.isTTY));