@monte3l/groundwork 1.0.4 → 1.1.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 (55) hide show
  1. package/README.md +62 -13
  2. package/dist/harness/rules.js +1 -1
  3. package/dist/main.js +5 -15
  4. package/dist/merge-json.d.ts +3 -1
  5. package/dist/merge-json.js +1 -1
  6. package/package.json +1 -1
  7. package/plugin/skills/customize/SKILL.md +17 -0
  8. package/plugin/skills/customize/step-3-round-1.md +105 -20
  9. package/plugin/src/domain-map.ts +1 -1
  10. package/plugin/src/pack-map.ts +177 -44
  11. package/plugin/src/plugin-map.ts +277 -28
  12. package/templates/core/.claude/hooks/inject-decision-gate.mjs +4 -0
  13. package/templates/core/.claude/rules/agent-dispatch.md +46 -0
  14. package/templates/core/.claude/settings.json +11 -1
  15. package/templates/core/.claude/skills/creating-prs/SKILL.md +1 -0
  16. package/templates/core/.claude/skills/finishing-work/SKILL.md +1 -0
  17. package/templates/core/.claude/skills/harness-guidance/SKILL.md +1 -0
  18. package/templates/core/.claude/skills/starting-work/SKILL.md +20 -0
  19. package/templates/core/.claude/skills/triaging-ci/SKILL.md +1 -0
  20. package/templates/core/.claude/skills/typescript-guidance/SKILL.md +1 -0
  21. package/templates/core/.claude/skills/writing-commits/SKILL.md +1 -0
  22. package/templates/core/CLAUDE.md +44 -60
  23. package/templates/core/bin/check-exports.mjs +3 -1
  24. package/templates/core/bin/lib/harness-rules.mjs +1 -1
  25. package/templates/core/eslint.config.js +2 -0
  26. package/templates/core/vitest.config.ts +4 -3
  27. package/templates/packs/README.md +8 -3
  28. package/templates/packs/{github → claude-github}/files/.github/workflows/claude-pr-review.yml +1 -1
  29. package/templates/packs/{github → claude-github}/files/.github/workflows/claude.yml +1 -1
  30. package/templates/packs/claude-github/pack.json +19 -0
  31. package/templates/packs/frontend/files/.claude/agents/ui-reviewer.md +132 -0
  32. package/templates/packs/frontend/files/.claude/skills/new-component/SKILL.md +72 -0
  33. package/templates/packs/frontend/pack.json +19 -0
  34. package/templates/packs/github/files/.claude/skills/reviewing-dependabot-prs/SKILL.md +4 -0
  35. package/templates/packs/github/files/.claude/skills/triaging-scan-alerts/SKILL.md +3 -0
  36. package/templates/packs/github/files/.claude/skills/watching-pr-checks/SKILL.md +4 -0
  37. package/templates/packs/github/pack.json +3 -3
  38. package/templates/packs/harness-extras/files/.claude/hooks/guard-readonly-bash.mjs +1117 -122
  39. package/templates/packs/harness-extras/pack.json +3 -15
  40. package/templates/packs/licensing/pack.json +31 -0
  41. package/templates/packs/publishing/pack.json +3 -14
  42. package/templates/packs/quality/files/.claude/agents/type-design-analyzer.md +1 -1
  43. package/templates/packs/service/files/.claude/agents/performance-analyzer.md +96 -0
  44. package/templates/packs/service/files/.claude/skills/api-doc/SKILL.md +67 -0
  45. package/templates/packs/service/files/.claude/skills/api-doc/openapi-template.yaml +48 -0
  46. package/templates/packs/service/pack.json +19 -0
  47. package/templates/packs/statusline/pack.json +31 -0
  48. package/templates/packs/supply-chain/pack.json +1 -1
  49. package/templates/packs/worktrees/files/.claude/skills/working-in-worktrees/SKILL.md +20 -5
  50. package/templates/packs/worktrees/pack.json +2 -1
  51. /package/templates/packs/{publishing → licensing}/files/REUSE.toml +0 -0
  52. /package/templates/packs/{publishing → licensing}/files/bin/check-license-headers.mjs +0 -0
  53. /package/templates/packs/{harness-extras → statusline}/files/.claude/hooks/statusline-layout.mjs +0 -0
  54. /package/templates/packs/{harness-extras → statusline}/files/.claude/hooks/statusline.mjs +0 -0
  55. /package/templates/packs/{harness-extras → statusline}/files/.claude/hooks/subagent-statusline.mjs +0 -0
@@ -25,69 +25,88 @@
25
25
  * restriction whenever `agent_type` names a read-only agent is fail-safe --
26
26
  * it only refuses more -- so no `agent_id` check is needed here.
27
27
  *
28
- * Design tradeoff, matching every sibling guard hook's fail-open
29
- * philosophy: this is a DENYLIST of known-mutating patterns, not a strict
30
- * allowlist. A stricter allowlist would be more airtight but would also
31
- * block legitimate read commands this hook's author didn't anticipate (a
32
- * false positive wedges a reviewer's diagnostic work; a false negative
33
- * merely defers to code review, which remains the authoritative backstop).
34
- * Extend MUTATING_PATTERNS as new gaps are found rather than flipping to an
35
- * allowlist.
28
+ * Design: an ALLOWLIST that fails closed. Anything this hook does not
29
+ * recognize, cannot read or cannot finish classifying is BLOCKED. That matters
30
+ * more than usual here: the hook is registered without `onFailure`, so a throw
31
+ * or a timeout would let the command through. The entry point therefore turns
32
+ * any classifier exception into a block, and the classifier caps its own
33
+ * work: a command over MAX_COMMAND_LENGTH characters, or one nesting
34
+ * substitutions, tool wrappers, `-c` shells or `find -exec` commands deeper
35
+ * than MAX_DEPTH, blocks unread. A false positive costs a reviewer one
36
+ * diagnostic command, handed back to the hub; a false negative lets a
37
+ * read-only spoke mutate the repo. The checks:
36
38
  *
37
- * Known, accepted gaps in the prefix-verb/nested-shell handling (deliberate,
38
- * per the tradeoff above -- not oversights): a prefix verb's OWN value-taking
39
- * flag (`sudo -u root rm x`, `env -C /tmp rm x`, `xargs -n 1 rm`) resolves the
40
- * flag's value as the verb, missing the real command. A nested shell's `-c`
41
- * command string (standalone `-c` or a short-option cluster like `-lc`) is
42
- * unwrapped and classified recursively wherever the verb resolves to a shell
43
- * -- behind `sudo`/`env`/`xargs`/`command`, leading `VAR=value` assignments,
44
- * or `npx`/`pnpm exec`/`pnpm dlx`/`npm exec` (whose own shell-mode flags,
45
- * `-c`/`--call`/`--shell-mode`, are unwrapped the same way) -- but only for
46
- * the shells `bash sh zsh dash ksh`; `eval`, `busybox sh` and a shell reached
47
- * through an unrecognized wrapper (`nice`, `nohup`, `timeout`, `xargs -I{}`,
48
- * ...) are not unwrapped unless listed -- `time` is the one such wrapper
49
- * stripped, alongside the leading reserved words `if then else elif do while
50
- * until ! {` and a glued `(`/`{`. Beyond that strip, shell grammar is not
51
- * modelled: a `case ... esac` body (`pat) rm x ;;` resolves `pat)` as the
52
- * verb), a function definition or call (`f() { rm x; }; f`) and an alias run
53
- * whatever they wrap unseen. A wrapper's "tool" word that holds whitespace
54
- * once unquoted (`npx "rm -rf src"`) is judged as a command string. Every word is unquoted
55
- * the way the shell would before it is compared (`"rm"`, `r\m` and `git
56
- * "commit"` match as `rm`/`git commit`); a verb or subcommand word, or a
57
- * nested command string, that uses `$'...'` ANSI-C quoting or whose quote
58
- * never closes blocks rather than being decoded. `find`'s `-exec` check only
59
- * inspects the immediate next token, missing `-execdir`/`-ok` and a chained
60
- * `-exec sh -c '...'`. Interpreters are not inspected either: a file write
61
- * from inside `node -e`, `python -c`, `perl -e`, `ruby -e` or a script they
62
- * run passes, since recognizing it would mean parsing another language.
63
- * `git -c key=value`/`--config-env` is checked against GIT_EXEC_CONFIG_KEY, a
64
- * DENYLIST of the known command-executing config keys (pagers, editors,
65
- * aliases, credential helpers, textconv, ...) -- a command-running key git
66
- * adds later, or one not on that list, passes; `include.path`/
67
- * `includeIf.<cond>.path` and the `GIT_CONFIG*` file-swapping variables block,
68
- * but a config FILE the user already controls (the repo's `.git/config`,
69
- * `~/.gitconfig`) can still set an exec key and is never read. Leading `VAR=value`
70
- * assignments ahead of `git` are likewise checked against GIT_EXEC_ENV, a
71
- * DENYLIST of git's own command-executing environment variables; the
72
- * equivalent variables of other tools (`PAGER`, `EDITOR`, `LESSOPEN`, ...)
73
- * are not inspected at all, nor is a variable exported earlier in the session
74
- * rather than on the command itself. Command substitution is only inspected
75
- * for a redirect inside a double-quoted `"$(...)"`/backtick span; a bare
76
- * `$(...)`/backtick substitution outside double quotes, `<(...)` process
77
- * substitution and here-strings are not recursively classified, so
78
- * `echo $(rm x)` passes. Chain operators (`&&`, `||`, `|`, `&`, `;`, newline)
79
- * inside a quoted string do not split the command; a `bash -c '...'` payload
80
- * therefore stays one segment and is re-split, with the same quote-aware
81
- * rules, when it is classified recursively. The exec-config-key list stays a
82
- * denylist even after its extension to drivers, filters and tool commands.
39
+ * - Reading. Comments are stripped first (a `#` that begins a word, to the end
40
+ * of its line; quotes inside a comment open nothing). Every word is unquoted
41
+ * the way the shell would (`"rm"`, `r\m` and `git "commit"` match as
42
+ * `rm`/`git commit`); any word that cannot be -- `$'...'` ANSI-C quoting, a
43
+ * quote that never closes -- blocks, whatever the verb. Chain operators
44
+ * (`&&`, `||`, `|`, `&`, `;`, newline) inside a quoted string do not split
45
+ * the command. A write redirect to anything but `/dev/null`/`nul` blocks, and
46
+ * so does any `<<`/`<<<` here-document or here-string outside quotes, whose
47
+ * body is not inspected.
48
+ * - Substitutions. `$(...)` and backtick spans (inside double quotes too; a
49
+ * backtick body unescaped as the shell does) and `<(...)` are classified
50
+ * recursively; `>(...)` blocks, and so does one that never closes. A
51
+ * `$(...)` inside single quotes is literal. `$((...))` is arithmetic unless
52
+ * its body reads as a command (two adjacent words, `$((rm x)|(cat))`).
53
+ * - Verbs (READ_ONLY_VERBS). The effective verb of every segment -- after the
54
+ * prefix verbs `sudo env xargs command`, leading `VAR=value` assignments,
55
+ * reserved words and `time` are stripped, and after `npx`/`pnpm exec`/`pnpm
56
+ * dlx`/`npm exec` and `bash sh zsh dash ksh -c '...'` (also behind a
57
+ * wrapper's `-c`/`--call`/`--shell-mode`) are unwrapped -- must be on the
58
+ * list. Anything else blocks: `awk`, `python`, `curl`, `ln`, `rsync`,
59
+ * `eval`, `hostname`, a shell run without `-c`, and a verb built through
60
+ * expansion (`$X`, `r$(echo m)`). MUTATING_VERBS keeps its own reason.
61
+ * - node runs only as `node [SAFE_FLAGS]... <script> [args]` (NODE_SAFE_FLAGS,
62
+ * NODE_SAFE_VALUE_FLAGS); every other option before the script, no script, a
63
+ * program fed through `<`, and a `NODE_OPTIONS` assignment block.
64
+ * `--version`/`-v`/`--help`/`-h` pass only alone.
65
+ * - git (GIT_READ_SUBCOMMANDS). Only reading subcommands pass, plus the
66
+ * read-only forms of `branch tag config worktree stash remote submodule`
67
+ * (READ_ONLY_GIT_FORMS, with `branch`/`tag` judged against flag ALLOWLISTS,
68
+ * GIT_BRANCH_READ_FLAGS and GIT_TAG_READ_FLAGS, because their flags take
69
+ * abbreviations and bundled values no denylist can keep up with); every other
70
+ * subcommand, an unknown or missing one included, blocks. Before a bare
71
+ * `--`, `--output` blocks on every subcommand, as do `grep -O`, `ls-remote
72
+ * -u`/`--upload-pack`/`--exec` and `help -w`/`-i`/`-m`. `git -c`/
73
+ * `--config-env` keys are checked against GIT_EXEC_CONFIG_KEY and leading
74
+ * assignments against GIT_EXEC_ENV, both DENYLISTS of known
75
+ * command-executing keys and variables.
76
+ * - Argument guards on allowlisted verbs that can also write or execute:
77
+ * `sed -i`/`-I`/`--in-place`, `-f`, or a script using `w`/`W`/`e` or the
78
+ * `s///w`/`e` flag (an unreadable script blocks too); `find
79
+ * -delete`/`-fprint*`/`-fls`, and every `-exec`/`-execdir`/`-ok`/`-okdir`
80
+ * command classified with the same allowlist (a `{}` or reserved word as its
81
+ * program blocks); `sort -o`/`--output`/`--compress-program`; a second
82
+ * `uniq` operand; `rg --pre`/`--pre-glob`/`--hostname-bin`; `tree -o`;
83
+ * `eslint --fix`/`-o`/`--output-file`/`--init`; `prettier --write`/`-w`;
84
+ * `knip --fix`; `file -C`; `vitest -u`; `tsc` without `--noEmit` or
85
+ * `-b`/`--build`, and `tsc --init`; `date -s`/`--set`.
83
86
  *
84
- * `git branch` and `git tag` are the exceptions to the denylist design: their
85
- * flag surfaces accept unique-prefix abbreviations (`--unset` for
86
- * `--unset-upstream`), bundled/inline values (`-uorigin/main`) and
87
- * value-taking flags whose separated value can look like a list flag (`git tag
88
- * --format -l v2` creates `v2`), which no denylist of spellings can keep up
89
- * with, so each is judged against an ALLOWLIST of its read-only flags
90
- * (GIT_BRANCH_READ_FLAGS, GIT_TAG_READ_FLAGS) -- anything else blocks.
87
+ * Residuals, deliberate:
88
+ *
89
+ * - A script file's contents: whatever runs through `node <script>`, `pnpm
90
+ * <script>` or `npm run <script>` can do anything its own code does; the
91
+ * hook does not read it. `pnpm`/`npm` keep a DENYLIST of mutating
92
+ * subcommands (MUTATING_SUBCOMMANDS) plus the fixer guards rather than an
93
+ * allowlist, because script names are project-defined.
94
+ * - `tsc -b` and `vitest` write their own build outputs and caches.
95
+ * - A prefix verb's OWN value-taking flag resolves the flag's value as the
96
+ * verb: `sudo -u root rm x`, `env -C /tmp rm x`, `xargs -n 1 rm`, and the
97
+ * natural `xargs -I {} rm -rf {}`, where `{}` reads as a grouping brace.
98
+ * - System-state writes through allowlisted verbs other than the guarded
99
+ * ones (`sudo date 0101...` sets the clock through an operand).
100
+ * - Shell grammar beyond the stripped reserved words is not modelled: a `case
101
+ * ... esac` body, a function definition or call (`f() { cat x; }; f`) and an
102
+ * alias run whatever they wrap, judged only by the words this hook sees.
103
+ * - The exec denylists: a command-running git config key or variable not on
104
+ * GIT_EXEC_CONFIG_KEY/GIT_EXEC_ENV passes; a config FILE the user already
105
+ * controls (`.git/config`, `~/.gitconfig`) can set one and is never read;
106
+ * other tools' variables (`PAGER`, `EDITOR`, `LESSOPEN`, ...) and anything
107
+ * exported earlier in the session are not inspected.
108
+ * - `gh` is not on the list (fail closed); it can be added later with its own
109
+ * read-form table.
91
110
  */
92
111
  import process from "node:process";
93
112
  import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
@@ -389,6 +408,9 @@ function stripPrefixVerbs(input) {
389
408
  /** @type {string[]} */
390
409
  const assignments = [];
391
410
  const words = [...input];
411
+ // The raw texts, read once: assignmentEnd scans them, and rebuilding the
412
+ // array per assignment would make a long run of assignments quadratic.
413
+ const raws = words.map((w) => w.raw);
392
414
  const raw = (k) => words[k].raw;
393
415
  const text = (k) => wordText(words[k]);
394
416
  let i = 0;
@@ -397,10 +419,7 @@ function stripPrefixVerbs(input) {
397
419
  const name = ASSIGNMENT.exec(raw(i))?.[1];
398
420
  if (name !== undefined) {
399
421
  assignments.push(name);
400
- i = assignmentEnd(
401
- words.map((w) => w.raw),
402
- i,
403
- );
422
+ i = assignmentEnd(raws, i);
404
423
  } else if (allowFlags && text(i).startsWith("-")) {
405
424
  i++;
406
425
  } else {
@@ -414,7 +433,10 @@ function stripPrefixVerbs(input) {
414
433
  if (glued !== undefined) {
415
434
  const rest = raw(i).slice(glued.length);
416
435
  if (rest === "") i++;
417
- else words[i] = toWord(rest);
436
+ else {
437
+ words[i] = toWord(rest);
438
+ raws[i] = rest;
439
+ }
418
440
  } else if (LEADING_RESERVED_WORDS.has(text(i))) {
419
441
  const isTime = text(i) === "time";
420
442
  i++;
@@ -462,12 +484,12 @@ function stripClosingParens(list) {
462
484
  if (last === undefined) return list;
463
485
  let end = last.raw;
464
486
  const opens = (end.match(/\(/g) ?? []).length;
465
- while (
466
- end.endsWith(")") &&
467
- !end.endsWith("\\)") &&
468
- (end.match(/\)/g) ?? []).length > opens
469
- ) {
487
+ // Counted once and decremented, not recounted per `)`: a word ending in
488
+ // thousands of `)` must not cost a quadratic scan.
489
+ let closes = (end.match(/\)/g) ?? []).length;
490
+ while (end.endsWith(")") && !end.endsWith("\\)") && closes > opens) {
470
491
  end = end.slice(0, -1);
492
+ closes--;
471
493
  }
472
494
  if (end === last.raw) return list;
473
495
  const head = list.slice(0, -1);
@@ -738,7 +760,7 @@ function isReadOnlyGitTag(args) {
738
760
  // an arbitrary command (a pager, editor, alias with `!`, credential helper,
739
761
  // textconv filter, diff/merge driver, clean/smudge filter, upload-pack
740
762
  // override, difftool/mergetool/browser/man viewer command, ...). A DENYLIST
741
- // of the known ones -- see the module header's accepted gaps. Matched
763
+ // of the known ones -- see the module header's residuals. Matched
742
764
  // case-insensitively, as git's keys are.
743
765
  const GIT_EXEC_CONFIG_KEY = new RegExp(
744
766
  `^(?:${[
@@ -833,8 +855,149 @@ const READ_ONLY_GIT_FORMS = {
833
855
  args.some((a) => GIT_CONFIG_READ.has(a))) &&
834
856
  !args.some((a) => GIT_CONFIG_WRITE.has(a)),
835
857
  tag: isReadOnlyGitTag,
858
+ // `remote` with no arguments or `-v` lists remotes; `show`/`get-url` read
859
+ // one. `add`/`remove`/`set-url`/`prune`/... still block.
860
+ remote: (args) =>
861
+ args.length === 0 ||
862
+ (args.length === 1 && (args[0] === "-v" || args[0] === "--verbose")) ||
863
+ args[0] === "show" ||
864
+ args[0] === "get-url",
865
+ submodule: (args) => args[0] === "status",
836
866
  };
837
867
 
868
+ // The ALLOWLIST of git subcommands that only read, besides the read-only
869
+ // forms of READ_ONLY_GIT_FORMS; every other subcommand -- unknown ones
870
+ // included -- blocks.
871
+ const GIT_READ_SUBCOMMANDS = new Set([
872
+ ...["status", "diff", "log", "show", "blame", "rev-parse", "rev-list"],
873
+ ...["ls-files", "ls-tree", "cat-file", "describe", "shortlog", "grep"],
874
+ ...["for-each-ref", "name-rev", "merge-base", "show-ref", "count-objects"],
875
+ ...["whatchanged", "diff-tree", "diff-index", "diff-files", "cherry"],
876
+ ...["version", "help", "ls-remote"],
877
+ ]);
878
+
879
+ /**
880
+ * Whether `name` (a long option, `=value` stripped) is `full` or an
881
+ * abbreviation of it at least `min` characters long -- git, sed and sort all
882
+ * accept an unambiguous prefix of a long option.
883
+ *
884
+ * @param {string} name
885
+ * @param {string} full
886
+ * @param {number} min
887
+ * @returns {boolean}
888
+ */
889
+ function abbreviates(name, full, min) {
890
+ return name.length >= min && full.startsWith(name);
891
+ }
892
+
893
+ /**
894
+ * Whether one git argument (`name` is its part before any `=`) makes
895
+ * `git <sub>` write a file or run a program. On every subcommand: `--output`
896
+ * or an abbreviation of it from `--outp` on (`--output-indicator-*` is
897
+ * another flag). On `grep`: `-O` in a short cluster (digits included, as in
898
+ * `-5Ovim`) or `--open-files-in-pager`, which run a pager on the matches.
899
+ * On `ls-remote`: `-u`/`--upload-pack` and `--exec`, which run the given
900
+ * program in place of git-upload-pack. On `help`: `-w`/`--web`, `-i`/
901
+ * `--info` and `-m`/`--man`, which start a browser, info or man.
902
+ *
903
+ * @param {string} sub
904
+ * @param {string} arg
905
+ * @param {string} name
906
+ * @returns {boolean}
907
+ */
908
+ function isGitWriteArg(sub, arg, name) {
909
+ if (abbreviates(name, "--output", 6)) return true;
910
+ const isLong = arg.startsWith("--");
911
+ switch (sub) {
912
+ case "grep":
913
+ return isLong
914
+ ? abbreviates(name, "--open-files-in-pager", 4)
915
+ : /^-[A-Za-z0-9]*O/.test(arg);
916
+ case "ls-remote":
917
+ return isLong
918
+ ? abbreviates(name, "--upload-pack", 3) ||
919
+ abbreviates(name, "--exec", 3)
920
+ : /^-[A-Za-z]*u/.test(arg);
921
+ case "help":
922
+ return isLong
923
+ ? ["--web", "--info", "--man"].some((full) =>
924
+ abbreviates(name, full, 4),
925
+ )
926
+ : /^-[A-Za-z]*[wim]/.test(arg);
927
+ default:
928
+ return false;
929
+ }
930
+ }
931
+
932
+ /**
933
+ * The first argument of `git <sub>` that writes a file or runs a program
934
+ * (isGitWriteArg), or undefined. Only the arguments before a bare `--` are
935
+ * flags; after it they are paths (`git diff -- f --output=x` is allowed).
936
+ *
937
+ * @param {string} sub
938
+ * @param {string[]} args
939
+ * @returns {string | undefined}
940
+ */
941
+ function gitWriteFlag(sub, args) {
942
+ const end = args.indexOf("--");
943
+ return (end === -1 ? args : args.slice(0, end)).find((arg) =>
944
+ isGitWriteArg(sub, arg, arg.split("=")[0]),
945
+ );
946
+ }
947
+
948
+ /**
949
+ * The verdict for `git <sub> <args>` once its global flags and environment
950
+ * have been checked: a write flag (gitWriteFlag) blocks first, for every
951
+ * subcommand, before any read-only form can return early; then a read-only
952
+ * form (READ_ONLY_GIT_FORMS) is allowed, a known mutating subcommand keeps
953
+ * its specific reason, an allowlisted read subcommand is allowed, and
954
+ * anything else -- a missing or unknown subcommand included -- blocks.
955
+ *
956
+ * @param {string | undefined} sub
957
+ * @param {string[]} args
958
+ * @returns {{ blocked: true, reason: string } | undefined}
959
+ */
960
+ function classifyGitSubcommand(sub, args) {
961
+ if (sub === undefined) {
962
+ return {
963
+ blocked: true,
964
+ reason: `runs "git" with no subcommand, which is not on the read-only allowlist`,
965
+ };
966
+ }
967
+ const flag = gitWriteFlag(sub, args);
968
+ if (flag !== undefined) {
969
+ return {
970
+ blocked: true,
971
+ reason: `runs "git ${sub} ${flag}", which writes a file or runs a program`,
972
+ };
973
+ }
974
+ if (
975
+ Object.hasOwn(READ_ONLY_GIT_FORMS, sub) &&
976
+ READ_ONLY_GIT_FORMS[sub](args)
977
+ ) {
978
+ return undefined;
979
+ }
980
+ if (MUTATING_SUBCOMMANDS.git.has(sub)) {
981
+ return {
982
+ blocked: true,
983
+ reason: `runs "git ${sub}", a mutating subcommand`,
984
+ };
985
+ }
986
+ if (Object.hasOwn(READ_ONLY_GIT_FORMS, sub)) {
987
+ return {
988
+ blocked: true,
989
+ reason: `runs "git ${sub}" in a form that is not on the read-only allowlist (only its read-only forms are)`,
990
+ };
991
+ }
992
+ if (!GIT_READ_SUBCOMMANDS.has(sub)) {
993
+ return {
994
+ blocked: true,
995
+ reason: `runs "git ${sub}", whose subcommand "${sub}" is not on the read-only allowlist`,
996
+ };
997
+ }
998
+ return undefined;
999
+ }
1000
+
838
1001
  // ESLint's one writing flag: `--fix` (or `--fix=<bool>`). `--fix-dry-run`
839
1002
  // only reports, and `--fix-type` merely narrows what a `--fix` would touch.
840
1003
  const ESLINT_FIX = /^--fix(?:=.*)?$/;
@@ -897,6 +1060,94 @@ const MUTATING_VERBS = new Set([
897
1060
  "tee",
898
1061
  ]);
899
1062
 
1063
+ // The ALLOWLIST of verbs a read-only spoke may run (after prefix verbs and
1064
+ // tool wrappers are unwrapped); every other verb blocks. A verb built through
1065
+ // expansion (`$X`, `r$(echo m)`) keeps its `$`/backtick and so is never on it.
1066
+ const READ_ONLY_VERBS = new Set([
1067
+ // Plain readers.
1068
+ ...["cat", "head", "tail", "wc", "ls", "tree", "stat", "file", "du", "df"],
1069
+ ...["pwd", "echo", "printf", "true", "false", "test", "[", "[["],
1070
+ ...["grep", "egrep", "fgrep", "rg", "cut", "tr", "diff", "cmp", "comm"],
1071
+ ...["basename", "dirname", "realpath", "readlink", "date", "uname"],
1072
+ ...["whoami", "id", "which", "type", "jq", "column", "nl", "fold", "rev"],
1073
+ ...["tac", "paste", "expand", "unexpand", "seq", "expr", "printenv"],
1074
+ // Not `hostname`: given an operand, it sets the host name.
1075
+ // Harmless shell builtins: `cd` only moves the working directory, `read`
1076
+ // only sets a shell variable, `exit` and `:` run nothing.
1077
+ ...["cd", "read", "exit", ":"],
1078
+ // `command -v`/`-V` only: every other `command` is a prefix verb that
1079
+ // stripPrefixVerbs peels off, so `command` is never the verb otherwise.
1080
+ "command",
1081
+ // Guarded readers: allowed only without their write flags.
1082
+ ...["sed", "find", "sort", "uniq"],
1083
+ // Project check tools (the fixer guards still block their write flags).
1084
+ ...["eslint", "prettier", "tsc", "vitest", "knip", "publint", "attw"],
1085
+ // Judged by their own subcommand logic and the wrapper unwrapping.
1086
+ ...["git", "pnpm", "npm", "npx", "pnpx"],
1087
+ // Guarded: only `node [SAFE_FLAGS] <script> [args]` (see nodeHazard).
1088
+ "node",
1089
+ ]);
1090
+
1091
+ // Closing reserved words that end a compound command (`for ...; do ...;
1092
+ // done`, `if ...; fi`, `{ ...; }`): `segments` leaves each as its own
1093
+ // segment, and it runs nothing -- a redirect after it is scanned separately.
1094
+ const CLOSING_RESERVED_WORDS = new Set(["done", "fi", "esac", "}"]);
1095
+
1096
+ // The ALLOWLIST of `node` options that may precede the script: each changes
1097
+ // only diagnostics, limits or the test runner, none runs other code. The
1098
+ // first set takes no value; the second only an inline `=value`.
1099
+ const NODE_SAFE_FLAGS = new Set([
1100
+ "--test",
1101
+ "--check",
1102
+ "-c",
1103
+ "--no-warnings",
1104
+ "--trace-warnings",
1105
+ "--enable-source-maps",
1106
+ "--no-deprecation",
1107
+ "--trace-deprecation",
1108
+ ]);
1109
+ const NODE_SAFE_VALUE_FLAGS = new Set([
1110
+ "--stack-trace-limit",
1111
+ "--max-old-space-size",
1112
+ "--test-reporter",
1113
+ "--test-name-pattern",
1114
+ ]);
1115
+ // Informational options, allowed only as node's sole argument.
1116
+ const NODE_INFO_FLAGS = new Set(["--version", "-v", "--help", "-h"]);
1117
+
1118
+ /**
1119
+ * Why a `node` invocation is not `node [SAFE_FLAGS]... <script> [args]`, or
1120
+ * undefined when it is. The script is the first word not starting with `-`;
1121
+ * every word after it belongs to the script and is never judged as a node
1122
+ * option. Before it, only NODE_SAFE_FLAGS (bare) and NODE_SAFE_VALUE_FLAGS
1123
+ * (with `=value`) may appear. A script word starting with `<` is a redirect
1124
+ * or here-string feeding node its program on stdin; no script at all is a
1125
+ * REPL. `--version`/`-v`/`--help`/`-h` pass only as the sole argument.
1126
+ *
1127
+ * @param {string[]} tokens the command's tokens, `tokens[0]` being `node`
1128
+ * @returns {string | undefined} the reason, phrased to follow "runs"
1129
+ */
1130
+ function nodeHazard(tokens) {
1131
+ const args = tokens.slice(1);
1132
+ if (args.length === 1 && NODE_INFO_FLAGS.has(args[0])) return undefined;
1133
+ for (const arg of args) {
1134
+ if (!arg.startsWith("-")) {
1135
+ return arg.startsWith("<")
1136
+ ? `"node" with its program fed from a redirect ("${arg}")`
1137
+ : undefined;
1138
+ }
1139
+ const eq = arg.indexOf("=");
1140
+ const safe =
1141
+ eq === -1
1142
+ ? NODE_SAFE_FLAGS.has(arg)
1143
+ : NODE_SAFE_VALUE_FLAGS.has(arg.slice(0, eq));
1144
+ if (!safe) {
1145
+ return `"node" with option "${arg}", which is not on the read-only allowlist`;
1146
+ }
1147
+ }
1148
+ return `"node" with no script file (an interactive REPL)`;
1149
+ }
1150
+
900
1151
  // `bash -c '...'`/`sh -c "..."` (optionally through a path like
901
1152
  // `/bin/bash`), capturing the quoted argument's inner content.
902
1153
  const SHELL_DASH_C =
@@ -955,14 +1206,15 @@ function shellCommandIndex(tokens) {
955
1206
  /**
956
1207
  * Classify a nested shell command given as shell words (see `words`), which a
957
1208
  * shell or wrapper `via` runs: each word's unquoted value is joined and the
958
- * result classified recursively with classifyBashCommand. Fails closed --
959
- * blocks -- when there is no word or one cannot be read.
1209
+ * result classified recursively with classifyCommandAt one level deeper.
1210
+ * Fails closed -- blocks -- when there is no word or one cannot be read.
960
1211
  *
961
1212
  * @param {string} via e.g. `bash -c`, `npx -c`
962
1213
  * @param {Word[]} payloadWords
1214
+ * @param {number} depth the nesting depth of the command holding the payload
963
1215
  * @returns {{ blocked: true, reason: string } | undefined}
964
1216
  */
965
- function classifyNestedCommand(via, payloadWords) {
1217
+ function classifyNestedCommand(via, payloadWords, depth) {
966
1218
  const values = payloadWords.map((w) => w.value);
967
1219
  if (values.length === 0 || values.includes(undefined)) {
968
1220
  return {
@@ -970,7 +1222,7 @@ function classifyNestedCommand(via, payloadWords) {
970
1222
  reason: `runs a nested shell command via ${via} whose command string could not be read`,
971
1223
  };
972
1224
  }
973
- const nested = classifyBashCommand(values.join(" "));
1225
+ const nested = classifyCommandAt(values.join(" "), depth + 1);
974
1226
  if (!nested.blocked) return undefined;
975
1227
  return {
976
1228
  blocked: true,
@@ -979,16 +1231,275 @@ function classifyNestedCommand(via, payloadWords) {
979
1231
  }
980
1232
 
981
1233
  /**
982
- * Classify a shell command as blocked (mutating) or allowed for a read-only
983
- * spoke. Denylist-based -- see the module header for the design tradeoff.
1234
+ * The index of the `)` closing the `(` at `open`, or -1 when it never closes.
1235
+ * Quoted spans and backtick spans are skipped whole, so a `)` inside them does
1236
+ * not count; a nested `(` (a nested `$(`, a subshell) deepens the match.
1237
+ *
1238
+ * @param {string} text
1239
+ * @param {number} open
1240
+ * @returns {number}
1241
+ */
1242
+ function closingParen(text, open) {
1243
+ let depth = 0;
1244
+ for (let j = open; j < text.length; j++) {
1245
+ const c = text[j];
1246
+ if (c === "\\") {
1247
+ j++;
1248
+ } else if (c === "'" || c === "`") {
1249
+ j = text.indexOf(c, j + 1);
1250
+ if (j === -1) return -1;
1251
+ } else if (c === '"') {
1252
+ j++;
1253
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
1254
+ if (j >= text.length) return -1;
1255
+ } else if (c === "(") {
1256
+ depth++;
1257
+ } else if (c === ")" && --depth === 0) {
1258
+ return j;
1259
+ }
1260
+ }
1261
+ return -1;
1262
+ }
1263
+
1264
+ /**
1265
+ * The index of the backtick closing the one at `open` (skipping escaped
1266
+ * backticks), or -1 when it never closes.
1267
+ *
1268
+ * @param {string} text
1269
+ * @param {number} open
1270
+ * @returns {number}
1271
+ */
1272
+ function closingBacktick(text, open) {
1273
+ for (let j = open + 1; j < text.length; j++) {
1274
+ if (text[j] === "\\") j++;
1275
+ else if (text[j] === "`") return j;
1276
+ }
1277
+ return -1;
1278
+ }
1279
+
1280
+ // How deep substitutions, tool wrappers, nested `-c` shells and `find -exec`
1281
+ // commands may nest before the command is blocked as unreadable, and the
1282
+ // longest command classified at all. The hook has no `onFailure`, so a stack
1283
+ // overflow or a run past the hook timeout would ALLOW the command: both caps
1284
+ // turn that into a block, and together they bound the work per command.
1285
+ const MAX_DEPTH = 32;
1286
+ const MAX_COMMAND_LENGTH = 65_536;
1287
+ const TOO_DEEP = Object.freeze({
1288
+ blocked: /** @type {const} */ (true),
1289
+ reason: "nests substitutions, wrappers or shells too deeply to read",
1290
+ });
1291
+
1292
+ /**
1293
+ * `command` with every shell comment removed: an unquoted `#` that begins a
1294
+ * word (at the start, or after whitespace or an operator character) up to the
1295
+ * end of its line. Quote characters inside a comment open nothing, so a
1296
+ * comment such as `# don't` cannot swallow the lines after it. Done once, up
1297
+ * front, so the segment splitter and the substitution scanner both read the
1298
+ * command without its comments. Quotes pair as in splitUnquoted.
984
1299
  *
985
1300
  * @param {string} command
986
- * @returns {{ blocked: boolean, reason?: string }}
1301
+ * @returns {string}
987
1302
  */
988
- export function classifyBashCommand(command) {
989
- if (typeof command !== "string" || command.trim().length === 0) {
990
- return { blocked: false };
1303
+ function stripComments(command) {
1304
+ if (!command.includes("#")) return command;
1305
+ let out = "";
1306
+ let start = 0;
1307
+ /** @type {"'" | '"' | "$'" | undefined} */
1308
+ let quote;
1309
+ for (let i = 0; i < command.length; i++) {
1310
+ const c = command[i];
1311
+ if (quote === "'") {
1312
+ if (c === "'") quote = undefined;
1313
+ } else if (c === "\\") {
1314
+ i++;
1315
+ } else if (quote !== undefined) {
1316
+ if (c === quote.at(-1)) quote = undefined;
1317
+ } else if (c === "'" || c === '"') {
1318
+ quote = c;
1319
+ } else if (c === "$" && command[i + 1] === "'") {
1320
+ quote = "$'";
1321
+ i++;
1322
+ } else if (c === "#" && (i === 0 || /[\s;&|()<>]/.test(command[i - 1]))) {
1323
+ const newline = command.indexOf("\n", i);
1324
+ out += command.slice(start, i);
1325
+ if (newline === -1) return out;
1326
+ start = newline;
1327
+ i = newline - 1;
1328
+ }
1329
+ }
1330
+ return out + command.slice(start);
1331
+ }
1332
+
1333
+ // Two identifier-like words separated only by whitespace (`rm x`, `-rf x`):
1334
+ // what a command looks like and arithmetic never does (`a + b`, `1+2`).
1335
+ const COMMAND_LIKE = /(?:^|[^\w$])[A-Za-z_]\w*\s+[A-Za-z_]/;
1336
+
1337
+ /**
1338
+ * Whether a `$((...))` body reads as a command (a subshell inside a command
1339
+ * substitution, `$((rm x)|(cat))`) rather than arithmetic, per COMMAND_LIKE.
1340
+ * Nested `$(...)`/backtick spans are replaced by `0` first, innermost out, so
1341
+ * `$(( $(date +%s) + 1 ))` stays arithmetic; when they nest past MAX_DEPTH
1342
+ * the body is treated as a command (fail closed).
1343
+ *
1344
+ * @param {string} body the text between `$((` and `))`
1345
+ * @returns {boolean}
1346
+ */
1347
+ function isCommandLikeArithmetic(body) {
1348
+ let text = body.replace(/`[^`]*`/g, "0");
1349
+ for (let k = 0; k < MAX_DEPTH && text.includes("$("); k++) {
1350
+ text = text.replace(/\$\([^()]*\)/g, "0");
991
1351
  }
1352
+ return text.includes("$(") || COMMAND_LIKE.test(text);
1353
+ }
1354
+
1355
+ /**
1356
+ * Classify every command and process substitution in `command` that the
1357
+ * shell would run: `$(...)` and backtick spans outside single quotes (inside
1358
+ * double quotes too) and `<(...)` outside any quotes, each body classified
1359
+ * recursively with classifyCommandAt one level deeper. A backtick body is
1360
+ * unescaped first (`` \` `` -> `` ` ``, `\\` -> `\`, `\$` -> `$`), as the
1361
+ * shell does, so an escaped nested backtick is seen. `>(...)` blocks outright
1362
+ * -- its body receives the outer command's output as input to act on -- and
1363
+ * so does a `<<`/`<<<` here-document or here-string, whose body is not
1364
+ * inspected. An arithmetic `$((...))` is not a command, but a substitution
1365
+ * inside it still is; a `$((...))` body that reads as a command
1366
+ * (isCommandLikeArithmetic) is classified as one. Fails closed -- blocks --
1367
+ * on a `$(`, `<(` or backtick that never closes. A `$'...'` span is literal
1368
+ * here; classifyTokens fails closed on it.
1369
+ *
1370
+ * @param {string} command
1371
+ * @param {number} depth
1372
+ * @param {boolean} [arithmetic] scanning an arithmetic expression, where `<<`
1373
+ * is a shift, not a here-document
1374
+ * @returns {{ blocked: true, reason: string } | undefined}
1375
+ */
1376
+ function classifySubstitutions(command, depth, arithmetic = false) {
1377
+ if (depth > MAX_DEPTH) return TOO_DEEP;
1378
+ /** @type {"'" | '"' | "$'" | undefined} */
1379
+ let quote;
1380
+ for (let i = 0; i < command.length; i++) {
1381
+ const c = command[i];
1382
+ const next = command[i + 1];
1383
+ if (quote === "'") {
1384
+ if (c === "'") quote = undefined;
1385
+ continue;
1386
+ }
1387
+ if (c === "\\") {
1388
+ i++;
1389
+ continue;
1390
+ }
1391
+ if (quote === "$'") {
1392
+ if (c === "'") quote = undefined;
1393
+ continue;
1394
+ }
1395
+ if (quote === undefined && !arithmetic && c === "<" && next === "<") {
1396
+ return {
1397
+ blocked: true,
1398
+ reason:
1399
+ "uses a here-document or here-string, whose body is not inspected",
1400
+ };
1401
+ }
1402
+ if (c === '"') {
1403
+ quote = quote === '"' ? undefined : '"';
1404
+ continue;
1405
+ }
1406
+ if (quote === undefined && c === "'") {
1407
+ quote = "'";
1408
+ continue;
1409
+ }
1410
+ if (quote === undefined && c === "$" && next === "'") {
1411
+ quote = "$'";
1412
+ i++;
1413
+ continue;
1414
+ }
1415
+
1416
+ /** @type {{ kind: string, body: string } | undefined} */
1417
+ let found;
1418
+ if (c === "$" && next === "(") {
1419
+ const close = closingParen(command, i + 1);
1420
+ if (close === -1) return unbalancedSubstitution("$(");
1421
+ const body = command.slice(i + 2, close);
1422
+ const expression =
1423
+ body.startsWith("(") && body.endsWith(")")
1424
+ ? body.slice(1, -1)
1425
+ : undefined;
1426
+ if (expression !== undefined && !isCommandLikeArithmetic(expression)) {
1427
+ // `$((...))` arithmetic: scan its expression for substitutions only.
1428
+ const inner = classifySubstitutions(expression, depth + 1, true);
1429
+ if (inner !== undefined) return inner;
1430
+ } else {
1431
+ found = { kind: "command substitution", body };
1432
+ }
1433
+ i = close;
1434
+ } else if (c === "`") {
1435
+ const close = closingBacktick(command, i);
1436
+ if (close === -1) return unbalancedSubstitution("`");
1437
+ found = {
1438
+ kind: "command substitution",
1439
+ body: command.slice(i + 1, close).replace(/\\([`$\\])/g, "$1"),
1440
+ };
1441
+ i = close;
1442
+ } else if (quote === undefined && c === ">" && next === "(") {
1443
+ return {
1444
+ blocked: true,
1445
+ reason: `runs an output process substitution (">(...)"), whose command acts on this command's output`,
1446
+ };
1447
+ } else if (quote === undefined && c === "<" && next === "(") {
1448
+ const close = closingParen(command, i + 1);
1449
+ if (close === -1) return unbalancedSubstitution("<(");
1450
+ found = {
1451
+ kind: "process substitution",
1452
+ body: command.slice(i + 2, close),
1453
+ };
1454
+ i = close;
1455
+ }
1456
+ if (found === undefined) continue;
1457
+ const nested = classifyCommandAt(found.body, depth + 1);
1458
+ if (nested.blocked) {
1459
+ return {
1460
+ blocked: true,
1461
+ reason: `runs a ${found.kind} that ${nested.reason}`,
1462
+ };
1463
+ }
1464
+ }
1465
+ return undefined;
1466
+ }
1467
+
1468
+ /**
1469
+ * The fail-closed verdict for a substitution opened by `opener` that never
1470
+ * closes, so its body cannot be read.
1471
+ *
1472
+ * @param {string} opener
1473
+ * @returns {{ blocked: true, reason: string }}
1474
+ */
1475
+ function unbalancedSubstitution(opener) {
1476
+ return {
1477
+ blocked: true,
1478
+ reason: `opens a substitution ("${opener}") that never closes, so the command it runs could not be read`,
1479
+ };
1480
+ }
1481
+
1482
+ /**
1483
+ * classifyBashCommand at nesting depth `depth` (see MAX_DEPTH): every
1484
+ * recursion -- a substitution body, a nested `-c` shell, a wrapped tool, a
1485
+ * `find -exec` command -- comes back through here or classifyTokens one level
1486
+ * deeper, so the depth cap bounds all of them.
1487
+ *
1488
+ * @param {string} rawCommand
1489
+ * @param {number} depth
1490
+ * @returns {{ blocked: boolean, reason?: string }}
1491
+ */
1492
+ function classifyCommandAt(rawCommand, depth) {
1493
+ if (depth > MAX_DEPTH) return TOO_DEEP;
1494
+ const command = stripComments(rawCommand);
1495
+ if (command.trim().length === 0) return { blocked: false };
1496
+
1497
+ // Substitutions run before the command that holds them, so judge each one
1498
+ // first. Scanned over the whole command rather than per segment: a chain
1499
+ // operator inside `$(a | b)` belongs to the substitution, not the outer
1500
+ // chain, and splitting on it first would cut the substitution in two.
1501
+ const substitution = classifySubstitutions(command, depth);
1502
+ if (substitution !== undefined) return substitution;
992
1503
 
993
1504
  for (const segment of segments(command)) {
994
1505
  if (segment.length === 0) continue;
@@ -998,7 +1509,7 @@ export function classifyBashCommand(command) {
998
1509
  // the outer `bash -c` invocation, which is never itself mutating.
999
1510
  const nestedShell = SHELL_DASH_C.exec(segment);
1000
1511
  if (nestedShell !== null) {
1001
- const nested = classifyBashCommand(nestedShell[2]);
1512
+ const nested = classifyCommandAt(nestedShell[2], depth + 1);
1002
1513
  if (nested.blocked) {
1003
1514
  return {
1004
1515
  blocked: true,
@@ -1060,6 +1571,8 @@ export function classifyBashCommand(command) {
1060
1571
 
1061
1572
  const verdict = classifyTokens(
1062
1573
  stripClosingParens(words(segment).map(toWord)),
1574
+ [],
1575
+ depth,
1063
1576
  );
1064
1577
  if (verdict !== undefined) return verdict;
1065
1578
  }
@@ -1067,6 +1580,29 @@ export function classifyBashCommand(command) {
1067
1580
  return { blocked: false };
1068
1581
  }
1069
1582
 
1583
+ /**
1584
+ * Classify a shell command as blocked or allowed for a read-only spoke.
1585
+ * Allowlist-based and failing closed -- a command too long or nested too
1586
+ * deeply to read blocks -- see the module header for the design.
1587
+ *
1588
+ * @example
1589
+ * ```js
1590
+ * import { classifyBashCommand } from "./guard-readonly-bash.mjs";
1591
+ * classifyBashCommand("git status"); // { blocked: false }
1592
+ * classifyBashCommand("echo $(rm x)").blocked; // true
1593
+ * ```
1594
+ *
1595
+ * @param {string} command
1596
+ * @returns {{ blocked: boolean, reason?: string }}
1597
+ */
1598
+ export function classifyBashCommand(command) {
1599
+ if (typeof command !== "string") return { blocked: false };
1600
+ if (command.length > MAX_COMMAND_LENGTH) {
1601
+ return { blocked: true, reason: "is too long to classify" };
1602
+ }
1603
+ return classifyCommandAt(command, 0);
1604
+ }
1605
+
1070
1606
  /**
1071
1607
  * Where a tool wrapper's own arguments start, or -1 when `verb`/`sub` is not
1072
1608
  * one: `npx`/`pnpx [-p pkg] <tool>`, `pnpm dlx`/`pnpm exec <tool>` and
@@ -1115,6 +1651,437 @@ function wrapperValueFlags(verb) {
1115
1651
  }
1116
1652
  }
1117
1653
 
1654
+ /** @typedef {{ blocked: true, reason: string }} Blocked */
1655
+
1656
+ /**
1657
+ * What in a sed script writes a file or runs a shell command -- the `w`, `W`
1658
+ * or `e` command, or the `w`/`e` flag of `s///` -- or what makes it
1659
+ * unreadable, or undefined when neither. A small parser over sed's command
1660
+ * syntax (addresses, `s`/`y` delimiters, text and label arguments), so a `w`
1661
+ * inside a regex or a replacement (`s/w/x/`) is not mistaken for the
1662
+ * command. A label (`:a`, `b a`, `t a`, `T a`) is its first word only:
1663
+ * GNU and BSD sed disagree about where a label ends, so any text after it is
1664
+ * parsed as more script (`b end w out` is caught). Best effort: an
1665
+ * unterminated address or `s`/`y` is reported unreadable (fail closed), and
1666
+ * a multi-line `a\`/`i\`/`c\` text block may be over-reported.
1667
+ *
1668
+ * @param {string} script
1669
+ * @returns {{ unreadable: boolean, what: string } | undefined}
1670
+ */
1671
+ function sedScriptHazard(script) {
1672
+ const n = script.length;
1673
+ let i = 0;
1674
+ const readDelimited = (/** @type {string} */ d) => {
1675
+ while (i < n) {
1676
+ const c = script[i];
1677
+ i += c === "\\" ? 2 : 1;
1678
+ if (c === d) return true;
1679
+ }
1680
+ return false;
1681
+ };
1682
+ const readAddress = () => {
1683
+ if (script[i] === "/" || script[i] === "\\") {
1684
+ const d = script[i] === "/" ? "/" : script[i + 1];
1685
+ i += script[i] === "/" ? 1 : 2;
1686
+ if (d === undefined || !readDelimited(d)) return false;
1687
+ while (i < n && /[IM]/.test(script[i])) i++;
1688
+ return true;
1689
+ }
1690
+ while (i < n && /[\d$~+]/.test(script[i])) i++;
1691
+ return true;
1692
+ };
1693
+ const skip = (/** @type {RegExp} */ pattern) => {
1694
+ while (i < n && pattern.test(script[i])) i++;
1695
+ };
1696
+ const unterminated = { unreadable: true, what: "an unterminated address" };
1697
+ for (;;) {
1698
+ skip(/[\s;{}!]/);
1699
+ if (i >= n) return undefined;
1700
+ if (script[i] === "#") {
1701
+ skip(/[^\n]/);
1702
+ continue;
1703
+ }
1704
+ if (!readAddress()) return unterminated;
1705
+ skip(/\s/);
1706
+ if (script[i] === ",") {
1707
+ i++;
1708
+ skip(/\s/);
1709
+ if (!readAddress()) return unterminated;
1710
+ }
1711
+ skip(/[\s!]/);
1712
+ if (i >= n) return undefined;
1713
+ const command = script[i++];
1714
+ switch (command) {
1715
+ case "w":
1716
+ case "W":
1717
+ case "e":
1718
+ return { unreadable: false, what: `the "${command}" command` };
1719
+ case "s":
1720
+ case "y": {
1721
+ const d = script[i++];
1722
+ if (d === undefined || !readDelimited(d) || !readDelimited(d)) {
1723
+ return {
1724
+ unreadable: true,
1725
+ what: `an unterminated "${command}" command`,
1726
+ };
1727
+ }
1728
+ const start = i;
1729
+ skip(/[^\s;}#]/);
1730
+ const flag = /[we]/.exec(command === "s" ? script.slice(start, i) : "");
1731
+ if (flag !== null) {
1732
+ return { unreadable: false, what: `the "${flag[0]}" flag of "s"` };
1733
+ }
1734
+ break;
1735
+ }
1736
+ case "a":
1737
+ case "i":
1738
+ case "c":
1739
+ case "r":
1740
+ case "R":
1741
+ skip(/[^\n]/); // text or a file name, up to the end of the line
1742
+ break;
1743
+ case "b":
1744
+ case "t":
1745
+ case "T":
1746
+ case ":":
1747
+ skip(/[ \t]/);
1748
+ skip(/[^;\s]/); // the label's first word; the rest is parsed as script
1749
+ break;
1750
+ default:
1751
+ break; // a command without arguments (`p`, `d`, `n`, `=`, ...)
1752
+ }
1753
+ }
1754
+ }
1755
+
1756
+ /**
1757
+ * The verdict for a `sed` invocation: an in-place edit (a short cluster
1758
+ * holding `i`, or BSD's `I`, or an abbreviation of `--in-place`), a script file (`-f`/
1759
+ * `--file`, whose contents the hook cannot read), or a script -- given with
1760
+ * `-e`/`--expression`, else the first operand -- that writes or executes
1761
+ * (sedScriptHazard) blocks.
1762
+ *
1763
+ * @param {string[]} tokens `tokens[0]` is `sed`
1764
+ * @returns {Blocked | undefined}
1765
+ */
1766
+ function classifySed(tokens) {
1767
+ const inPlace = { blocked: true, reason: `runs "sed -i" (in-place edit)` };
1768
+ const scriptFile = {
1769
+ blocked: true,
1770
+ reason: `runs "sed -f", whose script file cannot be inspected`,
1771
+ };
1772
+ /** @type {string[]} */
1773
+ const scripts = [];
1774
+ /** @type {string[]} */
1775
+ const operands = [];
1776
+ let explicit = false;
1777
+ for (let k = 1; k < tokens.length; k++) {
1778
+ const t = tokens[k];
1779
+ if (t === "--") {
1780
+ operands.push(...tokens.slice(k + 1));
1781
+ break;
1782
+ }
1783
+ if (t.startsWith("--")) {
1784
+ const eq = t.indexOf("=");
1785
+ const name = eq === -1 ? t : t.slice(0, eq);
1786
+ if (abbreviates(name, "--in-place", 3)) return inPlace;
1787
+ if (abbreviates(name, "--file", 4)) return scriptFile;
1788
+ if (abbreviates(name, "--expression", 3)) {
1789
+ explicit = true;
1790
+ scripts.push(eq === -1 ? (tokens[++k] ?? "") : t.slice(eq + 1));
1791
+ } else if (abbreviates(name, "--line-length", 3) && eq === -1) {
1792
+ k++; // its value
1793
+ }
1794
+ } else if (t.startsWith("-") && t.length > 1) {
1795
+ if (/[iI]/.test(t)) return inPlace;
1796
+ for (let j = 1; j < t.length; j++) {
1797
+ if (t[j] === "f") return scriptFile;
1798
+ if (t[j] === "e") {
1799
+ explicit = true;
1800
+ scripts.push(t.slice(j + 1) || (tokens[++k] ?? ""));
1801
+ break;
1802
+ }
1803
+ if (t[j] === "l") {
1804
+ if (j + 1 === t.length) k++; // its value is the next token
1805
+ break;
1806
+ }
1807
+ }
1808
+ } else {
1809
+ operands.push(t);
1810
+ }
1811
+ }
1812
+ // With any -e, every operand is an input file; otherwise the first is the
1813
+ // script.
1814
+ if (!explicit && operands.length > 0) scripts.push(operands[0]);
1815
+ for (const script of scripts) {
1816
+ const hazard = sedScriptHazard(script);
1817
+ if (hazard !== undefined) {
1818
+ return {
1819
+ blocked: true,
1820
+ reason: hazard.unreadable
1821
+ ? `runs a sed script that could not be read (${hazard.what})`
1822
+ : `runs a sed script using ${hazard.what}, which writes a file or runs a command`,
1823
+ };
1824
+ }
1825
+ }
1826
+ return undefined;
1827
+ }
1828
+
1829
+ // `find` actions that write or delete files, and those that run a command
1830
+ // on each match.
1831
+ const FIND_WRITE_ACTIONS = new Set([
1832
+ "-delete",
1833
+ "-fprint",
1834
+ "-fprint0",
1835
+ "-fprintf",
1836
+ "-fls",
1837
+ ]);
1838
+ const FIND_EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1839
+ // Shell reserved words: find runs its exec command through execvp, with no
1840
+ // shell, so none of these means anything there -- and classifyTokens, which
1841
+ // reads shell grammar, would strip or skip them and judge the wrong word.
1842
+ const SHELL_RESERVED_WORDS = new Set([
1843
+ ...["{", "}", "if", "then", "else", "elif", "fi", "do", "done"],
1844
+ ...["while", "until", "for", "case", "esac", "select", "time", "!"],
1845
+ ]);
1846
+
1847
+ /**
1848
+ * The verdict for a `find` invocation: a write action blocks, and each
1849
+ * exec action's command (up to its terminating `;`, or a `+` right after
1850
+ * `{}`) is classified with classifyTokens -- the same allowlist -- blocking
1851
+ * when it blocks, when it is missing, or when no terminator follows.
1852
+ *
1853
+ * @param {Word[]} words
1854
+ * @param {string[]} tokens `tokens[0]` is `find`, index-aligned with `words`
1855
+ * @param {number} depth the nesting depth of the `find` command
1856
+ * @returns {Blocked | undefined}
1857
+ */
1858
+ function classifyFind(words, tokens, depth) {
1859
+ for (let k = 1; k < tokens.length; k++) {
1860
+ const t = tokens[k];
1861
+ if (FIND_WRITE_ACTIONS.has(t)) {
1862
+ return {
1863
+ blocked: true,
1864
+ reason: `runs "find ... ${t}", which writes or deletes files`,
1865
+ };
1866
+ }
1867
+ if (!FIND_EXEC_ACTIONS.has(t)) continue;
1868
+ let end = k + 1;
1869
+ while (
1870
+ end < tokens.length &&
1871
+ tokens[end] !== ";" &&
1872
+ !(tokens[end] === "+" && tokens[end - 1] === "{}")
1873
+ ) {
1874
+ end++;
1875
+ }
1876
+ if (end >= tokens.length || end === k + 1) {
1877
+ return {
1878
+ blocked: true,
1879
+ reason: `runs "find ... ${t}" with no command or no terminating ";" or "+", so what it runs could not be read`,
1880
+ };
1881
+ }
1882
+ // The program find runs is the first word itself: a match (`{}`) or a
1883
+ // reserved word there, even behind a prefix verb, is no command this
1884
+ // guard can judge.
1885
+ const program = parseTokens(words.slice(k + 1, end)).tokens[0] ?? "";
1886
+ for (const first of [tokens[k + 1], program]) {
1887
+ if (first.includes("{}") || SHELL_RESERVED_WORDS.has(first)) {
1888
+ return {
1889
+ blocked: true,
1890
+ reason: `runs "find ... ${t} ${first}", whose program is a matched file or a shell reserved word`,
1891
+ };
1892
+ }
1893
+ }
1894
+ const nested = classifyTokens(words.slice(k + 1, end), [], depth + 1);
1895
+ if (nested !== undefined) {
1896
+ return {
1897
+ blocked: true,
1898
+ reason: `runs "find ... ${t}" whose command ${nested.reason}`,
1899
+ };
1900
+ }
1901
+ k = end;
1902
+ }
1903
+ return undefined;
1904
+ }
1905
+
1906
+ /**
1907
+ * The verdict for a `sort` invocation: an output file (`-o`, a short cluster
1908
+ * holding `o`, an abbreviation of `--output`) or a compressor program
1909
+ * (`--compress-program`, which sort runs) blocks. Arguments after a bare
1910
+ * `--` are files.
1911
+ *
1912
+ * @param {string[]} tokens `tokens[0]` is `sort`
1913
+ * @returns {Blocked | undefined}
1914
+ */
1915
+ function classifySort(tokens) {
1916
+ for (const t of tokens.slice(1)) {
1917
+ if (t === "--") break;
1918
+ const name = t.split("=")[0];
1919
+ const hit = t.startsWith("--")
1920
+ ? abbreviates(name, "--output", 3) ||
1921
+ abbreviates(name, "--compress-program", 4)
1922
+ : t.startsWith("-") && t.includes("o");
1923
+ if (hit) {
1924
+ return {
1925
+ blocked: true,
1926
+ reason: `runs "sort ${t}", which writes a file or runs a program`,
1927
+ };
1928
+ }
1929
+ }
1930
+ return undefined;
1931
+ }
1932
+
1933
+ // `uniq`'s long options that take their value as the following token.
1934
+ const UNIQ_VALUE_OPTIONS = ["--skip-fields", "--skip-chars", "--check-chars"];
1935
+
1936
+ /**
1937
+ * The verdict for a `uniq` invocation: a second operand is the file uniq
1938
+ * writes its output to, so more than one blocks. Option values (`-f N`,
1939
+ * `-s N`, `-w N` and their long forms) are not operands.
1940
+ *
1941
+ * @param {string[]} tokens `tokens[0]` is `uniq`
1942
+ * @returns {Blocked | undefined}
1943
+ */
1944
+ function classifyUniq(tokens) {
1945
+ /** @type {string[]} */
1946
+ const operands = [];
1947
+ for (let k = 1; k < tokens.length; k++) {
1948
+ const t = tokens[k];
1949
+ if (t === "--") {
1950
+ operands.push(...tokens.slice(k + 1));
1951
+ break;
1952
+ }
1953
+ if (t.startsWith("--")) {
1954
+ if (
1955
+ !t.includes("=") &&
1956
+ UNIQ_VALUE_OPTIONS.some((full) => abbreviates(t, full, 4))
1957
+ ) {
1958
+ k++;
1959
+ }
1960
+ } else if (t.startsWith("-") && t.length > 1) {
1961
+ const at = t.search(/[fsw]/);
1962
+ if (at !== -1 && at + 1 === t.length) k++; // value is the next token
1963
+ } else {
1964
+ operands.push(t);
1965
+ }
1966
+ }
1967
+ if (operands.length <= 1) return undefined;
1968
+ return {
1969
+ blocked: true,
1970
+ reason: `runs "uniq" with a second operand ("${operands[1]}"), which is the file it writes`,
1971
+ };
1972
+ }
1973
+
1974
+ /**
1975
+ * The argument guards of the verbs on READ_ONLY_VERBS that also have a
1976
+ * writing form: the guarded readers (`sed`, `find`, `sort`, `uniq`) and the
1977
+ * tools checked by toolWriteReason. Any other verb returns undefined.
1978
+ *
1979
+ * @param {string} verb
1980
+ * @param {Word[]} words
1981
+ * @param {string[]} tokens
1982
+ * @param {number} depth
1983
+ * @returns {Blocked | undefined}
1984
+ */
1985
+ function classifyGuardedReader(verb, words, tokens, depth) {
1986
+ switch (verb) {
1987
+ case "sed":
1988
+ return classifySed(tokens);
1989
+ case "find":
1990
+ return classifyFind(words, tokens, depth);
1991
+ case "sort":
1992
+ return classifySort(tokens);
1993
+ case "uniq":
1994
+ return classifyUniq(tokens);
1995
+ default: {
1996
+ const why = toolWriteReason(verb, tokens);
1997
+ return why === undefined ? undefined : { blocked: true, reason: why };
1998
+ }
1999
+ }
2000
+ }
2001
+
2002
+ /**
2003
+ * Whether `tsc` is given `--noEmit` (not followed by an explicit `false`).
2004
+ * tsc matches option names case-insensitively.
2005
+ *
2006
+ * @param {string[]} lower the lowercased arguments
2007
+ * @returns {boolean}
2008
+ */
2009
+ function tscNoEmit(lower) {
2010
+ const k = lower.findIndex((t) => t === "--noemit" || t === "--noemit=true");
2011
+ return k !== -1 && lower[k + 1] !== "false";
2012
+ }
2013
+
2014
+ /**
2015
+ * The reason an allowlisted tool's flags make it write a file, run another
2016
+ * program or change system state, or undefined. Only the arguments before a
2017
+ * bare `--` are read as flags. `rg --pre`/`--pre-glob`/`--hostname-bin` run
2018
+ * a program; `tree -o`/`--output`, `eslint -o`/`--output-file`/`--init`,
2019
+ * `knip --fix`/`--fix-type`, `file -C`/`--compile` and `vitest -u`/`--update`
2020
+ * write files; `tsc` emits unless given `--noEmit` or `-b`/`--build`, and
2021
+ * `--init` always writes; `date -s`/`--set` sets the clock.
2022
+ *
2023
+ * @param {string} verb
2024
+ * @param {string[]} tokens `tokens[0]` is the verb
2025
+ * @returns {string | undefined} the full reason, starting with "runs"
2026
+ */
2027
+ function toolWriteReason(verb, tokens) {
2028
+ const end = tokens.indexOf("--");
2029
+ const args = tokens.slice(1, end === -1 ? undefined : end);
2030
+ const short = (/** @type {RegExp} */ pattern) =>
2031
+ args.find((t) => /^-[^-]/.test(t) && pattern.test(t));
2032
+ const long = (/** @type {(name: string) => boolean} */ test) =>
2033
+ args.find((t) => t.startsWith("--") && test(t.split("=")[0]));
2034
+ /** @type {string | undefined} */
2035
+ let flag;
2036
+ switch (verb) {
2037
+ case "rg":
2038
+ flag = long((n) => ["--pre", "--pre-glob", "--hostname-bin"].includes(n));
2039
+ break;
2040
+ case "tree":
2041
+ flag = short(/o/) ?? long((n) => abbreviates(n, "--output", 5));
2042
+ break;
2043
+ case "eslint":
2044
+ flag =
2045
+ args.find((t) => t === "-o" || t === "--init") ??
2046
+ long((n) => n === "--output-file");
2047
+ break;
2048
+ case "knip":
2049
+ flag = long((n) => n === "--fix" || n === "--fix-type");
2050
+ break;
2051
+ case "file":
2052
+ flag = short(/C/) ?? long((n) => n === "--compile");
2053
+ break;
2054
+ case "vitest":
2055
+ flag = args.find((t) => t === "-u") ?? long((n) => n === "--update");
2056
+ break;
2057
+ case "date":
2058
+ flag = short(/^-[uRjn]*s/) ?? long((n) => abbreviates(n, "--set", 3));
2059
+ if (flag !== undefined) {
2060
+ return `runs "date ${flag}", which sets the system clock`;
2061
+ }
2062
+ return undefined;
2063
+ case "tsc": {
2064
+ const lower = args.map((t) => t.toLowerCase());
2065
+ if (lower.includes("--init")) {
2066
+ return `runs "tsc --init", which writes a tsconfig.json`;
2067
+ }
2068
+ if (
2069
+ tscNoEmit(lower) ||
2070
+ lower.includes("-b") ||
2071
+ lower.includes("--build")
2072
+ ) {
2073
+ return undefined;
2074
+ }
2075
+ return `runs "tsc" without --noEmit or --build, which emits compiled files`;
2076
+ }
2077
+ default:
2078
+ return undefined;
2079
+ }
2080
+ return flag === undefined
2081
+ ? undefined
2082
+ : `runs "${verb} ${flag}", which writes a file or runs a program`;
2083
+ }
2084
+
1118
2085
  /**
1119
2086
  * The command-level checks for one tokenized segment (everything except the
1120
2087
  * redirect scan, which needs the raw segment text). A tool wrapper (see
@@ -1125,11 +2092,16 @@ function wrapperValueFlags(verb) {
1125
2092
  * unquoted -- `$'...'` ANSI-C quoting or a quote that never closes -- blocks,
1126
2093
  * since the command it names is unknown.
1127
2094
  *
2095
+ * Every recursion it makes -- a wrapped tool, a nested `-c` command, a
2096
+ * guarded reader's `find -exec` -- goes one level deeper (see MAX_DEPTH).
2097
+ *
1128
2098
  * @param {Word[]} rawWords
1129
2099
  * @param {readonly string[]} [inherited]
2100
+ * @param {number} [depth]
1130
2101
  * @returns {{ blocked: true, reason: string } | undefined}
1131
2102
  */
1132
- function classifyTokens(rawWords, inherited = []) {
2103
+ function classifyTokens(rawWords, inherited = [], depth = 0) {
2104
+ if (depth > MAX_DEPTH) return TOO_DEEP;
1133
2105
  const parsed = parseTokens(rawWords);
1134
2106
  const { verb, sub, subIndex, words, tokens } = parsed;
1135
2107
  const assignments = [...inherited, ...parsed.assignments];
@@ -1156,6 +2128,7 @@ function classifyTokens(rawWords, inherited = []) {
1156
2128
  return classifyNestedCommand(
1157
2129
  `${verb} -c`,
1158
2130
  words.slice(commandIndex, commandIndex + 1),
2131
+ depth,
1159
2132
  );
1160
2133
  }
1161
2134
  }
@@ -1163,35 +2136,40 @@ function classifyTokens(rawWords, inherited = []) {
1163
2136
  if (MUTATING_VERBS.has(verb)) {
1164
2137
  return { blocked: true, reason: `runs "${verb}", a mutating command` };
1165
2138
  }
2139
+ if (CLOSING_RESERVED_WORDS.has(verb)) return undefined;
2140
+ if (!READ_ONLY_VERBS.has(verb)) {
2141
+ return {
2142
+ blocked: true,
2143
+ reason: `runs "${verb}", which is not on the read-only allowlist`,
2144
+ };
2145
+ }
1166
2146
 
1167
- if (
1168
- verb === "sed" &&
1169
- tokens.some(
1170
- (t) => t === "-i" || t.startsWith("-i") || t.startsWith("--in-place"),
1171
- )
1172
- ) {
1173
- return { blocked: true, reason: `runs "sed -i" (in-place edit)` };
2147
+ // Fail closed on any argument that cannot be unquoted (`$'-e'`, a quote
2148
+ // that never closes): what the verb receives is unknown, so no flag guard
2149
+ // below could be trusted to have seen it.
2150
+ const opaque = words.find((w) => w.value === undefined);
2151
+ if (opaque !== undefined) {
2152
+ return {
2153
+ blocked: true,
2154
+ reason: `passes an argument (${opaque.raw}) whose quoting could not be read`,
2155
+ };
1174
2156
  }
1175
2157
 
1176
- if (verb === "find") {
1177
- if (tokens.includes("-delete")) {
2158
+ if (verb === "node") {
2159
+ if (assignments.includes("NODE_OPTIONS")) {
1178
2160
  return {
1179
2161
  blocked: true,
1180
- reason: `runs "find ... -delete", which mutates matched files`,
2162
+ reason: `sets NODE_OPTIONS, which makes node load or run other code`,
1181
2163
  };
1182
2164
  }
1183
- const execIndex = tokens.indexOf("-exec");
1184
- if (execIndex !== -1) {
1185
- const execVerb = baseName(tokens[execIndex + 1] ?? "");
1186
- if (MUTATING_VERBS.has(execVerb)) {
1187
- return {
1188
- blocked: true,
1189
- reason: `runs "find ... -exec ${execVerb}", which mutates matched files`,
1190
- };
1191
- }
1192
- }
2165
+ const hazard = nodeHazard(tokens);
2166
+ if (hazard !== undefined)
2167
+ return { blocked: true, reason: `runs ${hazard}` };
1193
2168
  }
1194
2169
 
2170
+ const guarded = classifyGuardedReader(verb, words, tokens, depth);
2171
+ if (guarded !== undefined) return guarded;
2172
+
1195
2173
  const writeFlag = fixerWriteFlag(verb, tokens);
1196
2174
  if (writeFlag !== undefined) {
1197
2175
  return {
@@ -1218,17 +2196,25 @@ function classifyTokens(rawWords, inherited = []) {
1218
2196
  const t = tokens[k];
1219
2197
  if (WRAPPER_SHELL_FLAGS[verb].has(t)) {
1220
2198
  const payloadStart = verb === "pnpm" ? flagsEnd : k + 1;
1221
- return classifyNestedCommand(`${verb} ${t}`, words.slice(payloadStart));
2199
+ return classifyNestedCommand(
2200
+ `${verb} ${t}`,
2201
+ words.slice(payloadStart),
2202
+ depth,
2203
+ );
1222
2204
  }
1223
2205
  if (t.startsWith("--call=") && WRAPPER_SHELL_FLAGS[verb].has("--call")) {
1224
2206
  const inline = t.slice("--call=".length);
1225
- return classifyNestedCommand(`${verb} --call`, [
1226
- {
1227
- raw: inline,
1228
- value: words[k].value === undefined ? undefined : inline,
1229
- },
1230
- ...words.slice(k + 1),
1231
- ]);
2207
+ return classifyNestedCommand(
2208
+ `${verb} --call`,
2209
+ [
2210
+ {
2211
+ raw: inline,
2212
+ value: words[k].value === undefined ? undefined : inline,
2213
+ },
2214
+ ...words.slice(k + 1),
2215
+ ],
2216
+ depth,
2217
+ );
1232
2218
  }
1233
2219
  }
1234
2220
  // pnpm also accepts its shell-mode flag BEFORE the subcommand (`pnpm -c
@@ -1242,13 +2228,14 @@ function classifyTokens(rawWords, inherited = []) {
1242
2228
  return classifyNestedCommand(
1243
2229
  `pnpm ${preFlag} ${sub}`,
1244
2230
  toolIndex === -1 ? [] : words.slice(toolIndex),
2231
+ depth,
1245
2232
  );
1246
2233
  }
1247
2234
  if (toolIndex === -1) return undefined;
1248
2235
  // Fail closed: a "tool" word holding whitespace once unquoted (`npx "rm
1249
2236
  // -rf src"`) is no package name -- judge it as the command string it is.
1250
2237
  if (/\s/.test(words[toolIndex].value ?? "")) {
1251
- return classifyNestedCommand(verb, words.slice(toolIndex));
2238
+ return classifyNestedCommand(verb, words.slice(toolIndex), depth);
1252
2239
  }
1253
2240
  const tool = unpinnedToolName(tokens[toolIndex]);
1254
2241
  return classifyTokens(
@@ -1260,10 +2247,11 @@ function classifyTokens(rawWords, inherited = []) {
1260
2247
  ...words.slice(toolIndex + 1),
1261
2248
  ],
1262
2249
  assignments,
2250
+ depth + 1,
1263
2251
  );
1264
2252
  }
1265
2253
  if (verb === "pnpm" && (sub === "eslint" || sub === "prettier")) {
1266
- return classifyTokens(words.slice(subIndex), assignments);
2254
+ return classifyTokens(words.slice(subIndex), assignments, depth + 1);
1267
2255
  }
1268
2256
 
1269
2257
  if (verb === "git") {
@@ -1283,15 +2271,14 @@ function classifyTokens(rawWords, inherited = []) {
1283
2271
  reason: `overrides git config "${key}", which runs an arbitrary command`,
1284
2272
  };
1285
2273
  }
2274
+ return classifyGitSubcommand(
2275
+ sub,
2276
+ subIndex === -1 ? [] : tokens.slice(subIndex + 1),
2277
+ );
1286
2278
  }
1287
2279
 
1288
2280
  const mutatingSubs = MUTATING_SUBCOMMANDS[verb];
1289
2281
  if (mutatingSubs === undefined || sub === undefined) return undefined;
1290
- const args = tokens.slice(subIndex + 1);
1291
-
1292
- if (verb === "git" && READ_ONLY_GIT_FORMS[sub]?.(args) === true) {
1293
- return undefined;
1294
- }
1295
2282
 
1296
2283
  // `pnpm run <script>`/`npm run <script>`: the script name is what runs, so
1297
2284
  // classify it as the subcommand (`run format` blocks, `run format:check`
@@ -1361,9 +2348,17 @@ if (isEntryPoint()) {
1361
2348
  if (!readOnly.has(agentType)) process.exit(0);
1362
2349
 
1363
2350
  const command = input.tool_input?.command;
1364
- const verdict = classifyBashCommand(
1365
- typeof command === "string" ? command : "",
1366
- );
2351
+ let verdict;
2352
+ try {
2353
+ verdict = classifyBashCommand(typeof command === "string" ? command : "");
2354
+ } catch {
2355
+ // No `onFailure` is set for this hook, so a crash here would ALLOW the
2356
+ // command: a classifier failure blocks instead.
2357
+ verdict = {
2358
+ blocked: true,
2359
+ reason: "could not be classified (the guard failed on it)",
2360
+ };
2361
+ }
1367
2362
  if (!verdict.blocked) process.exit(0);
1368
2363
 
1369
2364
  process.stderr.write(`\