@kaynooo/cli-base 0.10.0 → 0.11.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.
package/README.md CHANGED
@@ -28,7 +28,8 @@ proof --keep tests/NewTest.php -- vendor/bin/phpunit tests/NewTest.php
28
28
 
29
29
  - `--ref` defaults to the merge base with `origin/main` when HEAD is on a branch other than `main` that is ahead of it, else HEAD; `--ref HEAD` forces the old default. The `--json` `ref` and the line name the commit it resolved to.
30
30
  - `--runs <n>` (`-n`) runs the command n times in the working tree, for a flaky test: every run must pass, the outcome is `flaky` (exit 1) when it failed before and only some runs fail now, and a line lists each run (`now: run 1 passed, run 2 failed (exit 1), run 3 passed`). The ref side runs once. `--json` adds `runs: [{code}]`.
31
+ - `--timeout <duration>` kills a run that lasts longer (a hung test) and ends with exit 2, a timeout telling nothing of the change.
31
32
  - `--keep`, `--no-link` and the single spaced argument through `sh -c` behave as in `base`.
32
33
  - Four outcomes, each printed as one line followed by the output of the side that explains it: `fails at 1a2b3c4, passes now` (the proof, exit 0, the output before), `passes at 1a2b3c4 too: it does not fail without the change`, `fails at 1a2b3c4 and fails now too` (the output now) and `passes at 1a2b3c4, fails now` (the output now), all three exit 1.
33
34
  - `--json` prints `{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}`, `outcome` being `proved`, `passes-before`, `fails-both` `regressed` or `flaky`.
34
- - Exit codes: 0 fails before and passes now, 1 any other outcome, 2 a usage error, an unknown ref, a refused command, one that cannot start or one that ends with exit 126, 127 or a signal (or 128 plus the signal when interrupted).
35
+ - Exit codes: 0 fails before and passes now, 1 any other outcome, 2 a usage error, an unknown ref, a refused command, one that cannot start or one that ends with exit 125, 126, 127 or a signal, or one that runs past `--timeout` (or 128 plus the signal when interrupted).
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process18 from "process";
5
+ import process19 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,24 +352,20 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
342
359
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
360
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
361
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
363
  `);
347
364
  }
348
365
  function exitRows(exits, colors = paint(process8.stdout)) {
349
366
  if (exits.length === 0)
350
367
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
368
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
369
  }
357
370
  function wantsHelpJson(env = process8.env) {
358
371
  return env.KIT_HELP === "json";
@@ -378,29 +391,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
391
  return [];
379
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
381
395
  function optionRows(options, colors = paint(process8.stdout)) {
382
396
  const rows = Object.entries(options).map(([name, option]) => {
383
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
385
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
388
405
  });
389
406
  const width = Math.max(0, ...rows.map((row) => row.width));
390
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
408
  }
392
409
 
393
410
  // ../kit/src/text.ts
394
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
395
411
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- for (const [i, left] of [...a].entries()) {
412
+ const left = [...a];
413
+ const right = [...b];
414
+ let before = [];
415
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
416
+ for (const [i, x] of left.entries()) {
398
417
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ for (const [j, y] of right.entries()) {
419
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
420
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
421
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
422
+ current.push(cost);
423
+ }
424
+ before = previous;
401
425
  previous = current;
402
426
  }
403
- return previous[b.length] ?? 0;
427
+ return previous[right.length] ?? 0;
404
428
  }
405
429
  function closest(name, names) {
406
430
  const started = names.find((known) => known.startsWith(name));
@@ -419,6 +443,17 @@ function wholeNumber(value, name, fallback, min = 1) {
419
443
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
420
444
  return number;
421
445
  }
446
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
+ function duration(value, name, fallback, unit = "s") {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const match = DURATION.exec(value.trim());
452
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
453
+ if (ms < 1)
454
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
+ return ms;
456
+ }
422
457
 
423
458
  // ../kit/src/args.ts
424
459
  var DASHES = /^-+/;
@@ -791,13 +826,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
791
826
  // ../kit/src/cli.ts
792
827
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
793
828
  import { dirname as dirname3, join as join5 } from "path";
794
- import process13 from "process";
829
+ import process14 from "process";
830
+
831
+ // ../kit/src/notify.ts
832
+ import process12 from "process";
833
+ var NOTIFY_AFTER_MS = 1e4;
834
+ var CANCELLED = 130;
835
+ function base64(text) {
836
+ return Buffer.from(text).toString("base64");
837
+ }
838
+ function notification(title, body, env = process12.env) {
839
+ const id = `kit${process12.pid}`;
840
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
841
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
842
+ }
843
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
844
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
845
+ return;
846
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
847
+ }
795
848
 
796
849
  // ../kit/src/usage.ts
797
850
  import { appendFileSync, mkdirSync } from "fs";
798
851
  import { homedir as homedir3 } from "os";
799
852
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
800
- import process12 from "process";
853
+ import process13 from "process";
801
854
 
802
855
  // ../kit/src/logs.ts
803
856
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -811,14 +864,14 @@ var usageError;
811
864
  function noteUsageError(message) {
812
865
  usageError = message;
813
866
  }
814
- function stateHome(env = process12.env) {
867
+ function stateHome(env = process13.env) {
815
868
  const dir = env.XDG_STATE_HOME;
816
869
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
817
870
  }
818
- function usagePath(env = process12.env) {
871
+ function usagePath(env = process13.env) {
819
872
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
820
873
  }
821
- function usageRecorded(env = process12.env) {
874
+ function usageRecorded(env = process13.env) {
822
875
  const off = env.KAYNOOO_CLI_NO_USAGE;
823
876
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
824
877
  }
@@ -832,7 +885,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
832
885
  usageError = undefined;
833
886
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
834
887
  }
835
- function recordUsage(entry, env = process12.env) {
888
+ function recordUsage(entry, env = process13.env) {
836
889
  if (!usageRecorded(env))
837
890
  return;
838
891
  try {
@@ -909,7 +962,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
909
962
  header(colors, summary),
910
963
  "",
911
964
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
912
- ...replacesRows(replaces, colors),
913
965
  "",
914
966
  ...await commandRows(commands, colors),
915
967
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -923,8 +975,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
923
975
  `);
924
976
  }
925
977
  function printError(prefix, message, hint, cause) {
926
- const colors = paint(process13.stderr);
927
- const styled = takesControlCodes(process13.stderr);
978
+ const colors = paint(process14.stderr);
979
+ const styled = takesControlCodes(process14.stderr);
928
980
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
929
981
  const under = (label, text, tint) => text === undefined ? "" : `
930
982
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -967,11 +1019,11 @@ async function dispatch(level, typed, { version, redact }) {
967
1019
  }
968
1020
  }
969
1021
  if (name === undefined && level.path.length > 1) {
970
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1022
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
971
1023
  return 2;
972
1024
  }
973
1025
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
974
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1026
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
975
1027
  return 0;
976
1028
  }
977
1029
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1106,10 +1158,13 @@ async function runCli(cli, argv = scriptArgs()) {
1106
1158
  const version = cli.version ?? packageVersion();
1107
1159
  if (argv[0] === COMPLETE)
1108
1160
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1161
+ const started = performance.now();
1109
1162
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1163
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1164
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1110
1165
  if (cli.usage !== false) {
1111
1166
  try {
1112
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1167
+ recordUsage(usageEntry(cli.name, command, argv, code));
1113
1168
  } catch {}
1114
1169
  }
1115
1170
  return code;
@@ -1137,11 +1192,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1137
1192
  return 0;
1138
1193
  }
1139
1194
  let code;
1195
+ const started = performance.now();
1140
1196
  try {
1141
1197
  code = await run(argv);
1142
1198
  } catch (error) {
1143
1199
  code = reportThrown(name, error, redact, wantsJson(argv));
1144
1200
  }
1201
+ notifyEnd(name, code, performance.now() - started);
1145
1202
  if (usage !== false) {
1146
1203
  try {
1147
1204
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1158,13 +1215,13 @@ var {Glob } = globalThis.Bun;
1158
1215
  var SESSION_FILES = new Glob("*.json");
1159
1216
  var ACCOUNT_DIRS = new Glob("*/sessions");
1160
1217
  // src/base.ts
1161
- import process16 from "process";
1218
+ import process17 from "process";
1162
1219
 
1163
1220
  // src/worktree.ts
1164
1221
  import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1165
1222
  import { tmpdir } from "os";
1166
1223
  import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1167
- import process15 from "process";
1224
+ import process16 from "process";
1168
1225
  var WHITESPACE = /\s/;
1169
1226
  var ORIGIN_PREFIX = /^origin\//;
1170
1227
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1320,7 +1377,7 @@ async function sweepStale(root) {
1320
1377
  continue;
1321
1378
  const path = join6(tmpdir(), name);
1322
1379
  const stat = lstatSync(path, { throwIfNoEntry: false });
1323
- if (stat?.isDirectory() === true && stat.uid === process15.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1380
+ if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1324
1381
  rmSync(path, { recursive: true, force: true });
1325
1382
  }
1326
1383
  await git2(["worktree", "prune"], root);
@@ -1338,7 +1395,8 @@ function shellCommand(given) {
1338
1395
  const [only] = given;
1339
1396
  return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1340
1397
  }
1341
- async function runIn(dir, command, signals, capture = false) {
1398
+ var TIMEOUT_DRAIN_MS = 500;
1399
+ async function runIn(dir, command, signals, capture = false, timeoutMs) {
1342
1400
  if (signals.signal !== undefined)
1343
1401
  return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1344
1402
  let child;
@@ -1349,10 +1407,16 @@ async function runIn(dir, command, signals, capture = false) {
1349
1407
  }
1350
1408
  signals.forward(child);
1351
1409
  const chunks = [];
1352
- if (capture)
1353
- await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1410
+ let timedOut = false;
1411
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
1412
+ timedOut = true;
1413
+ child.kill("SIGKILL");
1414
+ }, timeoutMs);
1415
+ const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
1354
1416
  await child.exited;
1355
- return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1417
+ clearTimeout(timer);
1418
+ await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
1419
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
1356
1420
  }
1357
1421
  async function collect(stream, chunks) {
1358
1422
  for await (const chunk of stream)
@@ -1410,33 +1474,34 @@ ${USAGE}`);
1410
1474
  if (runsInContainer(given))
1411
1475
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1412
1476
  const command = shellCommand(given);
1413
- const cwd = process16.cwd();
1477
+ const cwd = process17.cwd();
1414
1478
  const { root, prefix } = await checkout(cwd);
1415
1479
  const ref = parsed.values.ref ?? "HEAD";
1416
1480
  const sha = await resolveRef(root, ref);
1417
1481
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1418
1482
  const ran = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true }, async (runDir, signals) => runIn(runDir, command, signals));
1419
1483
  if (!ran.started)
1420
- console.error(`${role("problem", process16.stderr)("base:")} ${ran.output}`);
1421
- console.error(`${role("label", process16.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1484
+ console.error(`${role("problem", process17.stderr)("base:")} ${ran.output}`);
1485
+ console.error(`${role("label", process17.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1422
1486
  return ran.code;
1423
1487
  }
1424
1488
 
1425
1489
  // src/proof.ts
1426
- import process17 from "process";
1427
- var USAGE2 = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1490
+ import process18 from "process";
1491
+ var USAGE2 = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1428
1492
 
1429
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass.`;
1430
- var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal"], [130, "interrupted (128 plus the signal)"]];
1493
+ The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1494
+ var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1431
1495
  var OPTIONS2 = {
1432
1496
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
1433
1497
  runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1434
1498
  keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1499
+ timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
1435
1500
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1436
1501
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1437
1502
  };
1438
1503
  function abnormal(code) {
1439
- return code === 126 || code === 127 || code > 128 && code < 160;
1504
+ return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
1440
1505
  }
1441
1506
  function outcomeOf(before, now) {
1442
1507
  const failed = now.filter((code) => code !== 0).length;
@@ -1473,19 +1538,20 @@ ${USAGE2}`);
1473
1538
  if (runsInContainer(given))
1474
1539
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1475
1540
  const command = shellCommand(given);
1476
- const cwd = process17.cwd();
1541
+ const cwd = process18.cwd();
1477
1542
  const { root, prefix } = await checkout(cwd);
1478
1543
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1479
1544
  const ref = parsed.values.ref ?? await defaultProofRef(root);
1480
1545
  const sha = await resolveRef(root, ref);
1481
1546
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1547
+ const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
1482
1548
  const signals = holdSignals();
1483
1549
  let before;
1484
1550
  const nowRuns = [];
1485
1551
  try {
1486
- before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1552
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
1487
1553
  for (let i = 0;i < runs && signals.signal === undefined; i++)
1488
- nowRuns.push(await runIn(cwd, command, signals, true));
1554
+ nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
1489
1555
  } finally {
1490
1556
  signals.release();
1491
1557
  }
@@ -1494,6 +1560,10 @@ ${USAGE2}`);
1494
1560
  for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1495
1561
  if (!run.started)
1496
1562
  fail(run.output);
1563
+ if (run.timedOut === true)
1564
+ fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
1565
+
1566
+ ${folded(run.output)}`}`);
1497
1567
  if (abnormal(run.code))
1498
1568
  fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1499
1569
 
@@ -1508,7 +1578,7 @@ ${folded(run.output)}`}`);
1508
1578
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1509
1579
  return proved ? 0 : 1;
1510
1580
  }
1511
- console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
1581
+ console.log(role(proved ? "ok" : "problem", process18.stdout)(message));
1512
1582
  if (runs > 1)
1513
1583
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1514
1584
  const shown = side === "before" ? before : now;
@@ -1519,7 +1589,7 @@ ${folded(shown.output)}`);
1519
1589
  }
1520
1590
 
1521
1591
  // src/cli.ts
1522
- process18.exitCode = await runCli({
1592
+ process19.exitCode = await runCli({
1523
1593
  name: "base",
1524
1594
  about: "runs a command at HEAD or another ref in a temporary worktree, the working tree untouched",
1525
1595
  replaces: "git stash, a test run, then git stash pop",
package/dist/proof-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/proof-cli.ts
5
- import process17 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,24 +352,20 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
342
359
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
360
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
361
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
363
  `);
347
364
  }
348
365
  function exitRows(exits, colors = paint(process8.stdout)) {
349
366
  if (exits.length === 0)
350
367
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
368
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
369
  }
357
370
  function wantsHelpJson(env = process8.env) {
358
371
  return env.KIT_HELP === "json";
@@ -378,29 +391,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
391
  return [];
379
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
381
395
  function optionRows(options, colors = paint(process8.stdout)) {
382
396
  const rows = Object.entries(options).map(([name, option]) => {
383
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
385
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
388
405
  });
389
406
  const width = Math.max(0, ...rows.map((row) => row.width));
390
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
408
  }
392
409
 
393
410
  // ../kit/src/text.ts
394
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
395
411
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- for (const [i, left] of [...a].entries()) {
412
+ const left = [...a];
413
+ const right = [...b];
414
+ let before = [];
415
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
416
+ for (const [i, x] of left.entries()) {
398
417
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ for (const [j, y] of right.entries()) {
419
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
420
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
421
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
422
+ current.push(cost);
423
+ }
424
+ before = previous;
401
425
  previous = current;
402
426
  }
403
- return previous[b.length] ?? 0;
427
+ return previous[right.length] ?? 0;
404
428
  }
405
429
  function closest(name, names) {
406
430
  const started = names.find((known) => known.startsWith(name));
@@ -419,6 +443,17 @@ function wholeNumber(value, name, fallback, min = 1) {
419
443
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
420
444
  return number;
421
445
  }
446
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
+ function duration(value, name, fallback, unit = "s") {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const match = DURATION.exec(value.trim());
452
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
453
+ if (ms < 1)
454
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
+ return ms;
456
+ }
422
457
 
423
458
  // ../kit/src/args.ts
424
459
  var DASHES = /^-+/;
@@ -791,13 +826,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
791
826
  // ../kit/src/cli.ts
792
827
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
793
828
  import { dirname as dirname3, join as join5 } from "path";
794
- import process13 from "process";
829
+ import process14 from "process";
830
+
831
+ // ../kit/src/notify.ts
832
+ import process12 from "process";
833
+ var NOTIFY_AFTER_MS = 1e4;
834
+ var CANCELLED = 130;
835
+ function base64(text) {
836
+ return Buffer.from(text).toString("base64");
837
+ }
838
+ function notification(title, body, env = process12.env) {
839
+ const id = `kit${process12.pid}`;
840
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
841
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
842
+ }
843
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
844
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
845
+ return;
846
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
847
+ }
795
848
 
796
849
  // ../kit/src/usage.ts
797
850
  import { appendFileSync, mkdirSync } from "fs";
798
851
  import { homedir as homedir3 } from "os";
799
852
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
800
- import process12 from "process";
853
+ import process13 from "process";
801
854
 
802
855
  // ../kit/src/logs.ts
803
856
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -811,14 +864,14 @@ var usageError;
811
864
  function noteUsageError(message) {
812
865
  usageError = message;
813
866
  }
814
- function stateHome(env = process12.env) {
867
+ function stateHome(env = process13.env) {
815
868
  const dir = env.XDG_STATE_HOME;
816
869
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
817
870
  }
818
- function usagePath(env = process12.env) {
871
+ function usagePath(env = process13.env) {
819
872
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
820
873
  }
821
- function usageRecorded(env = process12.env) {
874
+ function usageRecorded(env = process13.env) {
822
875
  const off = env.KAYNOOO_CLI_NO_USAGE;
823
876
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
824
877
  }
@@ -832,7 +885,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
832
885
  usageError = undefined;
833
886
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
834
887
  }
835
- function recordUsage(entry, env = process12.env) {
888
+ function recordUsage(entry, env = process13.env) {
836
889
  if (!usageRecorded(env))
837
890
  return;
838
891
  try {
@@ -909,7 +962,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
909
962
  header(colors, summary),
910
963
  "",
911
964
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
912
- ...replacesRows(replaces, colors),
913
965
  "",
914
966
  ...await commandRows(commands, colors),
915
967
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -923,8 +975,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
923
975
  `);
924
976
  }
925
977
  function printError(prefix, message, hint, cause) {
926
- const colors = paint(process13.stderr);
927
- const styled = takesControlCodes(process13.stderr);
978
+ const colors = paint(process14.stderr);
979
+ const styled = takesControlCodes(process14.stderr);
928
980
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
929
981
  const under = (label, text, tint) => text === undefined ? "" : `
930
982
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -967,11 +1019,11 @@ async function dispatch(level, typed, { version, redact }) {
967
1019
  }
968
1020
  }
969
1021
  if (name === undefined && level.path.length > 1) {
970
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1022
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
971
1023
  return 2;
972
1024
  }
973
1025
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
974
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1026
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
975
1027
  return 0;
976
1028
  }
977
1029
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1106,10 +1158,13 @@ async function runCli(cli, argv = scriptArgs()) {
1106
1158
  const version = cli.version ?? packageVersion();
1107
1159
  if (argv[0] === COMPLETE)
1108
1160
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1161
+ const started = performance.now();
1109
1162
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1163
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1164
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1110
1165
  if (cli.usage !== false) {
1111
1166
  try {
1112
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1167
+ recordUsage(usageEntry(cli.name, command, argv, code));
1113
1168
  } catch {}
1114
1169
  }
1115
1170
  return code;
@@ -1137,11 +1192,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1137
1192
  return 0;
1138
1193
  }
1139
1194
  let code;
1195
+ const started = performance.now();
1140
1196
  try {
1141
1197
  code = await run(argv);
1142
1198
  } catch (error) {
1143
1199
  code = reportThrown(name, error, redact, wantsJson(argv));
1144
1200
  }
1201
+ notifyEnd(name, code, performance.now() - started);
1145
1202
  if (usage !== false) {
1146
1203
  try {
1147
1204
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1158,13 +1215,13 @@ var {Glob } = globalThis.Bun;
1158
1215
  var SESSION_FILES = new Glob("*.json");
1159
1216
  var ACCOUNT_DIRS = new Glob("*/sessions");
1160
1217
  // src/proof.ts
1161
- import process16 from "process";
1218
+ import process17 from "process";
1162
1219
 
1163
1220
  // src/worktree.ts
1164
1221
  import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1165
1222
  import { tmpdir } from "os";
1166
1223
  import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1167
- import process15 from "process";
1224
+ import process16 from "process";
1168
1225
  var WHITESPACE = /\s/;
1169
1226
  var ORIGIN_PREFIX = /^origin\//;
1170
1227
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1320,7 +1377,7 @@ async function sweepStale(root) {
1320
1377
  continue;
1321
1378
  const path = join6(tmpdir(), name);
1322
1379
  const stat = lstatSync(path, { throwIfNoEntry: false });
1323
- if (stat?.isDirectory() === true && stat.uid === process15.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1380
+ if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1324
1381
  rmSync(path, { recursive: true, force: true });
1325
1382
  }
1326
1383
  await git2(["worktree", "prune"], root);
@@ -1338,7 +1395,8 @@ function shellCommand(given) {
1338
1395
  const [only] = given;
1339
1396
  return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1340
1397
  }
1341
- async function runIn(dir, command, signals, capture = false) {
1398
+ var TIMEOUT_DRAIN_MS = 500;
1399
+ async function runIn(dir, command, signals, capture = false, timeoutMs) {
1342
1400
  if (signals.signal !== undefined)
1343
1401
  return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1344
1402
  let child;
@@ -1349,10 +1407,16 @@ async function runIn(dir, command, signals, capture = false) {
1349
1407
  }
1350
1408
  signals.forward(child);
1351
1409
  const chunks = [];
1352
- if (capture)
1353
- await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1410
+ let timedOut = false;
1411
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
1412
+ timedOut = true;
1413
+ child.kill("SIGKILL");
1414
+ }, timeoutMs);
1415
+ const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
1354
1416
  await child.exited;
1355
- return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1417
+ clearTimeout(timer);
1418
+ await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
1419
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
1356
1420
  }
1357
1421
  async function collect(stream, chunks) {
1358
1422
  for await (const chunk of stream)
@@ -1391,19 +1455,20 @@ async function inWorktree(options, body) {
1391
1455
  }
1392
1456
 
1393
1457
  // src/proof.ts
1394
- var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1458
+ var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1395
1459
 
1396
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass.`;
1397
- var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal"], [130, "interrupted (128 plus the signal)"]];
1460
+ The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1461
+ var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1398
1462
  var OPTIONS = {
1399
1463
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
1400
1464
  runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1401
1465
  keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1466
+ timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
1402
1467
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1403
1468
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1404
1469
  };
1405
1470
  function abnormal(code) {
1406
- return code === 126 || code === 127 || code > 128 && code < 160;
1471
+ return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
1407
1472
  }
1408
1473
  function outcomeOf(before, now) {
1409
1474
  const failed = now.filter((code) => code !== 0).length;
@@ -1440,19 +1505,20 @@ ${USAGE}`);
1440
1505
  if (runsInContainer(given))
1441
1506
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1442
1507
  const command = shellCommand(given);
1443
- const cwd = process16.cwd();
1508
+ const cwd = process17.cwd();
1444
1509
  const { root, prefix } = await checkout(cwd);
1445
1510
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1446
1511
  const ref = parsed.values.ref ?? await defaultProofRef(root);
1447
1512
  const sha = await resolveRef(root, ref);
1448
1513
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1514
+ const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
1449
1515
  const signals = holdSignals();
1450
1516
  let before;
1451
1517
  const nowRuns = [];
1452
1518
  try {
1453
- before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1519
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
1454
1520
  for (let i = 0;i < runs && signals.signal === undefined; i++)
1455
- nowRuns.push(await runIn(cwd, command, signals, true));
1521
+ nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
1456
1522
  } finally {
1457
1523
  signals.release();
1458
1524
  }
@@ -1461,6 +1527,10 @@ ${USAGE}`);
1461
1527
  for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1462
1528
  if (!run.started)
1463
1529
  fail(run.output);
1530
+ if (run.timedOut === true)
1531
+ fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
1532
+
1533
+ ${folded(run.output)}`}`);
1464
1534
  if (abnormal(run.code))
1465
1535
  fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1466
1536
 
@@ -1475,7 +1545,7 @@ ${folded(run.output)}`}`);
1475
1545
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1476
1546
  return proved ? 0 : 1;
1477
1547
  }
1478
- console.log(role(proved ? "ok" : "problem", process16.stdout)(message));
1548
+ console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
1479
1549
  if (runs > 1)
1480
1550
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1481
1551
  const shown = side === "before" ? before : now;
@@ -1486,4 +1556,4 @@ ${folded(shown.output)}`);
1486
1556
  }
1487
1557
 
1488
1558
  // src/proof-cli.ts
1489
- process17.exitCode = await runMain({ name: "proof", run: proof });
1559
+ process18.exitCode = await runMain({ name: "proof", run: proof });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-base",
3
3
  "type": "module",
4
- "version": "0.10.0",
4
+ "version": "0.11.0",
5
5
  "description": "base: a command run at HEAD or another ref in a temporary worktree, the working tree left untouched.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -38,6 +38,6 @@
38
38
  "proof": "$npm_execpath src/proof-cli.ts"
39
39
  },
40
40
  "devDependencies": {
41
- "@kaynooo/cli-kit": "0.38.2"
41
+ "@kaynooo/cli-kit": "0.39.0"
42
42
  }
43
43
  }