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,76 @@
1
+ // Why the report's fix box would do nothing in this repo: a workflow installed before Codex was an
2
+ // option passes the action no Codex credentials, and its condition reacts only to the Claude box.
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { providerLabel } from "./models.js";
6
+ // GITHUB_WORKFLOW_REF is owner/repo/.github/workflows/proofed.yml@refs/heads/main.
7
+ const workflowFile = (ref) => /^[^/]+\/[^/]+\/(.+?)@/.exec(ref ?? "")?.[1];
8
+ function workflowConditions(workflow) {
9
+ const lines = workflow.split(/\r?\n/);
10
+ const conditions = [];
11
+ const withoutComment = (line) => line.replace(/'(?:''|[^'])*'|"(?:\\.|[^"\\])*"|(^|\s)#.*$/g, (match, comment) => comment === undefined ? match : "");
12
+ for (let i = 0; i < lines.length; i++) {
13
+ const property = /^(\s*(?:-\s+)?)([\w-]+):\s*(.*)$/.exec(withoutComment(lines[i]));
14
+ if (!property)
15
+ continue;
16
+ let value = property[3];
17
+ const block = /^[>|][+-]?$/.test(value.trim());
18
+ if (block || property[2] === "if") {
19
+ const indent = property[1].length;
20
+ if (block)
21
+ value = "";
22
+ while (i + 1 < lines.length) {
23
+ const continuation = withoutComment(lines[i + 1]);
24
+ if (continuation.trim() && continuation.search(/\S/) <= indent)
25
+ break;
26
+ value += ` ${continuation.trim()}`;
27
+ i++;
28
+ }
29
+ }
30
+ if (property[2] === "if")
31
+ conditions.push(value);
32
+ }
33
+ return conditions;
34
+ }
35
+ const checksFor = (label) => new RegExp(`\\bcontains\\(\\s*github\\.event\\.comment\\.body\\s*,\\s*'- \\[x\\] \\*\\*Fix with ${label}\\*\\*'\\s*\\)`, "i");
36
+ const commandCondition = /(!\s*)?\b(?:contains|startsWith)\(\s*github\.event\.comment\.body\s*,\s*'\/proofed(?:\s+fix)?\s*'\s*\)/i;
37
+ const editedOnly = /\bgithub\.event\.action\s*(?:==\s*'edited'|!=\s*'created')/i;
38
+ const created = /\bgithub\.event\.action\s*==\s*'created'/i;
39
+ export function fixSetup(provider, env = process.env) {
40
+ const label = providerLabel(provider);
41
+ const file = workflowFile(env.GITHUB_WORKFLOW_REF);
42
+ // Only the check step says whether credentials were passed; elsewhere the flag is unset.
43
+ if ((provider === "codex" ? env.PROOFED_CODEX : env.PROOFED_CLAUDE) === "false") {
44
+ const inputs = provider === "codex"
45
+ ? "`codex-api-key: ${{ secrets.CODEX_API_KEY }}` or `codex-auth-json: ${{ secrets.CODEX_AUTH_JSON }}`"
46
+ : "`claude-code-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}`";
47
+ return {
48
+ note: `${label} is selected in Proofed. To fix with ${label}, add ${inputs} to the Proofed step in \`${file ?? "the workflow"}\`.`,
49
+ comment: false,
50
+ };
51
+ }
52
+ if (provider !== "codex" || !file)
53
+ return undefined;
54
+ let text;
55
+ try {
56
+ text = readFileSync(join(env.GITHUB_WORKSPACE ?? process.cwd(), file), "utf8");
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ const conditions = workflowConditions(text);
62
+ const claude = conditions.filter((condition) => checksFor("Claude").test(condition));
63
+ if (claude.every((condition) => checksFor("Codex").test(condition)))
64
+ return undefined;
65
+ // A command needs a branch that accepts a new comment without a ticked box.
66
+ const comment = claude.every((condition) => condition.split("||").some((branch) => {
67
+ const command = commandCondition.exec(branch);
68
+ return command && !command[1] && !editedOnly.test(branch) && !checksFor("Claude").test(branch) &&
69
+ (!editedOnly.test(condition) || created.test(branch));
70
+ }));
71
+ const change = "add `|| contains(github.event.comment.body, '- [x] **Fix with Codex**')` next to its Claude condition.";
72
+ return {
73
+ note: `\`${file}\` supports the **Fix with Claude** checkbox. ${comment ? `Comment \`/proofed fix\`, or ${change}` : `To show the Codex box, ${change}`}`,
74
+ comment,
75
+ };
76
+ }
@@ -0,0 +1,48 @@
1
+ import { resolveScenarioTarget } from "../targets/target.js";
2
+ import { targetFilter } from "../check/targetfilter.js";
3
+ import { timedAsync } from "../timing.js";
4
+ export const scenarioTarget = (s) => s.resolvedTarget ?? resolveScenarioTarget(s, {}, process.env, process.cwd());
5
+ export function targetScenarios(scenarios) {
6
+ const env = process.env;
7
+ const requested = env.PROOFED_TARGET?.trim();
8
+ const matchesTarget = targetFilter({}, { env, cwd: process.cwd() });
9
+ return scenarios
10
+ .filter((s) => !requested || (s.resolvedTarget ? s.resolvedTarget.kind === requested : !s.file || matchesTarget(s)))
11
+ .map((s) => ({ ...s, resolvedTarget: scenarioTarget(s) }));
12
+ }
13
+ export function checkedAt(s) {
14
+ const target = scenarioTarget(s);
15
+ if (target.kind === "web")
16
+ return "in Chrome";
17
+ if (target.kind === "desktop")
18
+ return "in the desktop app";
19
+ if (target.kind === "android")
20
+ return target.execution === "local" ? "on an Android emulator" : "on an Android device";
21
+ return target.execution === "local" ? "in an iOS simulator" : "on an iOS device";
22
+ }
23
+ export const checkedWhere = (scenarios) => [...new Set(scenarios.map(checkedAt))].join(" and ");
24
+ export const needsWeb = (scenarios) => scenarios.some((s) => scenarioTarget(s).kind === "web");
25
+ // Only the scenarios this fix must verify matter; an unrelated pre-uploaded app does not block it.
26
+ export function fixRefusal(scenarios, build) {
27
+ for (const s of scenarios) {
28
+ const target = scenarioTarget(s);
29
+ if (target.kind === "web")
30
+ continue;
31
+ if ((target.kind === "android" || target.kind === "ios") && /^APP[\w-]+$/.test(target.app ?? ""))
32
+ return `Fix didn't run: "${s.name}" uses a pre-uploaded TestMu APP ID. Set app to a build artifact path so Kane can check the rebuild.`;
33
+ if (target.kind === "desktop" && !target.launch && !target.app)
34
+ return `Fix didn't run: "${s.name}" has only a desktop CDP endpoint. Set launch or app so Proofed can restart the rebuilt app.`;
35
+ if (!build?.trim())
36
+ return `Fix didn't run: "${s.name}" needs a build command for its ${target.kind} target. Set PROOFED_BUILD (the action's build input) to rebuild the app before Kane checks it.`;
37
+ }
38
+ }
39
+ // Both attempts and the final check use runAll directly, never the CLI pass cache.
40
+ export async function checkFix(scenarios, serve, check) {
41
+ const stop = needsWeb(scenarios) ? await timedAsync("app ready", serve) : undefined;
42
+ try {
43
+ return await timedAsync("re-check", () => check(scenarios));
44
+ }
45
+ finally {
46
+ await stop?.();
47
+ }
48
+ }
@@ -0,0 +1,67 @@
1
+ // Shared with the dashboard; keep this file free of Node imports.
2
+ export const PROVIDERS = ["claude", "codex"];
3
+ export const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
4
+ export const EFFORTS = [...CLAUDE_EFFORTS, "ultra"];
5
+ // Codex IDs and efforts come from its authenticated model catalog (models_cache.json).
6
+ // Luna has no ultra; the CLI's ReasoningEffort enum also accepts max and ultra.
7
+ export const MODELS = [
8
+ { provider: "claude", name: "haiku", id: "claude-haiku-5-5", efforts: CLAUDE_EFFORTS },
9
+ { provider: "claude", name: "sonnet", id: "claude-sonnet-5-5", efforts: CLAUDE_EFFORTS },
10
+ { provider: "claude", name: "opus", id: "claude-opus-5-5", efforts: CLAUDE_EFFORTS },
11
+ { provider: "claude", name: "fable", id: "claude-fable-5-2", efforts: CLAUDE_EFFORTS },
12
+ { provider: "codex", name: "sol", id: "gpt-6.2-sol", efforts: EFFORTS },
13
+ { provider: "codex", name: "sol", id: "gpt-6.1-sol", efforts: EFFORTS },
14
+ { provider: "codex", name: "terra", id: "gpt-6.1-terra", efforts: EFFORTS },
15
+ { provider: "codex", name: "astra", id: "gpt-6-astra", efforts: EFFORTS },
16
+ { provider: "codex", name: "luna", id: "gpt-6-luna", efforts: CLAUDE_EFFORTS },
17
+ ];
18
+ export const DEFAULT_FIXER = { model: "claude-haiku-5-5", effort: "xhigh" };
19
+ export const providerOf = (model) => model.startsWith("gpt-") ? "codex" : "claude";
20
+ export const providerLabel = (provider) => provider === "codex" ? "Codex" : "Claude";
21
+ export const isProvider = (word) => PROVIDERS.some((p) => p === word);
22
+ export const isEffort = (word) => EFFORTS.some((e) => e === word);
23
+ export const isModelId = (text) => /^claude-[a-z0-9][a-z0-9.-]{2,60}$/.test(text) || MODELS.some((m) => m.provider === "codex" && m.id === text);
24
+ export const effortsFor = (model) => MODELS.find((m) => m.id === model)?.efforts ?? CLAUDE_EFFORTS;
25
+ export const defaultModel = (provider) => MODELS.find((m) => m.provider === provider).id;
26
+ export function modelLabel(id) {
27
+ if (providerOf(id) === "codex")
28
+ return id.replace(/^gpt-/, "GPT-").replace(/-(sol|terra|astra|luna)$/, (_, name) => ` ${name[0].toUpperCase()}${name.slice(1)}`);
29
+ const match = /^claude-([a-z]+)-(\d+)-(\d+)(?:-\d{8})?$/.exec(id);
30
+ if (!match)
31
+ return id;
32
+ const [, family = "", major, minor] = match;
33
+ return `${family[0].toUpperCase()}${family.slice(1)} ${major}.${minor}`;
34
+ }
35
+ export function describeFixer({ model, effort }) {
36
+ const label = modelLabel(model);
37
+ return `${label === model ? `\`${model}\`` : `${providerLabel(providerOf(model))} ${label}`}, ${effort} effort`;
38
+ }
39
+ export function parseModel(words) {
40
+ const [first = "", version, ...rest] = words.map((w) => w.toLowerCase());
41
+ const family = MODELS.find((m) => m.name === first);
42
+ if (words.length === 1 && isProvider(first))
43
+ return { model: defaultModel(first) };
44
+ if (family && version === undefined)
45
+ return { model: family.id };
46
+ if (family?.provider === "claude" && rest.length === 0 && version && /^\d+([.-]\d+)?$/.test(version)) {
47
+ return { model: `claude-${family.name}-${version.replace(".", "-")}` };
48
+ }
49
+ if (words.length === 1 && isModelId(first))
50
+ return { model: first };
51
+ return { error: `Proofed doesn't know the model \`${words.join(" ")}\`. Use ${[...new Set(MODELS.map((m) => `\`${m.name}\``))].join(", ")}, ` +
52
+ "a provider (`claude` or `codex`), a Claude version (`opus 5.5`), or a full model ID. Effort goes last and must be supported by that model." };
53
+ }
54
+ // Resolve once, before installing a CLI. A provider change picks its default model.
55
+ export function resolveFixer(choice = {}, fallback = DEFAULT_FIXER) {
56
+ const selectedProvider = choice.provider?.trim().toLowerCase() || undefined;
57
+ if (selectedProvider !== undefined && !isProvider(selectedProvider))
58
+ return { error: `The provider \`${choice.provider}\` is invalid. Use ${PROVIDERS.join(", ")}.` };
59
+ const model = choice.model || (selectedProvider && selectedProvider !== providerOf(fallback.model) ? defaultModel(selectedProvider) : fallback.model);
60
+ const provider = providerOf(model);
61
+ if (!isModelId(model) || (selectedProvider && selectedProvider !== provider))
62
+ return { error: `The model \`${model}\` doesn't belong to the selected provider.` };
63
+ const effort = choice.effort || (effortsFor(model).some((e) => e === fallback.effort) ? fallback.effort : "high");
64
+ if (!effortsFor(model).some((e) => e === effort))
65
+ return { error: `The model \`${model}\` doesn't support \`${effort}\` effort. Use ${effortsFor(model).join(", ")}.` };
66
+ return { provider, model, effort };
67
+ }
package/dist/github.js CHANGED
@@ -1,23 +1,51 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { env } from "./env.js";
2
3
  export const repoFromEnv = (token) => {
3
4
  const [owner = "", name = ""] = (process.env.GITHUB_REPOSITORY ?? "").split("/");
4
5
  return { owner, name, token };
5
6
  };
6
- async function api(repo, method, path, body) {
7
- const res = await fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}${path}`, {
7
+ export function readEvent() {
8
+ return process.env.GITHUB_EVENT_PATH ? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")) : {};
9
+ }
10
+ export const ctx = () => {
11
+ const token = process.env.GITHUB_TOKEN;
12
+ return {
13
+ repo: token && process.env.GITHUB_REPOSITORY ? repoFromEnv(token) : undefined,
14
+ runUrl: process.env.GITHUB_RUN_ID
15
+ ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
16
+ : undefined,
17
+ outDir: env("PROOFED_OUT", ".proofed-out"),
18
+ };
19
+ };
20
+ async function request(token, method, path, body) {
21
+ const send = () => fetch(`https://api.github.com${path}`, {
8
22
  method,
9
23
  headers: {
10
- authorization: `Bearer ${repo.token}`,
24
+ authorization: `Bearer ${token}`,
11
25
  accept: "application/vnd.github+json",
12
26
  "x-github-api-version": "2022-11-28",
13
27
  ...(body !== undefined && { "content-type": "application/json" }),
14
28
  },
15
29
  body: body === undefined ? undefined : JSON.stringify(body),
16
30
  });
17
- if (!res.ok)
18
- throw new GitHubError(res.status, `${method} ${path}: ${res.status} ${await res.text()}`);
19
- return (res.status === 204 ? undefined : await res.json());
31
+ // A dropped connection ("fetch failed") ended a whole run after Kane had finished. Requests that
32
+ // are safe to repeat get two more tries; a POST might already have landed, so it doesn't.
33
+ for (let attempt = 1;; attempt++) {
34
+ try {
35
+ const res = await send();
36
+ if (!res.ok)
37
+ throw new GitHubError(res.status, `${method} ${path}: ${res.status} ${await res.text()}`);
38
+ return (res.status === 204 ? undefined : await res.json());
39
+ }
40
+ catch (e) {
41
+ if (method === "POST" || attempt === 3 || !(e instanceof TypeError))
42
+ throw e;
43
+ await new Promise((r) => setTimeout(r, 2000 * attempt));
44
+ }
45
+ }
20
46
  }
47
+ const api = (repo, method, path, body) => request(repo.token, method, `/repos/${repo.owner}/${repo.name}${path}`, body);
48
+ export const getPermission = async (repo, username) => (await api(repo, "GET", `/collaborators/${encodeURIComponent(username)}/permission`)).permission;
21
49
  export const getPullRequest = (repo, number) => api(repo, "GET", `/pulls/${number}`);
22
50
  // A folder's entries at `ref`, or undefined when there is no folder there.
23
51
  export async function listFolder(repo, path, ref) {
@@ -48,20 +76,38 @@ export const MARKER = "<!-- proofed -->";
48
76
  // A report a newer one replaced carries this instead. Neither the fix trigger in the installed workflows
49
77
  // nor the dashboard's webhook matches it, so an edit of an old report is never read as the PR's report.
50
78
  export const OLD_MARKER = "<!-- proofed:old -->";
51
- // Proofed's reports on the PR, oldest first: the newest is the report. Only a bot's comment counts,
52
- // since anyone can paste the marker. `older` are reports that weren't retired, as when an edit failed.
53
- export function reportsIn(comments) {
54
- const reports = comments.filter((c) => c.user?.type === "Bot" && c.body?.includes(MARKER));
79
+ // The marker is public; report authors must be bots or the user whose token posts the report.
80
+ export function reportsIn(comments, userId) {
81
+ const reports = comments.filter((c) => c.body?.includes(MARKER) && (c.user?.type === "Bot" || (userId !== undefined && c.user?.id === userId)));
55
82
  return { current: reports.at(-1), older: reports.slice(0, -1) };
56
83
  }
84
+ const identities = new WeakMap();
85
+ function authenticatedUser(repo) {
86
+ const known = identities.get(repo);
87
+ if (known)
88
+ return known;
89
+ const identity = request(repo.token, "GET", "/user").then(({ id }) => id).catch((e) => {
90
+ // App and installation tokens have no user endpoint.
91
+ if (e instanceof GitHubError && (e.status === 401 || e.status === 403 || e.status === 404))
92
+ return undefined;
93
+ identities.delete(repo);
94
+ throw e;
95
+ });
96
+ identities.set(repo, identity);
97
+ return identity;
98
+ }
57
99
  // Every page: a report is posted afresh further down a long thread, past the first hundred comments.
58
100
  export async function listReports(repo, pr) {
59
101
  const comments = [];
60
102
  for (let page = 1;; page++) {
61
103
  const batch = await api(repo, "GET", `/issues/${pr}/comments?per_page=100&page=${page}`);
62
104
  comments.push(...batch);
63
- if (batch.length < 100)
64
- return reportsIn(comments);
105
+ if (batch.length < 100) {
106
+ const userId = comments.some((c) => c.user?.type !== "Bot" && c.user?.id !== undefined && c.body?.includes(MARKER))
107
+ ? await authenticatedUser(repo)
108
+ : undefined;
109
+ return reportsIn(comments, userId);
110
+ }
65
111
  }
66
112
  }
67
113
  export const findReport = async (repo, pr) => (await listReports(repo, pr)).current;
@@ -97,9 +143,12 @@ const CLIPS_BRANCH = "proofed-clips";
97
143
  // Clips go to an orphan branch of the same repo, so the repo needs no storage of its own.
98
144
  // Links go through github.com/…/raw/…, not raw.githubusercontent.com: for a private repo GitHub
99
145
  // redirects a signed-in viewer to a tokened raw URL, so the GIF still renders in the PR comment.
146
+ export function clipUrl(repo, path) {
147
+ return `https://github.com/${repo.owner}/${repo.name}/raw/${CLIPS_BRANCH}/${path}`;
148
+ }
100
149
  export async function publishClips(repo, files) {
101
150
  if (files.length === 0)
102
- return new Map();
151
+ return;
103
152
  for (let attempt = 0;; attempt++) {
104
153
  const parent = await api(repo, "GET", `/git/ref/heads/${CLIPS_BRANCH}`).catch((e) => {
105
154
  if (e instanceof GitHubError && e.status === 404)
@@ -139,5 +188,4 @@ export async function publishClips(repo, files) {
139
188
  throw e;
140
189
  }
141
190
  }
142
- return new Map(files.map((f) => [f.path, `https://github.com/${repo.owner}/${repo.name}/raw/${CLIPS_BRANCH}/${f.path}`]));
143
191
  }
@@ -0,0 +1,104 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { addAbortListener } from "node:events";
3
+ import { readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { ensureOut, RESULT_FILE } from "../check/check.js";
6
+ import { repoRoot } from "../changes.js";
7
+ import { quote } from "../report/result.js";
8
+ import { maskSecrets, secretValues } from "../secrets.js";
9
+ import { bounded, observations, runCli } from "./cli.js";
10
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
11
+ const MAX_BLOCKS = 3;
12
+ function rememberFailure(root, session, active, failed) {
13
+ const out = join(root, ".proofed-out");
14
+ const stateFile = join(out, `claude-stop-${hash(session)}.json`);
15
+ let reported = [];
16
+ try {
17
+ reported = JSON.parse(readFileSync(stateFile, "utf8"));
18
+ }
19
+ catch (error) {
20
+ if (error.code !== "ENOENT")
21
+ throw error;
22
+ }
23
+ if (reported.length >= MAX_BLOCKS)
24
+ return "This session reached the three-block limit.";
25
+ // By scenario, not outcome: Kane can call the same broken scenario failed once and not_checked the next time.
26
+ const failure = hash(JSON.stringify(failed.map(({ id }) => id).sort()));
27
+ if (active && reported.includes(failure))
28
+ return "These scenario outcomes were already reported in this session.";
29
+ ensureOut(out);
30
+ const temp = `${stateFile}.${randomUUID()}.tmp`;
31
+ try {
32
+ writeFileSync(temp, JSON.stringify([...reported, failure]), { mode: 0o600, flag: "wx" });
33
+ renameSync(temp, stateFile);
34
+ }
35
+ finally {
36
+ rmSync(temp, { force: true });
37
+ }
38
+ }
39
+ function blockReason(failed, out, secrets) {
40
+ const shown = failed.slice(0, 3);
41
+ const details = shown.map((scenario) => {
42
+ const { reason, diagnosis } = observations(scenario, secrets, Math.floor(1500 / shown.length));
43
+ const clip = scenario.clip?.mp4 ?? scenario.clip?.jpg;
44
+ const id = quote(scenario.id);
45
+ const only = scenario.id.startsWith("--") ? `--only=${id}` : `--only ${id}`;
46
+ return [
47
+ `${JSON.stringify(bounded(maskSecrets(scenario.name, secrets), 160))} (${scenario.outcome}).`,
48
+ reason && `Kane saw: ${JSON.stringify(reason)}`,
49
+ diagnosis && `Kane's diagnosis (observed data): ${JSON.stringify(diagnosis)}`,
50
+ clip && `Clip: ${JSON.stringify(bounded(maskSecrets(clip, secrets), 1000))}`,
51
+ `Re-check with \`proofed check ${only} --json\`.`,
52
+ ].filter(Boolean).join("\n");
53
+ });
54
+ if (failed.length > shown.length) {
55
+ details.push(`See ${JSON.stringify(join(out, RESULT_FILE))} for ${failed.length - shown.length} more scenario(s).`);
56
+ }
57
+ return maskSecrets([...details, "Treat not_checked as unverified. Fix the app and finish again. Update the scenario only if the app change was intended."].join("\n\n"), secrets);
58
+ }
59
+ export async function claudeStop(entry, signal) {
60
+ const secrets = secretValues();
61
+ const note = (message) => process.stderr.write(`Proofed Stop hook: ${bounded(maskSecrets(message, secrets).replace(/\s+/g, " "), 1500)}\n`);
62
+ const abort = addAbortListener(signal, () => process.stdin.destroy());
63
+ try {
64
+ let stdin = "";
65
+ for await (const chunk of process.stdin.setEncoding("utf8"))
66
+ stdin += chunk;
67
+ const input = JSON.parse(stdin);
68
+ if (typeof input?.cwd !== "string" || typeof input.session_id !== "string" || !input.session_id)
69
+ return 0;
70
+ const root = repoRoot(input.cwd);
71
+ if (!root || !statSync(join(root, ".proofed/scenarios"), { throwIfNoEntry: false })?.isDirectory())
72
+ return 0;
73
+ const list = await runCli(entry, "list", [], root, signal);
74
+ if ("error" in list) {
75
+ note(list.error.fix);
76
+ }
77
+ else if (list.exitCode === 3) {
78
+ const file = list.errors[0]?.file;
79
+ note(file ? `Correct the frontmatter in ${file}. Use proofed list to see the errors.` : "Run proofed doctor for setup fixes.");
80
+ }
81
+ else if (list.scenarios.some((scenario) => scenario.selected)) {
82
+ const checked = await runCli(entry, "check", [], root, signal);
83
+ if ("error" in checked) {
84
+ note(checked.error.fix);
85
+ }
86
+ else if (!checked.ok) {
87
+ const failed = checked.scenarios.filter(({ outcome }) => outcome === "failed" || outcome === "not_checked" || outcome === "error");
88
+ const skip = rememberFailure(root, input.session_id, input.stop_hook_active === true, failed);
89
+ if (skip)
90
+ note(skip);
91
+ else
92
+ process.stdout.write(`${JSON.stringify({ decision: "block", reason: blockReason(failed, checked.out, secrets) })}\n`);
93
+ }
94
+ }
95
+ }
96
+ catch (error) {
97
+ if (!signal.aborted)
98
+ note(`${error instanceof Error ? error.message : String(error)} Run proofed doctor for setup fixes.`);
99
+ }
100
+ finally {
101
+ abort[Symbol.dispose]();
102
+ }
103
+ return 0;
104
+ }
@@ -0,0 +1,63 @@
1
+ import { spawn } from "node:child_process";
2
+ import { addAbortListener } from "node:events";
3
+ import { adopt } from "../children.js";
4
+ import { killTree } from "../process.js";
5
+ import { maskSecrets } from "../secrets.js";
6
+ export async function runCli(entry, command, args, cwd, signal) {
7
+ signal.throwIfAborted();
8
+ // The check handles SIGTERM and cleans up the process groups it owns (Kane, Chrome and the app).
9
+ const child = spawn(process.execPath, [entry, command, "--json", ...args], {
10
+ cwd, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "ignore"],
11
+ });
12
+ let stdout = "";
13
+ let startError;
14
+ child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; });
15
+ child.once("error", (error) => { startError = error; });
16
+ const exited = new Promise((resolve) => child.once("close", resolve));
17
+ let escalation;
18
+ const terminate = () => {
19
+ if (escalation)
20
+ return;
21
+ killTree(child.pid);
22
+ escalation = setTimeout(() => killTree(child.pid, "SIGKILL"), 5000);
23
+ };
24
+ const release = adopt({ exited, kill: (signal) => signal === "SIGTERM" ? terminate() : killTree(child.pid, signal) });
25
+ const abort = addAbortListener(signal, terminate);
26
+ try {
27
+ const code = await exited;
28
+ signal.throwIfAborted();
29
+ if (startError)
30
+ throw startError;
31
+ if (code !== 0 && code !== 1 && code !== 2 && code !== 3 && code !== 130) {
32
+ throw new Error(`proofed ${command} exited unexpectedly (${code ?? "signal"}).`);
33
+ }
34
+ let doc;
35
+ try {
36
+ doc = JSON.parse(stdout);
37
+ }
38
+ catch {
39
+ throw new Error(`proofed ${command} returned invalid JSON.`);
40
+ }
41
+ if (doc?.exitCode !== code)
42
+ throw new Error(`proofed ${command} returned an invalid result.`);
43
+ return doc;
44
+ }
45
+ finally {
46
+ abort[Symbol.dispose]();
47
+ if (escalation) {
48
+ clearTimeout(escalation);
49
+ killTree(child.pid, "SIGKILL");
50
+ }
51
+ release();
52
+ }
53
+ }
54
+ export function bounded(text, limit) {
55
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
56
+ }
57
+ export function observations({ reason, diagnosis }, secrets, limit = 1500) {
58
+ const fieldLimit = reason && diagnosis ? Math.floor(limit / 2) : limit;
59
+ return {
60
+ ...(reason && { reason: bounded(maskSecrets(reason, secrets), fieldLimit) }),
61
+ ...(diagnosis && { diagnosis: bounded(maskSecrets(diagnosis, secrets), fieldLimit) }),
62
+ };
63
+ }
@@ -0,0 +1,130 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ import { maskSecrets, secretValues } from "../secrets.js";
6
+ import { bounded, observations, runCli } from "./cli.js";
7
+ const nonblank = z.string().trim().min(1);
8
+ const selection = {
9
+ base: nonblank.optional().describe("Git ref to compare against."),
10
+ all: z.boolean().optional().describe("Select every scenario."),
11
+ };
12
+ function flags(values) {
13
+ return Object.entries(values).flatMap(([name, value]) => typeof value === "string" ? [`--${name}=${value}`] : value ? [`--${name}`] : []);
14
+ }
15
+ function result(text, isError = false) {
16
+ return { content: [{ type: "text", text }], ...(isError && { isError: true }) };
17
+ }
18
+ function json(doc, secrets, indent) {
19
+ return JSON.stringify(doc, (_key, value) => typeof value === "string" ? maskSecrets(value, secrets) : value, indent);
20
+ }
21
+ function scenarioDetails(scenarios, secrets) {
22
+ return scenarios.map((scenario) => {
23
+ const { id, name, outcome, cached, notChecked, rerun, clip, credits, estimatedCredits } = scenario;
24
+ return {
25
+ id, name, outcome, cached, notChecked,
26
+ ...((scenario.reason || scenario.diagnosis) && { "Kane saw": observations(scenario, secrets) }),
27
+ rerun, clip, credits, estimatedCredits,
28
+ };
29
+ });
30
+ }
31
+ function checkText({ summary, scenarios, next: _next, ...doc }, secrets) {
32
+ return `${bounded(maskSecrets(summary, secrets).replace(/\s+/g, " "), 500)}\n${json({ ...doc, scenarios: scenarioDetails(scenarios, secrets) }, secrets, 2)}`;
33
+ }
34
+ export async function mcp(entry, version, signal) {
35
+ const server = new McpServer({ name: "proofed", version });
36
+ const cwd = process.cwd();
37
+ const active = new Set();
38
+ // Checks share the project's cache, recordings and result.json.
39
+ let checks = Promise.resolve();
40
+ function call(command, args, extra) {
41
+ const { progressToken } = extra._meta ?? {};
42
+ let timer;
43
+ if (progressToken !== undefined) {
44
+ let progress = 0;
45
+ const notify = () => {
46
+ void extra.sendNotification({
47
+ method: "notifications/progress",
48
+ params: { progressToken, progress: progress++, message: `Proofed ${command} in progress` },
49
+ }).catch(() => { });
50
+ };
51
+ notify();
52
+ timer = setInterval(notify, 15_000);
53
+ timer.unref();
54
+ }
55
+ const invoke = () => runCli(entry, command, args, cwd, extra.signal);
56
+ const pending = command === "check" ? checks.then(invoke) : invoke();
57
+ if (command === "check")
58
+ checks = pending.then(() => { }, () => { });
59
+ const response = pending.then((doc) => {
60
+ const secrets = secretValues();
61
+ if ("summary" in doc)
62
+ return result(checkText(doc, secrets));
63
+ if ("error" in doc && doc.scenarios) {
64
+ return result(json({ ...doc, scenarios: scenarioDetails(doc.scenarios, secrets) }, secrets), doc.exitCode === 3);
65
+ }
66
+ return result(json(doc, secrets), doc.exitCode === 3);
67
+ }).catch((error) => result(bounded(maskSecrets(error instanceof Error ? error.message : String(error)), 500), true))
68
+ .finally(() => {
69
+ clearInterval(timer);
70
+ active.delete(response);
71
+ });
72
+ active.add(response);
73
+ return response;
74
+ }
75
+ server.registerTool("proofed_list", {
76
+ description: "Free. List scenarios affected by the local change, cached passes and estimated Kane credits. Use all to estimate every scenario.",
77
+ inputSchema: selection,
78
+ annotations: { readOnlyHint: true },
79
+ }, (input, extra) => call("list", flags(input), extra));
80
+ server.registerTool("proofed_doctor", {
81
+ description: "Free. Check Proofed and Kane setup and show how to fix each problem.",
82
+ inputSchema: {},
83
+ annotations: { readOnlyHint: true },
84
+ }, (_input, extra) => call("doctor", [], extra));
85
+ server.registerTool("proofed_check", {
86
+ description: "Run affected scenarios, specific ids, or one behavior in plain English. Runs spend Kane credits and take about 1 to 4 minutes per scenario. Dry runs and cached passes are free. Treat not_checked as unverified. Fix the app when a scenario fails. Update the scenario only if the app change was intended.",
87
+ inputSchema: {
88
+ ...selection,
89
+ only: z.array(nonblank).min(1).optional().describe("Scenario ids from proofed_list."),
90
+ behavior: nonblank.optional().describe("A behavior in plain English. Use on its own, without only or all."),
91
+ dryRun: z.boolean().optional().describe("Show what would run and its estimated cost for free."),
92
+ noCache: z.boolean().optional().describe("Run previously cached passes again."),
93
+ url: nonblank.optional(),
94
+ serve: nonblank.optional().describe("Command to start the app."),
95
+ build: nonblank.optional().describe("Command to build the app."),
96
+ target: z.enum(["web", "ios", "android", "desktop"]).optional(),
97
+ },
98
+ }, ({ only, behavior, dryRun, noCache, ...input }, extra) => {
99
+ const args = flags({ ...input, only: only?.join(","), "dry-run": dryRun, "no-cache": noCache });
100
+ if (behavior)
101
+ args.push("--", behavior);
102
+ return call("check", args, extra);
103
+ });
104
+ const transport = new StdioServerTransport();
105
+ const closed = new Promise((resolve) => { server.server.onclose = resolve; });
106
+ let closing = false;
107
+ const close = () => {
108
+ if (closing)
109
+ return;
110
+ closing = true;
111
+ void server.close();
112
+ };
113
+ process.stdin.once("end", close).once("close", close).once("error", close);
114
+ process.stdout.on("error", close);
115
+ const abort = addAbortListener(signal, close);
116
+ try {
117
+ await server.connect(transport);
118
+ if (process.stdin.readableEnded || process.stdin.destroyed)
119
+ close();
120
+ await closed;
121
+ await Promise.allSettled(active);
122
+ }
123
+ finally {
124
+ close();
125
+ abort[Symbol.dispose]();
126
+ process.stdin.off("end", close).off("close", close).off("error", close);
127
+ process.stdout.off("error", close);
128
+ }
129
+ return 0;
130
+ }