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,104 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { kaneLogin } from "./kaneauth.js";
6
+ const uid = process.getuid?.();
7
+ // The Windows profile has per-user ACLs; POSIX uses a uid-scoped private temp directory.
8
+ export const creditLockPath = (dir = uid === undefined ? homedir() : tmpdir()) => join(dir, uid === undefined ? ".proofed-kane-meter.lock" : `proofed-kane-${uid}.lock`);
9
+ const registration = /^(\d+)-[\da-f-]{36}(\.done)?$/;
10
+ const alive = (pid) => {
11
+ if (!Number.isSafeInteger(pid) || pid <= 0)
12
+ return false;
13
+ try {
14
+ process.kill(pid, 0);
15
+ return true;
16
+ }
17
+ catch (e) {
18
+ return e.code === "EPERM";
19
+ }
20
+ };
21
+ const privateDirectory = (dir) => {
22
+ const stat = lstatSync(dir);
23
+ return stat.isDirectory() && (uid === undefined || (stat.uid === uid && (stat.mode & 0o077) === 0));
24
+ };
25
+ export async function creditMeter(env, lock = creditLockPath()) {
26
+ const id = `${process.pid}-${randomUUID()}`;
27
+ const active = join(lock, id);
28
+ const warning = join(active, "contended");
29
+ let registered = false;
30
+ let contended = false;
31
+ try {
32
+ try {
33
+ mkdirSync(lock, { mode: 0o700 });
34
+ }
35
+ catch (e) {
36
+ if (e.code !== "EEXIST")
37
+ throw e;
38
+ }
39
+ if (privateDirectory(lock)) {
40
+ mkdirSync(active, { mode: 0o700 });
41
+ registered = true;
42
+ // A run registers before looking for overlap and stays registered until it finishes.
43
+ // Each peer keeps its own warning, even after the run that set it has finished.
44
+ for (const name of readdirSync(lock)) {
45
+ if (name === id)
46
+ continue;
47
+ const peer = registration.exec(name);
48
+ if (!peer)
49
+ continue;
50
+ if (peer[2] || !alive(Number(peer[1]))) {
51
+ rmSync(join(lock, name), { recursive: true, force: true });
52
+ continue;
53
+ }
54
+ contended = true;
55
+ try {
56
+ writeFileSync(join(lock, name, "contended"), "", { flag: "wx" });
57
+ }
58
+ catch (e) {
59
+ const code = e.code;
60
+ if (code !== "ENOENT" && code !== "EEXIST")
61
+ throw e;
62
+ }
63
+ }
64
+ }
65
+ }
66
+ catch {
67
+ contended = true;
68
+ }
69
+ const balance = async () => {
70
+ const login = await kaneLogin(env.KANE_CLI ?? "kane-cli", env);
71
+ const value = /^Available credits:\s*(\d+(?:\.\d+)?)\s*$/im.exec(login.balance ?? "")?.[1];
72
+ return value === undefined ? undefined : Number(value);
73
+ };
74
+ // The CLI has no transaction ledger. A balance delta can include remote account
75
+ // activity, which no local process scan or filesystem lock can rule out.
76
+ const attributable = () => {
77
+ try {
78
+ return privateDirectory(lock) && privateDirectory(active) && !existsSync(warning);
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ };
84
+ const before = registered && !contended ? await balance() : undefined;
85
+ return async (measure = true) => {
86
+ try {
87
+ const after = !measure || before === undefined || !attributable() ? undefined : await balance();
88
+ return before !== undefined && after !== undefined && after <= before && attributable()
89
+ ? { before, after, debit: Math.round((before - after) * 10_000) / 10_000 }
90
+ : undefined;
91
+ }
92
+ finally {
93
+ try {
94
+ if (registered && privateDirectory(lock)) {
95
+ // Retire the registration before cleanup, so a peer cannot add a marker mid-removal.
96
+ const done = `${active}.done`;
97
+ renameSync(active, done);
98
+ rmSync(done, { recursive: true, force: true });
99
+ }
100
+ }
101
+ catch { }
102
+ }
103
+ };
104
+ }
@@ -0,0 +1,131 @@
1
+ import { executableCommand, killTree } from "../process.js";
2
+ import { appendFileSync } from "node:fs";
3
+ import { spawn } from "node:child_process";
4
+ import { createInterface } from "node:readline";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { creditMeter } from "./creditmeter.js";
7
+ import { kaneSecretValues } from "./kaneauth.js";
8
+ import { adopt } from "../children.js";
9
+ import { maskSecrets } from "../secrets.js";
10
+ const isStep = (e) => "step" in e && "status" in e;
11
+ const isRunEnd = (e) => "type" in e && e.type === "run_end";
12
+ const cancelled = () => ({ steps: [], end: undefined, exitCode: null, stderr: "Kane run cancelled", timedOut: false });
13
+ function diagnostic(file) {
14
+ return (line) => {
15
+ if (!file)
16
+ return;
17
+ try {
18
+ appendFileSync(file, line);
19
+ }
20
+ catch {
21
+ file = undefined;
22
+ } // Keep reading Kane's verdict if its diagnostic file becomes unwritable.
23
+ };
24
+ }
25
+ export async function runKane(o) {
26
+ if (o.signal?.aborted)
27
+ return cancelled();
28
+ const env = { ...process.env, ...(o.username && o.accessKey && { LT_USERNAME: o.username, LT_ACCESS_KEY: o.accessKey }) };
29
+ const finish = await creditMeter(env);
30
+ if (o.signal?.aborted) {
31
+ await finish(false);
32
+ return cancelled();
33
+ }
34
+ try {
35
+ const result = await runUnmetered(o, kaneSecretValues(env));
36
+ return { ...result, accountBalance: await finish() };
37
+ }
38
+ catch (e) {
39
+ await finish();
40
+ throw e;
41
+ }
42
+ }
43
+ function runUnmetered(o, secrets) {
44
+ const args = [
45
+ "run",
46
+ o.objective,
47
+ "--agent",
48
+ ...(o.kaneArgs ?? ["--target", "desktop", "--url", o.url, "--cdp-endpoint", o.cdpEndpoint]),
49
+ "--timeout",
50
+ String(o.timeoutSeconds ?? 300),
51
+ ...(o.username && o.accessKey ? ["--username", o.username, "--access-key", o.accessKey] : []),
52
+ ];
53
+ // Own process group: Kane spawns runner and Playwright children that outlive a plain kill.
54
+ const command = executableCommand(process.env.KANE_CLI ?? "kane-cli", args);
55
+ const proc = spawn(command.file, command.args, { stdio: ["ignore", "pipe", "pipe"], detached: true, windowsHide: true });
56
+ const killGroup = (signal) => killTree(proc.pid, signal);
57
+ const release = adopt({ kill: killGroup, exited: new Promise((r) => proc.once("exit", r)) });
58
+ const steps = [];
59
+ let end;
60
+ let stderr = "";
61
+ // Read complete lines so a credential split between process chunks is still masked.
62
+ const errors = createInterface({ input: proc.stderr });
63
+ const lines = createInterface({ input: proc.stdout });
64
+ const drained = Promise.all([lines, errors].map((stream) => new Promise((r) => stream.once("close", r))));
65
+ const writeStderr = diagnostic(o.rawFile && `${o.rawFile}.stderr`);
66
+ const writeStdout = diagnostic(o.rawFile);
67
+ errors.on("line", (line) => {
68
+ const safe = maskSecrets(line, secrets) + "\n";
69
+ stderr += safe;
70
+ writeStderr(safe);
71
+ });
72
+ lines.on("line", (raw) => {
73
+ const line = maskSecrets(raw, secrets);
74
+ writeStdout(line + "\n");
75
+ let event;
76
+ try {
77
+ event = JSON.parse(line);
78
+ }
79
+ catch {
80
+ return; // Kane occasionally prints a non-JSON notice; it carries nothing we use.
81
+ }
82
+ if (typeof event !== "object" || event === null)
83
+ return;
84
+ if (isStep(event)) {
85
+ steps.push(event);
86
+ o.onStep?.(event);
87
+ }
88
+ else if (isRunEnd(event)) {
89
+ end = event;
90
+ o.onEnd?.(event);
91
+ }
92
+ });
93
+ // Kane's own --timeout counts only active time; when its backend stalls a run can hang for
94
+ // a quarter of an hour, so we also enforce a wall-clock limit.
95
+ let timedOut = false;
96
+ let hardKill;
97
+ const terminate = () => {
98
+ if (hardKill)
99
+ return;
100
+ killGroup("SIGTERM");
101
+ hardKill = setTimeout(() => killGroup("SIGKILL"), 5000);
102
+ };
103
+ const watchdog = setTimeout(() => {
104
+ timedOut = true;
105
+ terminate();
106
+ }, (o.wallTimeoutSeconds ?? 360) * 1000);
107
+ const abort = () => {
108
+ clearTimeout(watchdog);
109
+ terminate();
110
+ };
111
+ o.signal?.addEventListener("abort", abort, { once: true });
112
+ if (o.signal?.aborted)
113
+ abort();
114
+ const clearTimers = () => {
115
+ o.signal?.removeEventListener("abort", abort);
116
+ clearTimeout(watchdog);
117
+ clearTimeout(hardKill);
118
+ };
119
+ // "exit", not "close": an orphaned grandchild can hold stdout open long after Kane is gone.
120
+ return new Promise((resolve) => {
121
+ proc.once("error", (error) => { clearTimers(); release(); resolve({ steps, end, exitCode: null, stderr: maskSecrets(String(error), secrets), timedOut }); });
122
+ proc.on("exit", async (exitCode) => {
123
+ clearTimers();
124
+ // Let the last lines (run_end) through, but don't wait on a stream an orphan keeps open.
125
+ await Promise.race([drained, delay(2000, undefined, { ref: false })]);
126
+ killGroup("SIGKILL");
127
+ release();
128
+ resolve({ steps, end, exitCode, stderr, timedOut });
129
+ });
130
+ });
131
+ }
@@ -0,0 +1,84 @@
1
+ import { executableCommand } from "../process.js";
2
+ import { maskSecrets, secretValues } from "../secrets.js";
3
+ // Whether Kane can start a run: signed in with `kane-cli login`, or given LT_USERNAME and
4
+ // LT_ACCESS_KEY, which Proofed passes to every run. `proofed check` asks before it builds anything:
5
+ // without a working login every run ends at once, and a retry ends the same way.
6
+ import { execFile } from "node:child_process";
7
+ export const LOGIN_FIX = "kane-cli login (or export LT_USERNAME and LT_ACCESS_KEY from TestMu: Settings → Keys)";
8
+ export const KEYS_FIX = "LT_USERNAME and LT_ACCESS_KEY: copy both again from TestMu (Settings → Keys), in the GitHub repository secrets too, or unset them to use kane-cli login";
9
+ // What `kane-cli run` prints on stderr when it can't start for want of a login (kane-cli 0.10):
10
+ // "Not authenticated. Run: kane-cli login --oauth, or kane-cli login --username <user> --access-key <key>"
11
+ // and `kane-cli balance`: 'Not authenticated [prod]. Run "kane-cli login" first.'
12
+ export const NOT_SIGNED_IN = /\bnot authenticated\b|\bnot (?:logged|signed) in\b|\btoken (?:missing|expired|invalid)\b/i;
13
+ // What TestMu answers a login or keys it doesn't accept, through `kane-cli balance` (kane-cli 0.10):
14
+ // 'Error: Credit balance request failed: 401 {"error":"authentication failed"}'
15
+ const REJECTED = /\b40[13]\b|\bauthentication failed\b|\bcredentials not valid\b|\bunauthori[sz]ed\b/i;
16
+ export const kaneCredentials = (env) => env.LT_USERNAME?.trim() && env.LT_ACCESS_KEY?.trim() ? ["--username", env.LT_USERNAME.trim(), "--access-key", env.LT_ACCESS_KEY.trim()] : [];
17
+ export function kaneSecretValues(env) {
18
+ const secrets = secretValues(env);
19
+ const key = env.LT_ACCESS_KEY?.trim();
20
+ if (!key || key === env.LT_ACCESS_KEY)
21
+ return secrets;
22
+ // Kane can echo the trimmed key passed on its command line.
23
+ return [...new Set([...secrets, ...secretValues({ LT_ACCESS_KEY: key })])].sort((a, b) => b.length - a.length);
24
+ }
25
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
26
+ const NOTICE = /^(?:update available|skill update available)\b/i;
27
+ // The line Kane gives its reason in, without the update notices it prints around it.
28
+ const reasonIn = (output) => output
29
+ .replace(ANSI, "")
30
+ .split("\n")
31
+ .map((l) => l.trim().replace(/^error:\s*/i, ""))
32
+ .filter((l) => l && !NOTICE.test(l))
33
+ .at(-1) ?? "";
34
+ // `kane-cli balance` is free and asks TestMu with the login or the keys a run would use, so a
35
+ // missing, expired or wrong one shows here and not after the build. `whoami` only reads the local
36
+ // login: it can't tell a wrong key from a good one. A balance that can't be started, doesn't answer
37
+ // or fails for another reason (no network) says nothing either way, and the check goes on.
38
+ export function kaneLogin(bin, env, timeout = 20_000) {
39
+ const creds = kaneCredentials(env);
40
+ const secrets = kaneSecretValues(env);
41
+ const timedOut = { state: "unknown", detail: `kane-cli balance didn't answer within ${timeout / 1000} s` };
42
+ return new Promise((resolve) => {
43
+ try {
44
+ const cmd = executableCommand(bin, ["balance", ...creds], env);
45
+ let deadline;
46
+ const child = execFile(cmd.file, cmd.args, { env, timeout, windowsHide: true }, (error, stdout, stderr) => {
47
+ clearTimeout(deadline);
48
+ const output = `${stdout}\n${stderr}`.replace(ANSI, "");
49
+ if (!error) {
50
+ return resolve(creds.length ? { state: "keys", detail: "LT_USERNAME and LT_ACCESS_KEY work; Kane uses them", balance: output } : { state: "signed_in", detail: "signed in", balance: output });
51
+ }
52
+ const e = error;
53
+ if (e.killed)
54
+ return resolve(timedOut);
55
+ if (typeof e.code !== "number")
56
+ return resolve({ state: "unknown", detail: `kane-cli balance didn't answer: ${maskSecrets(e.message, secrets)}` });
57
+ const said = maskSecrets(reasonIn(output), secrets);
58
+ if (REJECTED.test(output) || NOT_SIGNED_IN.test(output)) {
59
+ return resolve(creds.length
60
+ ? { state: "keys_rejected", detail: `Kane rejected LT_USERNAME and LT_ACCESS_KEY${said ? ` (${said})` : ""}` }
61
+ : { state: "not_signed_in", detail: REJECTED.test(output) ? `the login was rejected${said ? ` (${said})` : ""}` : "not signed in" });
62
+ }
63
+ resolve({ state: "unknown", detail: `kane-cli balance failed${said ? `: ${said}` : ` with exit ${e.code}`}` });
64
+ });
65
+ if (timeout > 0)
66
+ deadline = setTimeout(() => {
67
+ // execFile gives Kane a SIGTERM first. Settle even if the process or its pipes stay open.
68
+ resolve(timedOut);
69
+ try {
70
+ child.kill("SIGKILL");
71
+ }
72
+ catch { /* Best-effort cleanup. */ }
73
+ child.stdin?.destroy();
74
+ child.stdout?.destroy();
75
+ child.stderr?.destroy();
76
+ child.unref();
77
+ }, timeout + 1000);
78
+ }
79
+ catch (e) {
80
+ const message = e instanceof Error ? e.message : String(e);
81
+ resolve({ state: "unknown", detail: `kane-cli balance didn't answer: ${maskSecrets(message, secrets)}` });
82
+ }
83
+ });
84
+ }
@@ -0,0 +1,13 @@
1
+ import { executableCommand } from "../process.js";
2
+ import { execFileSync } from "node:child_process";
3
+ export function readKaneVersion(bin, env = process.env) {
4
+ try {
5
+ const cmd = executableCommand(bin, ["--version"], env);
6
+ const stdout = execFileSync(cmd.file, cmd.args, { env, windowsHide: true, encoding: "utf8", timeout: 20_000, stdio: ["ignore", "pipe", "pipe"] });
7
+ // Match a version line, so runtime warnings cannot become part of the cache identity.
8
+ return /^\s*v?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)\s*$/m.exec(stdout)?.[1] ?? "unknown";
9
+ }
10
+ catch {
11
+ return "unknown";
12
+ }
13
+ }
package/dist/paths.js ADDED
@@ -0,0 +1,32 @@
1
+ import { posix } from "node:path";
2
+ // git and scenario globs use '/', even when the working tree uses Windows paths.
3
+ export const gitPath = (file) => process.platform === "win32" ? file.replaceAll("\\", "/") : file;
4
+ export function matchesPath(file, glob) {
5
+ const path = gitPath(file);
6
+ const pattern = gitPath(glob);
7
+ if (posix.matchesGlob(path, pattern))
8
+ return true;
9
+ if (!/(?:^|\/)\.(?!\.?(?:\/|$))/.test(path))
10
+ return false;
11
+ // Node excludes leading dots from wildcards. Prefix both sides with a literal
12
+ // that cannot appear in a git path, leaving globstars and navigation segments alone.
13
+ const prefix = (value, isPattern) => value.replace(/[^/]+/g, (part) => part === "." || part === ".." || (isPattern && part === "**") ? part : `\0${part}`);
14
+ const prefixed = prefix(path, false);
15
+ const matches = (pattern) => posix.matchesGlob(prefixed, prefix(pattern, true));
16
+ if (matches(pattern))
17
+ return true;
18
+ // A brace alternative can expose a whole globstar segment, so expand those alternatives first.
19
+ if (!/(?:[{,]\*\*(?=[/,}])|\/\*\*(?=[,}]))/.test(pattern))
20
+ return false;
21
+ let remaining = 1_000;
22
+ const matchAlternative = (pattern) => {
23
+ if (--remaining < 0)
24
+ return false;
25
+ const group = /(?<!\$)\{([^{}]*,[^{}]*)\}/.exec(pattern);
26
+ if (!group)
27
+ return matches(pattern);
28
+ const end = group.index + group[0].length;
29
+ return group[1].split(",").some((part) => matchAlternative(pattern.slice(0, group.index) + part + pattern.slice(end)));
30
+ };
31
+ return matchAlternative(pattern);
32
+ }
@@ -0,0 +1,65 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { openSync, readSync, closeSync, existsSync, readFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { findOnPath } from "./which.js";
5
+ export function treeKillCommand(pid, platform = process.platform) {
6
+ if (!Number.isSafeInteger(pid) || pid <= 0)
7
+ throw new Error("Invalid child pid");
8
+ return platform === "win32" ? { file: "taskkill", args: ["/PID", String(pid), "/T", "/F"] } : undefined;
9
+ }
10
+ // POSIX children own a process group. Windows needs taskkill to include descendants;
11
+ // a negative PID is invalid there. Keep this synchronous for exit-time cleanup too.
12
+ export function killTree(pid, signal = "SIGTERM", platform = process.platform) {
13
+ if (!pid)
14
+ return;
15
+ try {
16
+ const command = treeKillCommand(pid, platform);
17
+ if (command)
18
+ execFileSync(command.file, command.args, { stdio: "ignore", windowsHide: true, timeout: 10_000 });
19
+ else
20
+ process.kill(-pid, signal);
21
+ }
22
+ catch { /* Already gone. */ }
23
+ }
24
+ function nodeScript(file) {
25
+ if (/\.(?:[cm]?js|ts)$/i.test(file))
26
+ return true;
27
+ try {
28
+ const fd = openSync(file, "r");
29
+ try {
30
+ const head = Buffer.alloc(150);
31
+ const size = readSync(fd, head, 0, head.length, 0);
32
+ return /^#![^\r\n]*\bnode(?:\.exe)?(?:\s|$)/.test(head.toString("utf8", 0, size));
33
+ }
34
+ finally {
35
+ closeSync(fd);
36
+ }
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ // Never pass CLI arguments through cmd.exe: objectives/prompts may contain quotes,
43
+ // %, &, or newlines. npm's Windows shims name the actual Node entry beside the shim.
44
+ export function executableCommand(bin, args, env = process.env, platform = process.platform) {
45
+ let file = findOnPath(bin, env, platform) ?? bin;
46
+ if (platform === "win32" && /\.(?:cmd|bat)$/i.test(file)) {
47
+ const shim = readFileSync(file, "utf8");
48
+ const entry = /"%dp0%[\\/]([^"\r\n]+\.(?:[cm]?js|ts))"\s+%\*/i.exec(shim)?.[1];
49
+ const script = entry && resolve(dirname(file), entry.replaceAll("\\", "/"));
50
+ if (!script || !existsSync(script))
51
+ throw new Error(`Cannot resolve Node entry for ${file}; point KANE_CLI at its JavaScript launcher or an .exe`);
52
+ file = script;
53
+ }
54
+ return nodeScript(file) ? { file: process.execPath, args: [file, ...args] } : { file, args };
55
+ }
56
+ // Prefer Git Bash over the optional WSL bash.exe in System32 on Windows runners.
57
+ export function findGitBash(env = process.env, platform = process.platform) {
58
+ if (platform !== "win32")
59
+ return "bash";
60
+ const git = findOnPath("git", env, platform);
61
+ const roots = [env.ProgramFiles && resolve(env.ProgramFiles, "Git"), git && resolve(dirname(git), "..")];
62
+ return roots.filter((root) => !!root)
63
+ .flatMap((root) => [resolve(root, "bin/bash.exe"), resolve(root, "usr/bin/bash.exe")])
64
+ .find((file) => existsSync(file)) ?? "bash";
65
+ }
package/dist/proofed.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- // `proofed` in a terminal: the PR check (src/cli.ts) for the change on this machine, for a person
2
+ // `proofed` in a terminal: the PR check (src/action/cli.ts) for the change on this machine, for a person
3
3
  // or a coding agent that wants to see a UI change work before calling it done.
4
4
  import { readFileSync } from "node:fs";
5
- import { parse, UsageError } from "./args.js";
6
- import { check } from "./check.js";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parse, UsageError } from "./check/args.js";
7
7
  import { killChildren, stopChildren } from "./children.js";
8
- import { doctor } from "./doctor.js";
9
- import { helpText } from "./help.js";
10
- import { list } from "./list.js";
8
+ import { helpText } from "./check/help.js";
9
+ import { maskSecrets } from "./secrets.js";
11
10
  const argv = process.argv.slice(2);
12
11
  const io = { stdout: process.stdout, stderr: process.stderr, env: process.env, cwd: process.cwd() };
12
+ const version = () => JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
13
  // Whatever ends the process, nothing it started keeps running, and the cursor comes back.
14
14
  process.on("exit", () => {
15
15
  killChildren();
16
- if (process.stdout.isTTY)
16
+ if (process.stdout.isTTY && argv[0] !== "mcp" && argv[0] !== "hook")
17
17
  process.stdout.write("\x1b[?25h");
18
18
  });
19
19
  async function main() {
@@ -25,7 +25,7 @@ async function main() {
25
25
  if (!(e instanceof UsageError))
26
26
  throw e;
27
27
  if (argv.includes("--json")) {
28
- io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "usage", message: e.message, fix: "See proofed --help." } }, null, 2)}\n`);
28
+ io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "usage", message: e.message, fix: "See proofed --help." } })}\n`);
29
29
  }
30
30
  else {
31
31
  io.stderr.write(`proofed: ${e.message}\n`);
@@ -33,8 +33,7 @@ async function main() {
33
33
  return 3;
34
34
  }
35
35
  if (parsed.kind === "version") {
36
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
37
- io.stdout.write(`${pkg.version}\n`);
36
+ io.stdout.write(`${version()}\n`);
38
37
  return 0;
39
38
  }
40
39
  if (parsed.kind === "help") {
@@ -47,17 +46,33 @@ async function main() {
47
46
  return 0;
48
47
  }
49
48
  if (command === "check")
50
- return check(flags, text, io);
49
+ return (await import("./check/check.js")).check(flags, text, io);
51
50
  if (command === "list")
52
- return list(flags, io);
53
- return doctor(flags, io);
51
+ return (await import("./check/list.js")).list(flags, io);
52
+ if (command === "doctor")
53
+ return (await import("./check/doctor.js")).doctor(flags, io);
54
+ const entry = fileURLToPath(import.meta.url);
55
+ const controller = new AbortController();
56
+ const abort = () => controller.abort();
57
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
58
+ for (const signal of signals)
59
+ process.on(signal, abort);
60
+ try {
61
+ return command === "mcp"
62
+ ? await (await import("./integrations/mcp.js")).mcp(entry, version(), controller.signal)
63
+ : await (await import("./integrations/claude-stop.js")).claudeStop(entry, controller.signal);
64
+ }
65
+ finally {
66
+ for (const signal of signals)
67
+ process.off(signal, abort);
68
+ }
54
69
  }
55
70
  // Exit 1 is "a scenario failed", so a crash must not end that way: 3, with the error where the
56
71
  // caller reads it.
57
72
  const code = await main().catch((e) => {
58
- const message = `Proofed hit an unexpected error: ${e instanceof Error ? e.message : String(e)}`;
73
+ const message = maskSecrets(`Proofed hit an unexpected error: ${e instanceof Error ? e.message : String(e)}`);
59
74
  if (argv.includes("--json")) {
60
- io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "internal", message, fix: "Run it again with --verbose; nothing was checked." } }, null, 2)}\n`);
75
+ io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "internal", message, fix: "Run it again with --verbose; nothing was checked." } })}\n`);
61
76
  }
62
77
  else {
63
78
  io.stderr.write(`proofed: ${message}\n`);
@@ -67,4 +82,7 @@ const code = await main().catch((e) => {
67
82
  // A closed Chrome may still be shutting down; its profile folder is removed once it has exited.
68
83
  await stopChildren();
69
84
  // Exit once stdout has drained: a pipe may still hold the end of the JSON.
70
- process.stdout.write("", () => process.exit(code));
85
+ if (process.stdout.destroyed)
86
+ process.exit(code);
87
+ else
88
+ process.stdout.write("", () => process.exit(code));
@@ -1,4 +1,4 @@
1
- import { oidcToken, serverUrl } from "./server.js";
1
+ import { oidcToken, serverUrl } from "../action/server.js";
2
2
  const SEND_EVERY = 1000;
3
3
  const FRAME_EVERY = 2000;
4
4
  // A still taken for an action goes out even right after a regular one, so the cursor shows before the
@@ -78,6 +78,6 @@ export function summarize(live) {
78
78
  done: live.scenarios.filter((s) => s.status !== "waiting" && s.status !== "running").length,
79
79
  ...(on && { scenario: on.name }),
80
80
  ...(step && { step }),
81
- ...(live.fix && { fix: { attempt: live.fix.attempt, of: live.fix.of, doing: live.fix.doing } }),
81
+ ...(live.fix && { fix: { attempt: live.fix.attempt, of: live.fix.of, doing: live.fix.doing, model: live.fix.model } }),
82
82
  };
83
83
  }