@kaynooo/cli-guard 0.12.0 → 0.14.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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +370 -71
  3. package/package.json +8 -8
package/README.md CHANGED
@@ -14,7 +14,7 @@ guard check --json --cwd "$PWD" - < command.txt
14
14
  | --- | --- | --- |
15
15
  | `remote` | `ssh`, `scp`, `sftp`, `mosh`, `rsync` to a host, `DOCKER_HOST=ssh://`, `docker -H ssh://` | `src/remote.ts` |
16
16
  | `git` | `git stash` (pointing at `proof`, `base`, a commit first or `git worktree add`), `git add -A`/`.`/`-u`, `git commit -a` in any flag cluster, `git push` the user did not ask for, `git push --tags` without `--atomic` | `src/git.ts` |
17
- | `destructive` | `git reset --hard`, discarding the whole tree (`checkout -- .`, `checkout -f`, `restore .`, `switch -f`), `git clean -f`, a force push (`--force`, `-f`, `--mirror`, `+refspec`; `--force-with-lease` passes), `git branch -D`, a `git rebase` (`--continue` and `--abort` pass), `filter-branch`, `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory, a download piped into a shell (`curl ... \| sh`, `bash <(curl ...)`); each refusal names the safe route: a commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` | `src/destructive.ts` |
17
+ | `destructive` | `git reset --hard`, discarding the whole tree (`checkout -- .`, `checkout -f`, `restore .`, `switch -f`), `git clean -f`, a force push (`--force`, `-f`, `--mirror`, `+refspec`; `--force-with-lease` passes), `git branch -D`, a `git rebase` (`--continue` and `--abort` pass), `filter-branch`, `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory, a download piped into a shell (`curl ... \| sh`, `bash <(curl ...)`), `dl --exec --yes` on a script no `--sha256` or `--sums` pins; each refusal names the safe route: a commit with `gc` first, `base`, `git worktree add`, `--force-with-lease`, `dl <url>` then `dl <url> --exec --sha256 <sha>` | `src/destructive.ts` |
18
18
  | `commit` | a commit message breaking the format: no Conventional Commit title, a trailer, a body over two lines, a bullet list, a hard wrap; `-m`, `-F <file>` and `-F -` with a heredoc are read; the refusal spells the rule out and points at `gc` | `src/commit.ts`, the validator in `@kaynooo/cli-git` |
19
19
  | `sql` | a SQL client, console or dump tool fed a write (INSERT, UPDATE, DELETE, DDL, migrations, fixtures) outside a test database | `@kaynooo/cli-db` (`src/clients.ts`, `src/guard.ts`) |
20
20
  | `env` | a command reading, writing or printing an env file or the whole environment; `guard path` refuses a file tool opening one | `@kaynooo/cli-env` (`src/guard.ts`) |
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
6
6
  import { homedir as homedir4 } from "os";
7
7
  import { dirname as dirname5 } from "path";
8
- import process16 from "process";
8
+ import process17 from "process";
9
9
  // ../kit/src/args.ts
10
10
  import process9 from "process";
11
11
  import { parseArgs } from "util";
@@ -344,6 +344,23 @@ var STATUS_WORDS = {
344
344
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
345
345
 
346
346
  // ../kit/src/format.ts
347
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
348
+ function formatSeconds(total) {
349
+ let rest = Math.max(0, Math.round(total));
350
+ const amounts = UNITS.map(([unit, size]) => {
351
+ const amount = Math.floor(rest / size);
352
+ rest -= amount * size;
353
+ return `${amount}${unit}`;
354
+ });
355
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
356
+ if (first === -1)
357
+ return "0s";
358
+ const next = amounts[first + 1];
359
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
360
+ }
361
+ function formatDuration(ms) {
362
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
363
+ }
347
364
  function upTo(text, separator) {
348
365
  const end = text.indexOf(separator);
349
366
  return end === -1 ? text : text.slice(0, end);
@@ -352,24 +369,20 @@ var ESCAPE = String.fromCharCode(27);
352
369
 
353
370
  // ../kit/src/help.ts
354
371
  import process7 from "process";
355
- var OPTIONAL = /\[[^\]]+\]/g;
372
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
356
373
  var USAGE_PREFIX = /^usage:\s*/i;
357
374
  var FULL_STOP = /\.$/;
358
375
  function usageLine(usage, colors = paint(process7.stdout)) {
359
376
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
360
377
  }
361
- function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
362
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
378
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], exits = [] } = {}) {
379
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
363
380
  `);
364
381
  }
365
382
  function exitRows(exits, colors = paint(process7.stdout)) {
366
383
  if (exits.length === 0)
367
384
  return [];
368
- const width = Math.max(...exits.map(([code]) => String(code).length));
369
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
370
- }
371
- function replacesRows(replaces, colors = paint(process7.stdout)) {
372
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
385
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
373
386
  }
374
387
  function wantsHelpJson(env = process7.env) {
375
388
  return env.KIT_HELP === "json";
@@ -395,29 +408,40 @@ function exampleRows(examples, colors = paint(process7.stdout)) {
395
408
  return [];
396
409
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
397
410
  }
411
+ var MAX_INLINE_CHOICES = 24;
398
412
  function optionRows(options, colors = paint(process7.stdout)) {
399
413
  const rows = Object.entries(options).map(([name, option]) => {
400
414
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
401
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
415
+ const choices = option.choices?.join("|");
416
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
417
+ const named = inline ? `<${choices}>` : "<value>";
402
418
  const placeholder = option.optional === undefined ? named : `[${named}]`;
403
419
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
404
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
420
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
421
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
405
422
  });
406
423
  const width = Math.max(0, ...rows.map((row) => row.width));
407
424
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
408
425
  }
409
426
 
410
427
  // ../kit/src/text.ts
411
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
412
428
  function distance(a, b) {
413
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
414
- for (const [i, left] of [...a].entries()) {
429
+ const left = [...a];
430
+ const right = [...b];
431
+ let before = [];
432
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
433
+ for (const [i, x] of left.entries()) {
415
434
  const current = [i + 1];
416
- for (const [j, right] of [...b].entries())
417
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
435
+ for (const [j, y] of right.entries()) {
436
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
437
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
438
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
439
+ current.push(cost);
440
+ }
441
+ before = previous;
418
442
  previous = current;
419
443
  }
420
- return previous[b.length] ?? 0;
444
+ return previous[right.length] ?? 0;
421
445
  }
422
446
  function closest(name, names) {
423
447
  const started = names.find((known) => known.startsWith(name));
@@ -485,7 +509,7 @@ class Completing {
485
509
  }
486
510
  var completion = { active: false };
487
511
  var OUTPUT_OPTIONS = {
488
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
512
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
489
513
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
490
514
  };
491
515
  function applyOutput(color, plain, env = process9.env) {
@@ -779,13 +803,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
779
803
  // ../kit/src/cli.ts
780
804
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
781
805
  import { dirname as dirname3, join as join5 } from "path";
782
- import process13 from "process";
806
+ import process14 from "process";
807
+
808
+ // ../kit/src/completions.ts
809
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
810
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
811
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
812
+ set -l current (commandline -ct)
813
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
814
+ if test "$line" = __files__
815
+ __fish_complete_path $current
816
+ else
817
+ echo $line
818
+ end
819
+ end
820
+ end`;
821
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
822
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
823
+ local -a lines
824
+ COMPREPLY=()
825
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
826
+ for line in "\${lines[@]}"; do
827
+ if [[ $line == __files__ ]]; then
828
+ COMPREPLY+=($(compgen -f -- "$cur"))
829
+ else
830
+ words+="\${line%%$'\\t'*}"$'\\n'
831
+ fi
832
+ done
833
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
834
+ }`;
835
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
836
+ local line
837
+ local -a described plain
838
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
839
+ if [[ $line == __files__ ]]; then
840
+ _files
841
+ elif [[ $line == *$'\\t'* ]]; then
842
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
843
+ else
844
+ plain+=("$line")
845
+ fi
846
+ done
847
+ (( \${#described} )) && _describe -V value described
848
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
849
+ return 0
850
+ }`;
851
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
852
+ if (shell === "fish")
853
+ return `${header}
854
+ ${FISH_FUNCTION}
855
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
856
+ `).join("")}`;
857
+ if (shell === "bash")
858
+ return `${header}
859
+ ${BASH_FUNCTION}
860
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
861
+ `;
862
+ return `${header}
863
+ ${ZSH_FUNCTION}
864
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
865
+ `;
866
+ }
867
+
868
+ // ../kit/src/notify.ts
869
+ import process12 from "process";
870
+ var NOTIFY_AFTER_MS = 1e4;
871
+ var CANCELLED = 130;
872
+ function base64(text) {
873
+ return Buffer.from(text).toString("base64");
874
+ }
875
+ function notification(title, body, env = process12.env) {
876
+ const id = `kit${process12.pid}`;
877
+ 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\\`];
878
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
879
+ }
880
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
881
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
882
+ return;
883
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
884
+ }
783
885
 
784
886
  // ../kit/src/usage.ts
785
887
  import { appendFileSync, mkdirSync } from "fs";
786
888
  import { homedir as homedir3 } from "os";
787
889
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
788
- import process12 from "process";
890
+ import process13 from "process";
789
891
 
790
892
  // ../kit/src/logs.ts
791
893
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -799,14 +901,14 @@ var usageError;
799
901
  function noteUsageError(message) {
800
902
  usageError = message;
801
903
  }
802
- function stateHome(env = process12.env) {
904
+ function stateHome(env = process13.env) {
803
905
  const dir = env.XDG_STATE_HOME;
804
906
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
805
907
  }
806
- function usagePath(env = process12.env) {
908
+ function usagePath(env = process13.env) {
807
909
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
808
910
  }
809
- function usageRecorded(env = process12.env) {
911
+ function usageRecorded(env = process13.env) {
810
912
  const off = env.KAYNOOO_CLI_NO_USAGE;
811
913
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
812
914
  }
@@ -820,7 +922,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
820
922
  usageError = undefined;
821
923
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
822
924
  }
823
- function recordUsage(entry, env = process12.env) {
925
+ function recordUsage(entry, env = process13.env) {
824
926
  if (!usageRecorded(env))
825
927
  return;
826
928
  try {
@@ -836,7 +938,11 @@ var LEVEL_OPTIONS = {
836
938
  ...OUTPUT_OPTIONS,
837
939
  help: { type: "boolean", short: "h", description: "show this help" }
838
940
  };
839
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
941
+ var TOP_OPTIONS = {
942
+ ...LEVEL_OPTIONS,
943
+ version: { type: "boolean", short: "v", description: "print the version" },
944
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
945
+ };
840
946
  async function commandRows(all, colors) {
841
947
  const commands = shown(all);
842
948
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -897,7 +1003,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
897
1003
  header(colors, summary),
898
1004
  "",
899
1005
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
900
- ...replacesRows(replaces, colors),
901
1006
  "",
902
1007
  ...await commandRows(commands, colors),
903
1008
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -911,8 +1016,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
911
1016
  `);
912
1017
  }
913
1018
  function printError(prefix, message, hint, cause) {
914
- const colors = paint(process13.stderr);
915
- const styled = takesControlCodes(process13.stderr);
1019
+ const colors = paint(process14.stderr);
1020
+ const styled = takesControlCodes(process14.stderr);
916
1021
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
917
1022
  const under = (label, text, tint) => text === undefined ? "" : `
918
1023
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -955,11 +1060,11 @@ async function dispatch(level, typed, { version, redact }) {
955
1060
  }
956
1061
  }
957
1062
  if (name === undefined && level.path.length > 1) {
958
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1063
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
959
1064
  return 2;
960
1065
  }
961
1066
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
962
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1067
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
963
1068
  return 0;
964
1069
  }
965
1070
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1070,6 +1175,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1070
1175
  }
1071
1176
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1072
1177
  }
1178
+ var COMPLETIONS = "--completions";
1179
+ function flagValue([flag = "", ...rest]) {
1180
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1181
+ }
1182
+ function printCompletionScript(name, args) {
1183
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1184
+ if (shell === undefined || args.length !== 1) {
1185
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1186
+ return 2;
1187
+ }
1188
+ console.log(completionScript(shell, [name]).trimEnd());
1189
+ return 0;
1190
+ }
1073
1191
  async function printCandidates(found) {
1074
1192
  for (const line of await found)
1075
1193
  console.log(line);
@@ -1094,10 +1212,15 @@ async function runCli(cli, argv = scriptArgs()) {
1094
1212
  const version = cli.version ?? packageVersion();
1095
1213
  if (argv[0] === COMPLETE)
1096
1214
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1215
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1216
+ return printCompletionScript(cli.name, flagValue(argv));
1217
+ const started = performance.now();
1097
1218
  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 });
1219
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1220
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1098
1221
  if (cli.usage !== false) {
1099
1222
  try {
1100
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1223
+ recordUsage(usageEntry(cli.name, command, argv, code));
1101
1224
  } catch {}
1102
1225
  }
1103
1226
  return code;
@@ -1157,6 +1280,7 @@ var ANSI_ESCAPES = { n: `
1157
1280
  var ANSI_DIGITS = { x: 2, u: 4, U: 8 };
1158
1281
  var OCTAL = /^[0-7]{1,3}/;
1159
1282
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1283
+ var INPUT_REDIRECT = /^\d*<(?![<&(>])/;
1160
1284
  var MAX_DEPTH = 8;
1161
1285
  var MAX_BRACES = 256;
1162
1286
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
@@ -1584,6 +1708,8 @@ function parseCommand(text) {
1584
1708
  } else if (tokens.length > 1 && CASE_LABEL.test(first)) {
1585
1709
  isWrapped = true;
1586
1710
  tokens.shift();
1711
+ } else if (INPUT_REDIRECT.test(first)) {
1712
+ tokens.splice(0, first.replace(INPUT_REDIRECT, "") === "" ? 2 : 1);
1587
1713
  } else if (spec !== undefined) {
1588
1714
  isWrapped = true;
1589
1715
  tokens.shift();
@@ -2188,6 +2314,52 @@ function printsTrackedEnv(program, args) {
2188
2314
  return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2189
2315
  }
2190
2316
 
2317
+ // ../env/src/mask.ts
2318
+ var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
2319
+ var PLACEHOLDER = /^[$%{<(*/]/;
2320
+ function isPlaceholder(value) {
2321
+ return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
2322
+ }
2323
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
2324
+ var WEAK_NAME = "token|credentials?|auth";
2325
+ var PLAIN_WORD = /^[a-z]+$/i;
2326
+ var AFTER_COLON = /:\s*$/;
2327
+ var DIGIT = /\d/;
2328
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
2329
+ function isProse(value, before) {
2330
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
2331
+ }
2332
+ function isWeak(value, before) {
2333
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
2334
+ }
2335
+ function keyed(names, value) {
2336
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
2337
+ }
2338
+ var TOKEN_FORMATS = [
2339
+ { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
2340
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
2341
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
2342
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
2343
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
2344
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
2345
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
2346
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
2347
+ { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
2348
+ { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
2349
+ { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
2350
+ { kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
2351
+ { kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
2352
+ { kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
2353
+ { kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
2354
+ { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
2355
+ { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
2356
+ { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
2357
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
2358
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
2359
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
2360
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
2361
+ ];
2362
+
2191
2363
  // ../env/src/files.ts
2192
2364
  var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
2193
2365
  var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
@@ -2698,7 +2870,7 @@ function wrap(command) {
2698
2870
  // ../pkg/src/added.ts
2699
2871
  import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
2700
2872
  import { dirname as dirname4, join as join6 } from "path";
2701
- import process15 from "process";
2873
+ import process16 from "process";
2702
2874
  var REDIRECT2 = /^\d*[<>]/;
2703
2875
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2704
2876
  var ADDS = {
@@ -2730,7 +2902,7 @@ function manifestName(folder) {
2730
2902
  }
2731
2903
  function ownPackages() {
2732
2904
  const names = new Set;
2733
- let folder = process15.cwd();
2905
+ let folder = process16.cwd();
2734
2906
  while (true) {
2735
2907
  const name = manifestName(folder);
2736
2908
  if (name !== undefined)
@@ -2835,7 +3007,7 @@ var OPTION_FLAGS = new Map([
2835
3007
  ]);
2836
3008
  var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
2837
3009
  var VALUE_FLAGS2 = new Set([...DIR_FLAGS, "--filter", "-F"]);
2838
- var PLAIN_WORD = /^[\w=@./:+-]+$/;
3010
+ var PLAIN_WORD2 = /^[\w=@./:+-]+$/;
2839
3011
  function actions(byAction) {
2840
3012
  return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
2841
3013
  }
@@ -2848,7 +3020,7 @@ function translate(from, to, subcommand, rest) {
2848
3020
  const listed = ACTIONS[from].get(subcommand);
2849
3021
  const action = listed === "install" && packages.length > 0 ? "add" : listed;
2850
3022
  const command = action ? COMMANDS[to][action] : undefined;
2851
- if (!action || command === undefined || !packages.every((name) => PLAIN_WORD.test(name)))
3023
+ if (!action || command === undefined || !packages.every((name) => PLAIN_WORD2.test(name)))
2852
3024
  return null;
2853
3025
  const options = [];
2854
3026
  for (const flag of flags) {
@@ -2902,7 +3074,7 @@ function mismatchFor(request, pinned) {
2902
3074
  return null;
2903
3075
  const expected = [...pinned.managers];
2904
3076
  const only = expected.length === 1 ? expected[0] : undefined;
2905
- const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD.test(word));
3077
+ const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD2.test(word));
2906
3078
  const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
2907
3079
  const leading = piece.text.slice(0, piece.text.length - piece.text.trimStart().length);
2908
3080
  const trailing = piece.text.slice(piece.text.trimEnd().length);
@@ -3181,6 +3353,10 @@ var FETCH_SUBSTITUTION = /(?:\$\(|<\(|`)\s*(?:curl|wget|fetch)\b/;
3181
3353
  var RECURSIVE_LETTER = /r/i;
3182
3354
  var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
3183
3355
  var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
3356
+ var ABSOLUTE_HOME = /^(?:home\/[^/]+|root)\/([^/]+)$/;
3357
+ var EXEC_FLAGS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
3358
+ var REMOVER = /(?:^|\/)rm$/;
3359
+ var TRAILING_SLASH = /\/$/;
3184
3360
  var SAFE_REBASE = new Set(["--abort", "--continue", "--quit", "--show-current-patch", "--skip", "--edit-todo"]);
3185
3361
  var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
3186
3362
  var VERSION_SUFFIX = /[\d.]+$/;
@@ -3196,7 +3372,13 @@ var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch hol
3196
3372
  var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
3197
3373
  var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
3198
3374
  var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
3199
- var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
3375
+ var PROTECTED_RM = "Never `rm -r` on a `.git` directory, on `~/Workspace` itself or on a dot-directory of the home (`~/.ssh`, `$HOME/.claude`, `~/.config`): it deletes a repository's whole history, every project, or the credentials and settings of the machine. Remove the named files inside, or ask the user to run it.";
3376
+ var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME`): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
3377
+ var REFLOG_EXPIRE = "Never `git reflog expire`, `git gc --prune=now` or `git update-ref -d`: they drop the reflog, unreachable commits or a ref, the only way back from a bad reset or rebase. Let git prune on its own schedule, and ask the user to run one when it is really wanted.";
3378
+ var DOCKER_PRUNE_ALL = "Never `docker system prune -a` (`--all`): it removes every image not used by a running container, volumes of other projects' stacks included with --volumes. `docker system prune` without -a drops only dangling data; remove named images with `docker rmi`.";
3379
+ var PINNED_RUN = "`dl <url>` downloads it and prints its path and sha256; read that file, then `dl <url> --exec --sha256 <sha>` runs exactly what was read.";
3380
+ var PIPE_TO_SHELL = `Never run what \`curl\`/\`wget\` fetches straight in a shell (\`| sh\`, \`bash <(curl ...)\`, \`eval "$(curl ...)"\`): it runs code nobody read. ${PINNED_RUN} Or hand the command to the user.`;
3381
+ var UNPINNED_EXEC = `Never \`dl --exec --yes\` a script no \`--sha256\` or \`--sums\` pins: it runs code nobody read. ${PINNED_RUN}`;
3200
3382
  function hasOption(args, long, shorts) {
3201
3383
  for (const arg of args) {
3202
3384
  if (arg === "--")
@@ -3225,15 +3407,32 @@ function isBroadPath(path) {
3225
3407
  return parts.length === 0;
3226
3408
  return isAbsolute ? parts.length <= 1 : parts.every((part) => part === "..");
3227
3409
  }
3228
- function removesBroadly(args) {
3229
- if (args.includes("--no-preserve-root"))
3230
- return true;
3410
+ function recursiveTargets(args) {
3231
3411
  const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
3232
3412
  const isRecursive = options.some((arg) => arg === "--recursive" || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
3233
- if (!isRecursive)
3234
- return false;
3235
- const targets = args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--"));
3236
- return targets.some(isBroadPath);
3413
+ return isRecursive ? args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--")) : [];
3414
+ }
3415
+ function isProtectedPath(path) {
3416
+ const home = HOME_PREFIX.exec(path);
3417
+ const parts = (home === null ? path : path.slice(home[0].length)).split("/").filter((part) => part !== "" && part !== ".");
3418
+ const last = parts.at(-1) ?? "";
3419
+ const absolute = path.startsWith("/") ? ABSOLUTE_HOME.exec(parts.join("/")) : null;
3420
+ const homeChild = parts.length === 1 ? last : undefined;
3421
+ const child = home === null ? absolute?.[1] : homeChild;
3422
+ return last === ".git" || child !== undefined && (child === "Workspace" || child.startsWith(".") && child !== "..");
3423
+ }
3424
+ function deletesFromHome(args) {
3425
+ const firstOption = args.findIndex((arg) => arg.startsWith("-") || arg === "(" || arg === "!");
3426
+ const starts = firstOption === -1 ? args : args.slice(0, firstOption);
3427
+ const deletes = args.includes("-delete") || args.some((arg, i) => EXEC_FLAGS.has(arg) && REMOVER.test(args[i + 1] ?? ""));
3428
+ return deletes && starts.some((start) => start === "/" || start.replace(TRAILING_SLASH, "") === HOME_PREFIX.exec(start)?.[0]);
3429
+ }
3430
+ function dockerPrunesAll(args) {
3431
+ const system = args.indexOf("system");
3432
+ return system !== -1 && args[system + 1] === "prune" && hasOption(args.slice(system + 2), ["--all"], "a");
3433
+ }
3434
+ function removesBroadly(args) {
3435
+ return args.includes("--no-preserve-root") || recursiveTargets(args).some(isBroadPath);
3237
3436
  }
3238
3437
  function checksOutTree(rest, operands) {
3239
3438
  if (rest.includes("--"))
@@ -3264,6 +3463,12 @@ function gitDestructive(name, rest) {
3264
3463
  }
3265
3464
  if (name === "branch")
3266
3465
  return hasOption(rest, [], "D") || hasOption(rest, ["--delete"], "d") && hasOption(rest, ["--force"], "f") ? BRANCH_DELETE : null;
3466
+ if (name === "reflog")
3467
+ return rest[0] === "expire" ? REFLOG_EXPIRE : null;
3468
+ if (name === "gc")
3469
+ return rest.some((arg) => arg === "--prune=now" || arg === "--prune=all") ? REFLOG_EXPIRE : null;
3470
+ if (name === "update-ref")
3471
+ return hasOption(rest, ["--delete"], "d") ? REFLOG_EXPIRE : null;
3267
3472
  if (name === "rebase")
3268
3473
  return rest.some((arg) => SAFE_REBASE.has(arg)) ? null : REBASE;
3269
3474
  return name === "filter-branch" || name === "filter-repo" ? REWRITE_HISTORY : null;
@@ -3290,13 +3495,26 @@ function runsDownload(command) {
3290
3495
  return (SHELLS.has(program) || EVALUATORS.has(program)) && FETCH_SUBSTITUTION.test(piece.command);
3291
3496
  });
3292
3497
  }
3498
+ function runsUnpinned(args) {
3499
+ const own = args.includes("--") ? args.slice(0, args.indexOf("--")) : args;
3500
+ const given = (name) => own.some((arg) => arg === name || arg.startsWith(`${name}=`));
3501
+ return given("--exec") && given("--yes") && !given("--sha256") && !given("--sums");
3502
+ }
3293
3503
  function destructiveViolation(command) {
3294
3504
  if (runsDownload(command))
3295
3505
  return PIPE_TO_SHELL;
3296
3506
  for (const piece of splitCommand(command)) {
3297
3507
  const { program, args } = parseCommand(piece.command);
3508
+ if (program === "dl" && runsUnpinned(args))
3509
+ return UNPINNED_EXEC;
3298
3510
  if (program === "rm" && removesBroadly(args))
3299
3511
  return BROAD_RM;
3512
+ if (program === "rm" && recursiveTargets(args).some(isProtectedPath))
3513
+ return PROTECTED_RM;
3514
+ if (program === "find" && deletesFromHome(args))
3515
+ return FIND_DELETE_HOME;
3516
+ if (program === "docker" && dockerPrunesAll(args))
3517
+ return DOCKER_PRUNE_ALL;
3300
3518
  const git = gitCommandOf(program, args);
3301
3519
  if (git === undefined)
3302
3520
  continue;
@@ -3307,6 +3525,83 @@ function destructiveViolation(command) {
3307
3525
  return null;
3308
3526
  }
3309
3527
 
3528
+ // src/embedded.ts
3529
+ var PRINTERS3 = new Set(["echo", "printf"]);
3530
+ var ECHO_FLAGS = /^-[neE]+$/;
3531
+ var SHELL_STRING_FLAG = /^-[ABD-Z]*C[A-Z]*$/i;
3532
+ var PRINTF_SPEC = /%[sb]/g;
3533
+ var ESCAPE2 = /\\(.)/gs;
3534
+ var VERSION_SUFFIX2 = /[\d.]+$/;
3535
+ var CODE_FLAGS = new Map([["python", ["-c"]], ["perl", ["-e", "-E"]], ["ruby", ["-e"]], ["node", ["-e", "--eval", "-p", "--print"]], ["bun", ["-e", "--eval", "-p", "--print"]]]);
3536
+ var BACKTICK = String.fromCharCode(96);
3537
+ var QUOTED = String.raw`'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|${BACKTICK}(?:[^${BACKTICK}\\]|\\.)*${BACKTICK}`;
3538
+ var ARGV = new RegExp(String.raw`[[(]\s*((?:(?:${QUOTED})\s*,\s*)+(?:${QUOTED}))\s*(?:,\s*)?[\])]`, "gs");
3539
+ var LITERAL = new RegExp(QUOTED, "gs");
3540
+ var RUNS_SHELL = /(?:\b(?:system|exec\w*|spawn\w*|popen|run|call|check_\w+|Popen|getoutput|qx)|\$)\s*(?:\(\s*)?$/;
3541
+ var SHELL_BACKTICKS = new Set(["perl", "ruby"]);
3542
+ var ESCAPED = new Map([["n", `
3543
+ `], ["t", " "]]);
3544
+ function decode(text) {
3545
+ return text.replaceAll(ESCAPE2, (_, char) => ESCAPED.get(char) ?? char);
3546
+ }
3547
+ function literalValue(literal) {
3548
+ return decode(literal.slice(1, -1));
3549
+ }
3550
+ function printfText(args) {
3551
+ const [format = "", ...values] = args;
3552
+ const specs = format.match(PRINTF_SPEC)?.length ?? 0;
3553
+ if (specs === 0)
3554
+ return decode(format);
3555
+ let text = "";
3556
+ for (let rest = values;; rest = rest.slice(specs)) {
3557
+ let index = 0;
3558
+ text += format.replaceAll(PRINTF_SPEC, () => rest[index++] ?? "");
3559
+ if (rest.length <= specs)
3560
+ return decode(text);
3561
+ }
3562
+ }
3563
+ function printed(command) {
3564
+ const { program, args } = parseCommand(command);
3565
+ if (!PRINTERS3.has(program))
3566
+ return null;
3567
+ if (program === "printf")
3568
+ return printfText(args[0] === "--" ? args.slice(1) : args);
3569
+ return args.filter((arg, index) => !(ECHO_FLAGS.test(arg) && args.slice(0, index).every((before) => ECHO_FLAGS.test(before)))).join(" ");
3570
+ }
3571
+ function readsStdin(args) {
3572
+ if (args.some((arg) => SHELL_STRING_FLAG.test(arg)))
3573
+ return false;
3574
+ return args.includes("-s") || args.includes("-") || args.every((arg) => arg.startsWith("-"));
3575
+ }
3576
+ function fedCommands(command) {
3577
+ const pieces = splitCommand(command);
3578
+ return pieces.flatMap((piece, index) => {
3579
+ const before = pieces[index - 1];
3580
+ const { program, args } = parseCommand(piece.command);
3581
+ if (!SHELLS.has(program) || before?.separator !== "|" || !readsStdin(args))
3582
+ return [];
3583
+ const text = printed(before.command);
3584
+ return text === null ? [] : text.split(`
3585
+ `).filter((line) => line.trim() !== "");
3586
+ });
3587
+ }
3588
+ function scriptedCommands(command) {
3589
+ return splitCommand(command).flatMap((piece) => {
3590
+ const { program, args } = parseCommand(piece.command);
3591
+ const language = program.replace(VERSION_SUFFIX2, "");
3592
+ const flags = CODE_FLAGS.get(language);
3593
+ const flag = flags === undefined ? -1 : args.findIndex((arg) => flags.includes(arg));
3594
+ const code = flag === -1 ? undefined : args[flag + 1];
3595
+ if (code === undefined)
3596
+ return [];
3597
+ const argvs = [...code.matchAll(ARGV)].map(([, list = ""]) => (list.match(LITERAL) ?? []).map(literalValue).join(" "));
3598
+ const runs = [...code.matchAll(LITERAL)].filter(({ 0: literal, index }) => RUNS_SHELL.test(code.slice(0, index)) || literal.startsWith("`") && SHELL_BACKTICKS.has(language));
3599
+ const lines = runs.flatMap(([literal]) => literalValue(literal).split(`
3600
+ `));
3601
+ return [...argvs, ...lines].filter((line) => line.trim() !== "");
3602
+ });
3603
+ }
3604
+
3310
3605
  // src/remote.ts
3311
3606
  var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
3312
3607
  var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
@@ -3408,7 +3703,7 @@ var PYTHON_COUNT = /^\s*,\s*(\d+)\s*\)/;
3408
3703
  var SPACE2 = /^\s*/;
3409
3704
  var COMMA = /^\s*,\s*/;
3410
3705
  var REGEX_FLAGS = /^[gm]*$/;
3411
- var PLAIN_WORD2 = /^[\w@%+=:,./*?-]+$/;
3706
+ var PLAIN_WORD3 = /^[\w@%+=:,./*?-]+$/;
3412
3707
  var SED_SEPARATORS = /^[\s;]*/;
3413
3708
  var SED_SEPARATOR = /[\s;]/;
3414
3709
  var BRE_ESCAPED = new Map([["(", "("], [")", ")"], ["{", "{"], ["}", "}"], ["+", "+"], ["?", "?"], ["|", "|"]]);
@@ -3671,7 +3966,7 @@ function sedPairs(script, isExtended) {
3671
3966
  return pairs.length === 0 ? undefined : pairs;
3672
3967
  }
3673
3968
  function fileWord(path) {
3674
- return PLAIN_WORD2.test(path) ? path : shellQuote(path);
3969
+ return PLAIN_WORD3.test(path) ? path : shellQuote(path);
3675
3970
  }
3676
3971
  function flagsOf(pair) {
3677
3972
  return [pair.regex === true ? " --regex" : "", pair.all === true ? " --all" : "", pair.count === undefined ? "" : ` -n ${pair.count}`].join("");
@@ -3794,7 +4089,9 @@ async function checkCommand(command, context) {
3794
4089
  if (message !== null)
3795
4090
  violations.push({ rule, message });
3796
4091
  };
3797
- const run = commandsRun(command);
4092
+ const shown = commandsRun(command);
4093
+ const run = [...shown, ...shown.flatMap(fedCommands).flatMap((each) => commandsRun(each))];
4094
+ const scripted = run.flatMap(scriptedCommands).flatMap((each) => commandsRun(each));
3798
4095
  const first = (messages) => messages.find((message) => message !== null) ?? null;
3799
4096
  const guarded = async (rule, check) => {
3800
4097
  try {
@@ -3806,8 +4103,8 @@ async function checkCommand(command, context) {
3806
4103
  };
3807
4104
  const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
3808
4105
  add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
3809
- add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
3810
- add("destructive", await guarded("destructive", () => first(run.map(destructiveViolation))));
4106
+ add("git", await guarded("git", () => first([...run, ...scripted].map((each) => gitViolation(each, context.isPushAsked)))));
4107
+ add("destructive", await guarded("destructive", () => first([...run, ...scripted].map(destructiveViolation))));
3811
4108
  const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
3812
4109
  add("commit", commit === null ? null : `${commit} ${USE_GC}`);
3813
4110
  add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
@@ -3854,6 +4151,11 @@ var BINS = {
3854
4151
  gc: "`gc <title> [-m <line>]... [--ticket <line>]... -- <path>...`: commits exactly those paths, refusing with nothing staged when the message breaks a commit rule, a path has no change or other files are already staged; use it instead of chaining git add, status and commit.",
3855
4152
  gp: "`gp [--repos] [dir]...`: pushes the current branch when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
3856
4153
  gb: "`gb [branch]`: switches to a branch, a remote one getting its tracking branch, `gb -c <name>` creating one; without a terminal it lists the branches (`--json`), with how each stands against its upstream and whether it is merged.",
4154
+ gf: "`gf [--repos] [dir]...`: fetches with prune and fast-forwards the branch onto its upstream, saying what came in; a diverged branch or a tree the fast-forward would overwrite is refused untouched, `--no-pull` fetches only; use it instead of `git pull` and a git fetch per nested repository.",
4155
+ gm: "`gm [branch]`: merges the branch into the current one, saying fast-forward or merge commit, the commits and the files that came in; a conflict lists every conflicted file with its conflict regions and exits 1, `--dry-run` tries the merge without touching the tree, `--continue`/`--abort`, `--squash`; with no branch it picks one, or lists each with its verdict off a terminal; use it instead of git merge then git diff and reading conflict markers.",
4156
+ gcl: "`gcl <repo> [dir]`: clones a URL, scp address or owner/name into the workspace folder and prints the path, an existing clone being fetched instead; use it instead of git clone with the folder typed out.",
4157
+ gd: "`gd [path]...`: the tracked changes per file with added and removed lines, staged apart from unstaged, the patch of the paths given, `--staged`, `--ref <rev>`; use it instead of `git diff --stat` then `git diff <path>`.",
4158
+ gu: "`gu <path>...`: discards the unstaged changes of the paths after saving them as a patch, `--staged` unstages, `--commit` undoes the last unpushed commit keeping its changes staged; use it instead of git restore and git reset.",
3857
4159
  waitfor: "`waitfor --file <log> --until <regex> [--fail <regex>]`, `--port <n>`, `--url <url>`, `--pid <n>` (`-t 5m`): waits until the line shows, the port listens, the URL answers 2xx or the process exits, exits 1 on a --fail line with the lines around it, 2 on a timeout with the last lines; `waitfor task <id>` waits for a background Bash task and prints its exit code, last lines and failure lines; use it instead of sleep and tail, `until ! pgrep -f` or polling loops.",
3858
4160
  slot: "`slot [-l <lock>] -- <cmd>`: waits for one of the machine-wide slots shared by every session (half the CPUs), then runs the command; `--lock <name>` also holds a named lock for what must not run twice (a shared test database), `slot ls` lists holders and waiters; run heavy jobs (phpunit, playwright, vue-tsc, a full test suite) through it instead of a flock wrapper.",
3859
4161
  gl: "`gl ci [ref]` waits for the GitLab pipeline covering a commit and prints each failed job's tests (exit 0/1/2), `gl runs`, `gl logs <pipeline> [-j job] [--full]`; use it instead of `glab ci` or `glab api .../pipelines/<id>/jobs` polled in a sleep loop.",
@@ -3862,6 +4164,7 @@ var BINS = {
3862
4164
  doctor: "`doctor`: checks this host's @kaynooo/cli-* install, one line per check with its fix: each bin's version against the registry, tea's login, the Claude Code hooks, the Bun floor (`--json`); run it when a bin lacks a command or a flag its docs name.",
3863
4165
  cli: "`cli list`: every @kaynooo/cli-* bin in one line, what it does and what it is reached for instead of, read from each bin's own --help (`--json` adds the synopsis and examples); run it to find the bin that fits a task.",
3864
4166
  hotspots: "`hotspots [dir] [--since <date>] [-n 20]`: ranks the source files by complexity times git churn (commits touching each in the window, 6 months by default), tests and generated files left out, `--json`; use it to pick which complex files are worth splitting first.",
4167
+ dl: "`dl <url>`: downloads into a new folder and prints the path, size, final URL and sha256, with the diff of a text file since its last download; `--sha256 <hex>` or `--sums <url>` checks it, `-x` extracts, `--bin [name]` installs into ~/.local/bin, `--exec --sha256 <sha>` runs a script exactly as read, `dl ls` lists what it installed or ran; use it instead of `curl | sh`, `curl -LO` and `sha256sum -c`.",
3865
4168
  out: "`out -- <cmd>`: folds long output, keeping the errors and saving the full log; run noisy builds, installs, tests and linters through it.",
3866
4169
  changelog: "`changelog --dry`: the release notes since the last tag, grouped from the conventional commits, without publishing them; `changelog` publishes them as the Forgejo release of the tag at HEAD, `changelog undo [tag]` takes a release back."
3867
4170
  };
@@ -3968,7 +4271,7 @@ async function hook(event, input, machine) {
3968
4271
  var LISTED = [
3969
4272
  { name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
3970
4273
  { name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
3971
- { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked" },
4274
+ { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell, dl --exec --yes on an unpinned script", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked, `dl <url>` then `dl <url> --exec --sha256 <sha>`" },
3972
4275
  { name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
3973
4276
  { name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
3974
4277
  { name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
@@ -3983,9 +4286,8 @@ var checkUsage = `guard check [options] [<command> | -]
3983
4286
 
3984
4287
  Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), destructive commands (reset --hard, force push, rebase, broad rm), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3985
4288
  Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
3986
- The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.
3987
-
3988
- Exits 0 when the command is clean, 1 when a rule is broken, 2 on a usage error.`;
4289
+ The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.`;
4290
+ var CHECK_EXITS = [[0, "the command is clean"], [1, "a rule is broken"], [2, "a usage error"]];
3989
4291
  var checkOptions = {
3990
4292
  json: jsonOption("{violations, command, notes, packages} for a hook"),
3991
4293
  cwd: { type: "string", description: "the directory the command runs in (default: here)" },
@@ -3994,9 +4296,8 @@ var checkOptions = {
3994
4296
  };
3995
4297
  var pathUsage = `guard path [--json] <path>...
3996
4298
 
3997
- Checks the paths a file tool would read, edit or write: env files are refused.
3998
-
3999
- Exits 0 when every path is clean, 1 when one is refused, 2 on a usage error.`;
4299
+ Checks the paths a file tool would read, edit or write: env files are refused.`;
4300
+ var PATH_EXITS = [[0, "every path is clean"], [1, "one is refused"], [2, "a usage error"]];
4000
4301
  var pathOptions = {
4001
4302
  json: jsonOption("{violations} for a hook")
4002
4303
  };
@@ -4004,9 +4305,8 @@ var hookUsage = `guard hook <${EVENTS.join("|")}>
4004
4305
 
4005
4306
  Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
4006
4307
  pre-tool-use refuses a Bash call breaking a rule, an install pkg refuses (or fails to check), and a file tool (Read, Edit, MultiEdit, Write, NotebookEdit, Grep, Glob) reaching an env file; user-prompt-submit remembers whether the prompt asked for a push; session-start lists the installed @kaynooo/cli-* bins.
4007
- A failure exits 1, which Claude Code reports without blocking the call.
4008
-
4009
- Exits 0 when it answered, 1 on a failure or an unknown event (never 2, which would block the call).`;
4308
+ A failure exits 1, which Claude Code reports without blocking the call.`;
4309
+ var HOOK_EXITS = [[0, "it answered"], [1, "a failure or an unknown event (never 2, which would block the call)"]];
4010
4310
  var MAX_READ = 1e6;
4011
4311
  function readText(path) {
4012
4312
  try {
@@ -4018,10 +4318,10 @@ function readText(path) {
4018
4318
  }
4019
4319
  function report2(violations) {
4020
4320
  for (const { rule, message } of violations)
4021
- console.log(`${role("problem", process16.stdout)(rule)}: ${message}`);
4321
+ console.log(`${role("problem", process17.stdout)(rule)}: ${message}`);
4022
4322
  }
4023
4323
  async function check(args) {
4024
- const parsed = parse(args, checkUsage, checkOptions);
4324
+ const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
4025
4325
  const { values, positionals } = parsed;
4026
4326
  if (positionals.length > 1)
4027
4327
  fail(`give the command as one argument, quoted
@@ -4030,7 +4330,7 @@ ${checkUsage}`);
4030
4330
  const given = positionals[0] ?? "-";
4031
4331
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
4032
4332
  const context = {
4033
- cwd: values.cwd ?? process16.cwd(),
4333
+ cwd: values.cwd ?? process17.cwd(),
4034
4334
  home: homedir4(),
4035
4335
  isPushAsked: values["push-asked"] === true,
4036
4336
  canRewrite: true,
@@ -4045,12 +4345,12 @@ ${checkUsage}`);
4045
4345
  else
4046
4346
  report2(verdict.violations);
4047
4347
  if (values.json !== true && verdict.command !== command)
4048
- console.log(`${role("label", process16.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4348
+ console.log(`${role("label", process17.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4049
4349
  ${note}`).join("")}`);
4050
4350
  return verdict.violations.length > 0 ? 1 : 0;
4051
4351
  }
4052
4352
  function path(args) {
4053
- const parsed = parse(args, pathUsage, pathOptions);
4353
+ const parsed = parse(args, pathUsage, pathOptions, { exits: PATH_EXITS });
4054
4354
  if (parsed.positionals.length === 0)
4055
4355
  fail(`give at least one path
4056
4356
 
@@ -4064,20 +4364,19 @@ ${pathUsage}`);
4064
4364
  }
4065
4365
  var rulesUsage = `guard rules [--json]
4066
4366
 
4067
- Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs.
4068
-
4069
- Exits 0 once it listed them.`;
4367
+ Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs.`;
4368
+ var RULES_EXITS = [[0, "it listed them"]];
4070
4369
  var rulesOptions = {
4071
4370
  json: jsonOption("[{name, refuses, route, runs}]")
4072
4371
  };
4073
4372
  function rules(args) {
4074
- const parsed = parse(args, rulesUsage, rulesOptions);
4373
+ const parsed = parse(args, rulesUsage, rulesOptions, { exits: RULES_EXITS });
4075
4374
  if (parsed.values.json === true) {
4076
4375
  console.log(JSON.stringify(RULES2));
4077
4376
  return 0;
4078
4377
  }
4079
4378
  for (const rule of RULES2)
4080
- console.log(`${role("id", process16.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4379
+ console.log(`${role("id", process17.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4081
4380
  ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
4082
4381
  return 0;
4083
4382
  }
@@ -4105,7 +4404,7 @@ function machine() {
4105
4404
  };
4106
4405
  }
4107
4406
  async function hookCommand(args) {
4108
- const parsed = parse(args, hookUsage, {});
4407
+ const parsed = parse(args, hookUsage, {}, { exits: HOOK_EXITS });
4109
4408
  const event = parsed.positionals[0] ?? "";
4110
4409
  if (!EVENTS.includes(event))
4111
4410
  fail(`unknown event ${event}
@@ -4116,7 +4415,7 @@ ${hookUsage}`, 1);
4116
4415
  console.log(JSON.stringify(reply));
4117
4416
  return 0;
4118
4417
  }
4119
- process16.exitCode = await runCli({
4418
+ process17.exitCode = await runCli({
4120
4419
  name: "guard",
4121
4420
  usage: false,
4122
4421
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.12.0",
4
+ "version": "0.14.0",
5
5
  "description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,12 +36,12 @@
36
36
  "guard": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-db": "0.12.1",
40
- "@kaynooo/cli-edit": "0.10.0",
41
- "@kaynooo/cli-env": "0.13.1",
42
- "@kaynooo/cli-git": "0.15.0",
43
- "@kaynooo/cli-kit": "0.38.2",
44
- "@kaynooo/cli-out": "0.14.3",
45
- "@kaynooo/cli-pkg": "0.14.0"
39
+ "@kaynooo/cli-db": "0.13.0",
40
+ "@kaynooo/cli-edit": "0.11.0",
41
+ "@kaynooo/cli-env": "0.14.0",
42
+ "@kaynooo/cli-git": "0.16.0",
43
+ "@kaynooo/cli-kit": "0.41.0",
44
+ "@kaynooo/cli-out": "0.14.4",
45
+ "@kaynooo/cli-pkg": "0.16.0"
46
46
  }
47
47
  }