slicekit 0.5.0 → 0.6.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.
@@ -8,15 +8,45 @@
8
8
  // Before the rules below, in every session and on every branch (D-83): (0a) a command it cannot judge:
9
9
  // a git or gh command whose arguments hold a variable or a command substitution; `eval`, a shell's
10
10
  // `-c` (`sh`, `bash`, `zsh`, `pwsh`, `cmd /c`, ...) or an interpreter's inline code (`node -e`,
11
- // `python -c`, `perl -e`, `ruby -e`) that names git or gh; (0b) a change to the host rules from the
12
- // agent's shell: `slicekit init --protect`, or a `gh api` write (a method other than GET, or a field or
13
- // input flag without `-X GET`) to rulesets, rules or branch protection; (0c) a write to a test frozen
14
- // for the active slice (REQ-3.3) by redirection, `tee`, `sed -i`, `cp`, `mv`, `rm`, `unlink` or
15
- // `truncate`; (0d) a command naming a path that matches a pattern of `agents.denyPaths` (REQ-3.13): any
11
+ // `python -c`, `perl -e`, `ruby -e`) that names git or gh; a git command with a word that is a
12
+ // prefix of a long option one of these rules reads and is not that option in full (`--forc`, `--har`,
13
+ // `--f`), since git takes an unambiguous prefix as the option and the guard does not hold every option
14
+ // of git to tell which prefix is one; (0b) a change to the host rules from the
15
+ // agent's shell: `slicekit init --protect`; a `gh api` write (a method other than GET, or a field or
16
+ // input flag without `-X GET`) to rulesets, rules or branch protection, the endpoint given as a path, as
17
+ // a full URL or under a GitHub Enterprise Server host's `api/v3` prefix, the path ending at a `?` or a
18
+ // `#`; a write to an endpoint that holds a `.` or `..` segment, which cannot be judged; a
19
+ // `gh api graphql` call whose query declares a mutation and names branch protection or a ruleset
20
+ // outside a string or a comment, and one whose query is not in the command text (`--input`,
21
+ // `-F query=@file`, no query field) or is not a document the guard reads to its end, which cannot be
22
+ // judged; (0c) a write to
23
+ // a test frozen for the active slice (REQ-3.3): by a redirection (`>`, `>>`, `>|`, `>&`, `&>`, with a
24
+ // file descriptor or without, apart from the preceding word or against it); by `tee`, `sed -i`,
25
+ // `perl -i` and `ruby -i` in their spellings (`-pi`, `-i.bak`, `-p -i`), `gawk -i inplace`, `dd of=`,
26
+ // `truncate`; by `cp`, `mv`, `install`, `rsync` and `ln` with the test as the destination or the
27
+ // link name, or as a name under a destination directory; by `rm`, `unlink` and `mv` of the test or
28
+ // of a directory holding it; by `git checkout`, `git restore`, `git rm` and `git mv` naming the
29
+ // test, a directory holding it or a pathspec that matches it, and by one of those whose paths the
30
+ // text does not name (`--pathspec-from-file`, `--patch`, a `:(...)` pathspec); by a git command that
31
+ // rewrites the work tree and names no path, which reaches every frozen test: `git checkout -f`,
32
+ // `git switch -f` or `--discard-changes`, `git reset --hard`, `git stash` other than `list`, `show`,
33
+ // `drop`, `clear`, `create` and `store`, and `git clean` other than a dry run (`git stash push --`
34
+ // and `git clean` with pathspecs are judged by those); (0d) a command naming a
35
+ // path that matches a pattern of `agents.denyPaths` (REQ-3.13): any
16
36
  // argument, redirection target, option value or `<rev>:<path>` path, resolved against the shell's
17
- // directory, a glob or brace expression by what it expands to, and the directory a pattern starts with
18
- // (`data` for `data/**`); the directory each command runs in and each `cd`/`pushd` target are judged
19
- // too, and while the list is set a `cd` it cannot resolve from the text is refused.
37
+ // directory, a glob or brace expression by what it expands to and as the literal word (a bracket
38
+ // expression as Bash 5 reads it: quoted and escaped members, the backslash among them, `]` first, `!`
39
+ // and `^`, ranges, a range that runs backwards left out, named classes, and a collating symbol or an
40
+ // equivalence class of one character; a word with an expression the guard does not read to its end,
41
+ // such as `[[.hyphen.]]` or an unknown class name, is refused as one it cannot judge), and the
42
+ // directory a pattern starts with
43
+ // (`data` for `data/**`); a path named through a link or junction that leads into the repository is
44
+ // judged where the link leads too; the directory each command runs in and each `cd`/`pushd` target
45
+ // are judged too, a `cd` to a directory that does not exist yet is followed by its name, and while
46
+ // the list is set a `cd` it cannot resolve from the text is refused: a variable, a substitution, `-`,
47
+ // a glob or brace expression, and a `cd` in a pipeline or in the background. A `cd` inside a brace
48
+ // group that is piped on or put in the background ends at the closing brace, whatever redirections
49
+ // follow the brace (`} 2>&1 |`) and whatever word the group follows (`time`, `!`, `coproc`).
20
50
  //
21
51
  // Rules in order, first deny wins: (1) commit on a protected branch; (2) push to a protected branch;
22
52
  // (3) any force push; (4) a commit that changes a frozen intake snapshot; (5) from a subagent: commit,
@@ -31,7 +61,9 @@
31
61
  // Limits: this reads the command as a shell would on its surface. It splits on operators outside
32
62
  // quotes, treats here-document bodies as data, strips shell keywords, env prefixes and wrappers
33
63
  // (command/exec/sudo/env/timeout/nice/xargs/...), follows `cd`, `pushd`, `git -C`, `git checkout` and
34
- // `bash -c "..."`. A directory it cannot resolve makes a commit or push refuse rather than pass.
64
+ // `bash -c "..."`. A directory it cannot resolve makes a commit or push refuse rather than pass, and
65
+ // so does a `cd` in a pipeline or in the background before it, with or without a deny list; the
66
+ // reason names that `cd`.
35
67
  // It does not expand variables, aliases, functions or encoded payloads; where git or gh is named in
36
68
  // what it cannot expand, rule (0a) refuses the command. Deliberate obfuscation still gets through
37
69
  // (`$G push`, a script file that runs git); the host rules are the control.
@@ -40,8 +72,30 @@
40
72
  // is not split out; `echo '...' | bash` (a piped string, not a here-document) and a shell function
41
73
  // (`function f { ...; }; f`) are not followed; the default destructive list misses `rm -fr /`
42
74
  // spellings and absolute paths inside the worktree; SQL read from a file (`psql -f f.sql`,
43
- // `cat f.sql | psql`) is not matched against the destructive list; a frozen test written by a program
44
- // that names it only inside its own code (`node -e "fs.writeFileSync(...)"`) is not seen.
75
+ // `cat f.sql | psql`) is not matched against the destructive list.
76
+ // Known gaps of rule 0b: a host-rule write by a client other than `gh api` (`curl`, a script, an
77
+ // extension or alias of gh); a GraphQL mutation of the host's rules whose name holds neither
78
+ // `BranchProtection` nor `Ruleset`; a path with a percent-encoded character other than `%2e`
79
+ // (`rule%73ets`), which is matched as written.
80
+ // Known gaps of rule 0c, each a write to a frozen test the guard does not see: a program that names
81
+ // the test only inside its own code (`node -e "fs.writeFileSync(...)"`, `python -c`, a script file,
82
+ // an editor run with commands such as `ed`, `ex` or `vim -c`); a command given the name by another
83
+ // (`find ... -delete`, `find -exec`, `ls | xargs rm`); a writer not in the list above (`curl -o`,
84
+ // `wget -O`, `sort -o`, `patch`, `tar -x`, `unzip`, `git apply`, `git reset --merge` or `--keep`,
85
+ // `git checkout <branch>` or `git switch` without `-f` to a revision where the test differs,
86
+ // `git merge`, `git pull`, `git rebase`, `git cherry-pick`, `git revert`, `git am`, and a forced
87
+ // checkout or a stash run through a git alias); a write through a symbolic link the same
88
+ // command makes first (`ln -s test/a.test.js l && echo x > l`; a link that exists when the command is
89
+ // judged is resolved) or through a hard link; `perl -i` switched on by `PERL5OPT` or by the script's
90
+ // `#!` line; a name built from a variable, of which only the last segment is compared.
91
+ // Known gaps of rule 0d: a `cd` inside an `if`, `while`, `until`, `for` or `case` command that is
92
+ // piped or put in the background (`while read f; do cd src; done | cat`) is taken to last, as is
93
+ // one in a shell function's body; `CDPATH` is not read; a link to a listed directory that the
94
+ // same command makes under a name built from a variable is not seen; a glob read under a shell option
95
+ // the command text does not show (`extglob`, `nocaseglob`, `globasciiranges` turned off in a profile)
96
+ // or by a shell that orders a range by the locale (a Bash older than 5); a named class and an
97
+ // equivalence class in a word are read as their ASCII members and every character outside ASCII, so
98
+ // they can refuse a word that names no listed path.
45
99
  import fs from 'node:fs';
46
100
  import os from 'node:os';
47
101
  import path from 'node:path';
@@ -49,7 +103,7 @@ import { compileDestructive } from '../config.js';
49
103
  import { git, GitError, currentBranch } from '../git.js';
50
104
  import { kitPaths } from '../paths.js';
51
105
  import { allow, deny } from './io.js';
52
- import { denyDir, denyPaths, frozenTests, fromGitBash, matchesDeny, real, toPosix } from './paths.js';
106
+ import { BACKSLASH_MEMBER, classSrc, denyDir, denyPaths, frozenTests, fromGitBash, leaves, matchesDeny, namesUnder, real, readBracket, toPosix } from './paths.js';
53
107
 
54
108
  // ---- tokenising ----
55
109
 
@@ -61,13 +115,16 @@ const DELIM_END = /[\s;&|()<>`]/;
61
115
  // word with quotes removed; `b` is only its unquoted characters; `x` is the characters the shell expands
62
116
  // (`v` without single-quoted or backslash-escaped text). Here-document bodies are data, attached to the
63
117
  // command that opened them; `stdin` is the command piped into this one; `subst` marks a command that
64
- // an unquoted backtick substitution interrupts (its output becomes this command's next argument).
118
+ // an unquoted backtick substitution interrupts (its output becomes this command's next argument);
119
+ // `depth` counts the subshell parentheses a command sits in and `tick` says it sits in a backtick
120
+ // substitution; `piped` marks a command whose output is piped on and `background` one ended by `&`;
121
+ // `of` is the command a segment continues, when the `&` of a redirection (`2>&1`, `&>f`) split it off.
65
122
  function lex(command) {
66
123
  const s = String(command);
67
124
  const out = [];
68
125
  // `depth` counts the unquoted subshell parentheses a segment sits in.
69
126
  let depth = 0;
70
- let cur = { toks: [], heredocs: [], depth };
127
+ let cur = { toks: [], heredocs: [], depth, tick: false };
71
128
  let word = null;
72
129
  let bare = '';
73
130
  let expand = '';
@@ -104,7 +161,7 @@ function lex(command) {
104
161
  endWord();
105
162
  const ended = cur;
106
163
  if (cur.toks.length) out.push(cur);
107
- cur = { toks: [], heredocs: [], depth };
164
+ cur = { toks: [], heredocs: [], depth, tick: tickOpen };
108
165
  return ended;
109
166
  };
110
167
  let i = 0;
@@ -182,7 +239,15 @@ function lex(command) {
182
239
  if (!tickOpen) cur.subst = true;
183
240
  tickOpen = !tickOpen;
184
241
  }
242
+ // The `&` of `>&`, `<&` and `&>` is part of a redirection, not the end of the command: the
243
+ // words after it still belong to the command the redirection is on, so that command, `of`,
244
+ // is the one a later `|` pipes on or a later `&` puts in the background (verdict P6-S-52-r2 H-2).
245
+ const redirects = c === '&' && ((word !== null && word === bare && !mask.includes('1') && /^\d*[<>]$/.test(word))
246
+ || (s[i + 1] === '>' && s[i - 1] !== '&'));
185
247
  const ended = endSegment();
248
+ if (redirects) cur.of = ended.of ?? ended;
249
+ // `|&` pipes as `|` does: the command after it reads the one before it.
250
+ if (c === '&' && s[i - 1] === '|' && !ended.toks.length && ended.stdin !== undefined) cur.stdin = ended.stdin;
186
251
  const open = cases.at(-1);
187
252
  if (open?.pattern && (c === '(' || c === ')')) {
188
253
  // A case pattern's parentheses: `a)` and the optional `(a)`; no subshell starts or ends.
@@ -197,7 +262,15 @@ function lex(command) {
197
262
  i += s[i + 2] === '&' ? 2 : 1;
198
263
  }
199
264
  if (c === '|' && s[i + 1] === '|') i += 1;
200
- else if (c === '|') cur.stdin = ended;
265
+ else if (c === '|') {
266
+ cur.stdin = ended;
267
+ ended.piped = true;
268
+ if (ended.of) ended.of.piped = true;
269
+ } else if (c === '&' && s[i + 1] !== '&' && s[i + 1] !== '>' && !'&|<>'.includes(s[i - 1] ?? ' ')) {
270
+ // A lone `&` puts the command in the background; `&&`, `|&`, `&>` and `>&` are not that.
271
+ ended.background = true;
272
+ if (ended.of) ended.of.background = true;
273
+ }
201
274
  i += 1;
202
275
  if (c === '\n' && pending.length) {
203
276
  for (const p of pending) {
@@ -216,6 +289,12 @@ function lex(command) {
216
289
  }
217
290
  } else if (c === '#' && word === null) {
218
291
  while (i < s.length && s[i] !== '\n') i += 1;
292
+ } else if (c === '>' && s[i + 1] === '|') {
293
+ // `>|` is one redirection operator (it overwrites under noclobber), not a redirect and a pipe:
294
+ // `x>|f` is the word `x` and the redirect `>|f`; `1>|f` stays one word.
295
+ if (word !== null && !(word === bare && /^\d*$/.test(word))) endWord();
296
+ add('>|', false);
297
+ i += 2;
219
298
  } else if (c === '>' && word !== null && !(word === bare && /^\d*>?$/.test(word))) {
220
299
  // `x>f` is the word `x` and the redirect `>f`, as the shell reads it; `2>f` and `>>f` stay one word.
221
300
  endWord();
@@ -241,7 +320,7 @@ const base = (word) => path.posix.basename(word.replace(/\\/g, '/')).toLowerCase
241
320
  function dropRedirects(toks) {
242
321
  const out = [];
243
322
  for (let k = 0; k < toks.length; k++) {
244
- const m = /^\d*(<<<|>>?|<|>&|<&|&>)(.*)$/.exec(toks[k].b === toks[k].v ? toks[k].v : '');
323
+ const m = /^\d*(<<<|>\||>>?|<|>&|<&|&>)(.*)$/.exec(toks[k].b === toks[k].v ? toks[k].v : '');
245
324
  if (!m) out.push(toks[k]);
246
325
  else if (m[2] === '') k += 1;
247
326
  }
@@ -306,7 +385,10 @@ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh']);
306
385
  // ---- directories ----
307
386
 
308
387
  // A directory the hook cannot resolve is null: commits and pushes there refuse rather than pass.
309
- function resolveDir(from, target) {
388
+ // With `byName`, a target that does not exist yet is the path its name gives, since the command may
389
+ // create it first (`mkdir x && cd x`, issue #118); git is still not asked about such a directory
390
+ // (`dirExists`), so a commit or push from it refuses as before.
391
+ function resolveDir(from, target, byName = false) {
310
392
  if (/[$`]/.test(target)) return null;
311
393
  let t = target;
312
394
  if (t === '~' || t.startsWith('~/')) t = path.join(os.homedir(), t.slice(1));
@@ -316,11 +398,19 @@ function resolveDir(from, target) {
316
398
  const abs = path.resolve(from ?? '', t);
317
399
  try {
318
400
  return fs.statSync(abs).isDirectory() ? abs : null;
319
- } catch {
320
- return null;
401
+ } catch (e) {
402
+ return byName && e?.code === 'ENOENT' ? abs : null;
321
403
  }
322
404
  }
323
405
 
406
+ const dirExists = (dir) => {
407
+ try {
408
+ return dir !== null && fs.statSync(dir).isDirectory();
409
+ } catch {
410
+ return false;
411
+ }
412
+ };
413
+
324
414
  // ---- git argument parsing ----
325
415
 
326
416
  const GIT_GLOBAL_VALUE = new Set(['-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--super-prefix']);
@@ -429,6 +519,74 @@ function parseStage(op, args) {
429
519
  return { kind: 'stage', op, whole: whole && !paths.length, paths };
430
520
  }
431
521
 
522
+ // The long options this guard reads, per git subcommand: `flags` stand alone, `valued` take a value
523
+ // (the next word, or after `=`), and `short` holds the short options whose value is the next word.
524
+ // A rule that compares an option's name compares it whole, and git accepts any unambiguous prefix of
525
+ // a long option (`--forc`, `--har`), so `cutOption` reads each long option against this list.
526
+ const GIT_LONG = {
527
+ push: {
528
+ flags: ['--force', '--force-with-lease', '--force-if-includes', '--all', '--mirror', '--branches', '--delete'],
529
+ valued: ['--push-option', '--repo', '--receive-pack', '--exec'],
530
+ short: 'o',
531
+ },
532
+ commit: {
533
+ flags: ['--all', '--include'],
534
+ valued: ['--message', '--file', '--reuse-message', '--reedit-message', '--fixup', '--squash', '--author', '--date', '--cleanup',
535
+ '--template', '--trailer', '--pathspec-from-file'],
536
+ short: 'mFcCt',
537
+ },
538
+ add: { flags: ['--all', '--update'], valued: ['--pathspec-from-file'], short: '' },
539
+ rm: { flags: ['--cached'], valued: ['--pathspec-from-file'], short: '' },
540
+ checkout: {
541
+ flags: ['--force', '--patch', '--ours', '--theirs', '--merge', '--track', '--detach'],
542
+ valued: ['--pathspec-from-file', '--orphan', '--conflict', '--unified', '--inter-hunk-context'],
543
+ short: 'bBU',
544
+ },
545
+ switch: {
546
+ flags: ['--force', '--discard-changes', '--track', '--detach', '--merge'],
547
+ valued: ['--create', '--force-create', '--orphan', '--conflict'],
548
+ short: 'cC',
549
+ },
550
+ restore: {
551
+ flags: ['--staged', '--worktree', '--patch', '--ours', '--theirs', '--merge'],
552
+ valued: ['--source', '--pathspec-from-file', '--conflict', '--unified', '--inter-hunk-context'],
553
+ short: 'sU',
554
+ },
555
+ reset: { flags: ['--hard'], valued: [], short: '' },
556
+ clean: { flags: ['--dry-run'], valued: ['--exclude'], short: 'e' },
557
+ tag: { flags: ['--list'], valued: ['--message', '--file', '--local-user'], short: 'mFu' },
558
+ };
559
+ GIT_LONG.stage = GIT_LONG.add;
560
+
561
+ // -> {cut, full} for the first long option of `git <sub>` that is not one of the list in full and is
562
+ // a prefix of one of them (`--forc` of `--force`), or null. Git would read such a word as that option
563
+ // when no other option of the subcommand starts the same way, which this list cannot tell; the guard
564
+ // does not guess, and the caller refuses the command as one it cannot judge (verdict P6-S-52-r2 H-8).
565
+ // A prefix of several options (`--f`) is refused the same way, naming the first: git itself refuses
566
+ // an ambiguous one, so nothing git would run is lost. A word after `--`, and the value of an option
567
+ // that takes one, is not an option.
568
+ function cutOption(sub, args) {
569
+ const spec = Object.hasOwn(GIT_LONG, sub ?? '') ? GIT_LONG[sub] : null;
570
+ if (spec === null) return null;
571
+ const all = [...spec.flags, ...spec.valued];
572
+ for (let k = 0; k < args.length; k++) {
573
+ const a = args[k];
574
+ if (a === '--') return null;
575
+ if (a.startsWith('--')) {
576
+ const name = a.split('=')[0];
577
+ if (all.includes(name)) {
578
+ if (spec.valued.includes(name) && !a.includes('=')) k += 1;
579
+ continue;
580
+ }
581
+ const full = all.find((o) => o.startsWith(name));
582
+ if (full !== undefined) return { cut: name, full };
583
+ } else if (/^-[A-Za-z]+$/.test(a) && spec.short.includes(a.at(-1))) {
584
+ k += 1;
585
+ }
586
+ }
587
+ return null;
588
+ }
589
+
432
590
  // The branch a later commit in the same command will be on, if this changes it. UNKNOWN for `-`.
433
591
  export const UNKNOWN = Symbol('unknown');
434
592
  // `created` is true when the name is certainly the new branch; otherwise the evaluator carries the name
@@ -470,12 +628,14 @@ const GH_API_VALUE = new Set(['-H', '--header', '-q', '--jq', '-t', '--template'
470
628
 
471
629
  // `gh api` from index k: {method, endpoint}. The method is the explicit one, else POST when a field or
472
630
  // input flag is given, else GET.
631
+ // `fields` holds each body flag with its value, `{flag, value}`: `-f query=...`, `--input body.json`.
473
632
  function parseGhApi(w, k) {
474
633
  let method = null;
475
- let body = false;
476
634
  let endpoint = null;
635
+ const fields = [];
477
636
  for (let j = k; j < w.length; j++) {
478
637
  const a = w[j];
638
+ const name = a.startsWith('--') ? a.split('=')[0] : a.slice(0, 2);
479
639
  if (a === '-X' || a === '--method') {
480
640
  if (w[j + 1] !== undefined) method = w[j + 1];
481
641
  j += 1;
@@ -484,22 +644,139 @@ function parseGhApi(w, k) {
484
644
  } else if (/^-X./.test(a)) {
485
645
  method = a.slice(2);
486
646
  } else if (GH_API_BODY.has(a)) {
487
- body = true;
647
+ fields.push({ flag: a, value: w[j + 1] ?? '' });
488
648
  j += 1;
489
- } else if (GH_API_BODY.has(a.startsWith('--') ? a.split('=')[0] : a.slice(0, 2))) {
490
- body = true;
649
+ } else if (GH_API_BODY.has(name)) {
650
+ fields.push({ flag: name, value: a.slice(name.length).replace(/^=/, '') });
491
651
  } else if (GH_API_VALUE.has(a)) {
492
652
  j += 1;
493
653
  } else if (!a.startsWith('-') && endpoint === null) {
494
654
  endpoint = a;
495
655
  }
496
656
  }
497
- return { method: (method ?? (body ? 'POST' : 'GET')).toUpperCase(), endpoint };
657
+ return { method: (method ?? (fields.length ? 'POST' : 'GET')).toUpperCase(), endpoint, fields };
498
658
  }
499
659
 
500
660
  // A repository's (or organisation's) rulesets and rules, or a branch's protection.
501
661
  const HOST_RULES_PATH = /^\/?(?:(?:repos\/[^/]+\/[^/]+|orgs\/[^/]+|enterprises\/[^/]+)\/(?:rulesets|rules)|repos\/[^/]+\/[^/]+\/branches\/.+\/protection)(?:[/?]|$)/;
502
662
 
663
+ // The path of a `gh api` endpoint: a full URL without its scheme and host, a GitHub Enterprise Server
664
+ // path without its `api/v3` prefix, repeated slashes as one. `gh api` takes a URL where it takes a
665
+ // path, so both name the same resource (issue #104). A query string and a fragment are not part of
666
+ // the path the request names, so the path ends at the first `?` or `#` (verdict P6-S-52-r1 H-3).
667
+ function apiPath(endpoint) {
668
+ return endpoint
669
+ .replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*/, '')
670
+ .replace(/[?#].*$/s, '')
671
+ .replace(/\/{2,}/g, '/')
672
+ .replace(/^\/?api\/v3(?=\/|$)/i, '')
673
+ .replace(/^\//, '');
674
+ }
675
+
676
+ // Whether a path holds a `.` or `..` segment, written out or with `%2e`. Whether gh or the host
677
+ // resolves one is not known from the text, so `issues/../rulesets/1` may name a ruleset or not.
678
+ const dotSegment = (p) => p.replace(/%2e/gi, '.').split('/').some((s) => s === '.' || s === '..');
679
+ // The same path with each `.` segment dropped and each `..` segment taking the one before it.
680
+ function withoutDots(p) {
681
+ const out = [];
682
+ for (const s of p.replace(/%2e/gi, '.').split('/')) {
683
+ if (s === '..') out.pop();
684
+ else if (s !== '.') out.push(s);
685
+ }
686
+ return out.join('/');
687
+ }
688
+
689
+ // The GraphQL endpoint: `graphql`, or `api/graphql` on a GitHub Enterprise Server host.
690
+ const GRAPHQL_PATH = /^(?:api\/)?graphql\/?$/i;
691
+ // A GraphQL name that belongs to branch protection or to a ruleset: `deleteBranchProtectionRule`,
692
+ // `updateRepositoryRuleset`, and any later mutation named the same way.
693
+ const RULE_NAME = /[A-Za-z0-9_]*(?:BranchProtection|Ruleset)[A-Za-z0-9_]*/i;
694
+
695
+ // A GraphQL document -> {ops, plain}: the kind of each definition it declares (`query`, `mutation`,
696
+ // `subscription`, `fragment`; a bare selection set is a query) and its text with strings and comments
697
+ // taken out, so a name is read only where it is a name. Null when the text is not a document this
698
+ // reads to its end: a string or a selection set left open, a definition that starts with another
699
+ // word, or no definition (verdict P6-S-52-r1 H-4).
700
+ function graphqlDoc(text) {
701
+ let plain = '';
702
+ for (let i = 0; i < text.length;) {
703
+ if (text.startsWith('"""', i)) {
704
+ let e = text.indexOf('"""', i + 3);
705
+ while (e !== -1 && text[e - 1] === '\\') e = text.indexOf('"""', e + 3);
706
+ if (e === -1) return null;
707
+ plain += ' ';
708
+ i = e + 3;
709
+ } else if (text[i] === '"') {
710
+ let e = i + 1;
711
+ // A line terminator ends a string that is not a block string, closed or not.
712
+ while (e < text.length && text[e] !== '"' && text[e] !== '\n' && text[e] !== '\r') e += text[e] === '\\' ? 2 : 1;
713
+ if (text[e] !== '"') return null;
714
+ plain += ' ';
715
+ i = e + 1;
716
+ } else if (text[i] === '#') {
717
+ // A comment ends at a line terminator, which the GraphQL specification gives as a line feed, a
718
+ // carriage return, or a carriage return and a line feed (verdict P6-S-52-r2 H-7).
719
+ while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += 1;
720
+ } else {
721
+ plain += text[i];
722
+ i += 1;
723
+ }
724
+ }
725
+ const ops = [];
726
+ let k = 0;
727
+ for (;;) {
728
+ while (k < plain.length && /[\s,]/.test(plain[k])) k += 1;
729
+ if (k >= plain.length) break;
730
+ let kind = 'query';
731
+ if (plain[k] !== '{') {
732
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(plain.slice(k));
733
+ if (!word || !['query', 'mutation', 'subscription', 'fragment'].includes(word[0])) return null;
734
+ kind = word[0];
735
+ k += kind.length;
736
+ // The name, the variables and the directives, up to the selection set.
737
+ for (let paren = 0; k < plain.length && !(plain[k] === '{' && paren === 0); k++) {
738
+ if (plain[k] === '(') paren += 1;
739
+ else if (plain[k] === ')') paren -= 1;
740
+ else if (plain[k] === '}' && paren === 0) return null;
741
+ }
742
+ if (k >= plain.length) return null;
743
+ }
744
+ let depth = 0;
745
+ for (; k < plain.length; k++) {
746
+ if (plain[k] === '{') depth += 1;
747
+ else if (plain[k] === '}' && --depth === 0) break;
748
+ }
749
+ if (k >= plain.length) return null;
750
+ k += 1;
751
+ ops.push(kind);
752
+ }
753
+ return ops.length ? { ops, plain } : null;
754
+ }
755
+
756
+ // A `gh api graphql` call (issue #103) -> {change} when its query declares a mutation and names branch
757
+ // protection or a ruleset outside a string or a comment; {unjudged} when the query is not in the
758
+ // command text (`--input`, a typed field read from a file, or no query field) or is not a document
759
+ // `graphqlDoc` reads; null when every query it holds is free of both.
760
+ function graphqlRules(fields) {
761
+ const input = fields.find((f) => f.flag === '--input');
762
+ if (input) return { unjudged: `gh api graphql reads its request from ${input.value || 'its input'}` };
763
+ const queries = fields.filter((f) => /^query=/.test(f.value));
764
+ if (!queries.length) return { unjudged: 'gh api graphql names no query' };
765
+ for (const q of queries) {
766
+ const text = q.value.slice('query='.length);
767
+ // Only a typed field (`-F`, `--field`) reads `@file`; a raw field sends the text as it is.
768
+ if ((q.flag === '-F' || q.flag === '--field') && text.startsWith('@')) {
769
+ return { unjudged: `gh api graphql reads its query from ${text.slice(1) === '-' ? 'standard input' : text.slice(1)}` };
770
+ }
771
+ const doc = graphqlDoc(text);
772
+ if (doc === null) return { unjudged: 'the query of gh api graphql is not a GraphQL document the guard can read to its end' };
773
+ // A document that declares a mutation may run it; the name may stand in a fragment it spreads.
774
+ const name = doc.ops.includes('mutation') ? RULE_NAME.exec(doc.plain) : null;
775
+ if (name) return { change: `gh api graphql mutation ${name[0]}` };
776
+ }
777
+ return null;
778
+ }
779
+
503
780
  // gh's command group and the index after it.
504
781
  function ghGroup(w) {
505
782
  let k = 1;
@@ -519,20 +796,32 @@ function classifyGh(w) {
519
796
  return null;
520
797
  }
521
798
 
522
- // -> a description of a write to the host's rules (REQ-3.14), or null.
799
+ // -> {change}, a description of a write to the host's rules (REQ-3.14); {unjudged}, why a call that
800
+ // may be one cannot be judged; or null.
523
801
  function hostRulesChange(w) {
524
802
  const head = base(w[0]);
525
803
  if (head === 'gh') {
526
804
  const { group, k } = ghGroup(w);
527
805
  if (group !== 'api') return null;
528
- const { method, endpoint } = parseGhApi(w, k);
529
- return method !== 'GET' && endpoint !== null && HOST_RULES_PATH.test(endpoint) ? `gh api ${method} ${endpoint}` : null;
806
+ const { method, endpoint, fields } = parseGhApi(w, k);
807
+ if (endpoint === null) return null;
808
+ const p = apiPath(endpoint);
809
+ // A write, or a call that may be a GraphQL one, to a path with a dot segment is not judged.
810
+ if (dotSegment(p) && (method !== 'GET' || GRAPHQL_PATH.test(withoutDots(p)) || GRAPHQL_PATH.test(p.split('/').pop()))) {
811
+ return {
812
+ unjudged: `the endpoint ${endpoint} holds a . or .. segment`,
813
+ fix: 'write the endpoint without it',
814
+ };
815
+ }
816
+ // A GraphQL call is judged by its query, whatever method it names.
817
+ if (GRAPHQL_PATH.test(p)) return graphqlRules(fields);
818
+ return method !== 'GET' && HOST_RULES_PATH.test(p) ? { change: `gh api ${method} ${endpoint}` } : null;
530
819
  }
531
820
  const i = w.findIndex((x, idx) => idx <= 3 && /^slicekit(\.[cm]?js)?$/.test(base(x)));
532
821
  if (i === -1) return null;
533
822
  const rest = w.slice(i + 1);
534
823
  return rest.includes('init') && rest.some((a) => a === '--protect' || a.startsWith('--protect='))
535
- ? 'slicekit init --protect'
824
+ ? { change: 'slicekit init --protect' }
536
825
  : null;
537
826
  }
538
827
 
@@ -609,28 +898,167 @@ function positionals(args, valued = new Set()) {
609
898
  return out;
610
899
  }
611
900
 
612
- // -> [{word, removes?, into?}]: the paths a simple command writes. `removes` also covers a directory
613
- // holding the file; `into` lists source names for a destination that may be a directory.
614
- function writeTargets(seg, w, head) {
901
+ // Commands that copy or link their leading arguments to the last one, as `cp` does, with the options
902
+ // of each that take a separate value.
903
+ const COPIERS = {
904
+ cp: ['-t', '--target-directory', '-S', '--suffix'],
905
+ mv: ['-t', '--target-directory', '-S', '--suffix'],
906
+ install: ['-t', '--target-directory', '-S', '--suffix', '-m', '--mode', '-o', '--owner', '-g', '--group', '--strip-program'],
907
+ ln: ['-t', '--target-directory', '-S', '--suffix'],
908
+ rsync: ['-e', '--rsh', '-f', '--filter', '-B', '--block-size', '-T', '--temp-dir', '-M', '--remote-option'],
909
+ };
910
+
911
+ // Whether perl or ruby edits its file arguments in place: `-i`, `-i.bak`, `-pi`, `-ni`, in any option
912
+ // before the code or the script. An option letter that takes the rest of its word as a value ends the
913
+ // word (`-Mi` loads module `i`), and `-e` and `-E` take the next word when nothing follows them.
914
+ // -> the file arguments, or null when the command does not edit in place.
915
+ function inPlaceFiles(args) {
916
+ let inPlace = false;
917
+ let k = 0;
918
+ for (; k < args.length; k++) {
919
+ const a = args[k];
920
+ if (a === '--') {
921
+ k += 1;
922
+ break;
923
+ }
924
+ if (!a.startsWith('-') || a === '-') break;
925
+ if (a.startsWith('--')) continue;
926
+ for (let j = 1; j < a.length; j++) {
927
+ const c = a[j];
928
+ if (c === 'i') {
929
+ inPlace = true;
930
+ break;
931
+ }
932
+ if ('eEIr'.includes(c)) {
933
+ if (j === a.length - 1) k += 1;
934
+ break;
935
+ }
936
+ // `-0[digits]` and `-l[digits]` take only digits; more option letters may follow them.
937
+ if (c === '0' || c === 'l') {
938
+ while (/[0-7]/.test(a[j + 1] ?? '') || (c === '0' && /[0-9A-Fa-fx]/.test(a[j + 1] ?? ''))) j += 1;
939
+ continue;
940
+ }
941
+ if ('MmFxCdDV'.includes(c)) break;
942
+ }
943
+ }
944
+ if (!inPlace) return null;
945
+ // Without `-e` the first argument is the script; it is counted too, which can only refuse more.
946
+ return args.slice(k).filter((a) => !a.startsWith('-') || a === '-');
947
+ }
948
+
949
+ // `git checkout`, `git restore`, `git rm` and `git mv` (issue #105) -> the paths the command writes in
950
+ // the work tree, each resolved in the directory `-C` names. A path covers what lies under it, and git
951
+ // matches `*` across directories. A pathspec the text does not settle (`:(glob)...`, `:/`,
952
+ // `--pathspec-from-file`, `--patch`) is `any`: it may reach every file.
953
+ function gitWrites(w, cwd) {
954
+ let dir = cwd;
955
+ let k = 1;
956
+ while (k < w.length && w[k].startsWith('-')) {
957
+ if (w[k] === '-C' && w[k + 1] !== undefined) dir = resolveDir(dir, w[k + 1]);
958
+ k += w[k] === '-C' || GIT_GLOBAL_VALUE.has(w[k]) ? 2 : 1;
959
+ }
960
+ const sub = w[k];
961
+ const args = w.slice(k + 1);
962
+ const has = (...names) => args.some((a) => names.includes(a.split('=')[0]));
963
+ const short = (letter) => args.some((a) => /^-[A-Za-z]+$/.test(a) && a.includes(letter));
964
+ // A `--no-<option>` may take back the option that spares the work tree (`--staged --no-staged`,
965
+ // `--dry-run --no-dry-run`); with one in the command, no option is read as sparing it.
966
+ const negates = args.some((a) => a.startsWith('--no-'));
967
+ // The forms that rewrite the work tree and name no path reach every file (verdict P6-S-52-r1 H-6):
968
+ // a forced checkout or switch throws away each local change, `git reset --hard` does too, `git stash`
969
+ // takes the changes away or puts them back, and `git clean` removes what is not tracked.
970
+ const every = [{ word: `${sub}`, any: true, dir }];
971
+ const specs = (words) => words.map((word) => (word.startsWith(':') ? { word, any: true, dir } : { word, removes: true, pathspec: true, dir }));
972
+ if (sub === 'switch') return has('--force', '--discard-changes') || short('f') ? every : [];
973
+ if (sub === 'reset') return has('--hard') ? every : [];
974
+ if (sub === 'stash') {
975
+ const sep = args.indexOf('--');
976
+ const verb = (sep === -1 ? args : args.slice(0, sep)).find((a) => !a.startsWith('-'));
977
+ if (['list', 'show', 'drop', 'clear', 'create', 'store'].includes(verb)) return [];
978
+ // `git stash [push] -- <pathspec>` takes away only what the pathspec names.
979
+ return (verb === 'push' || verb === undefined) && sep !== -1 && args.length > sep + 1 ? specs(args.slice(sep + 1)) : every;
980
+ }
981
+ if (sub === 'clean') {
982
+ // A dry run removes nothing, with `-f` or without.
983
+ if ((has('--dry-run') || short('n')) && !negates) return [];
984
+ const named = positionals(args, new Set(['-e', '--exclude']));
985
+ return named.length ? specs(named) : every;
986
+ }
987
+ if (sub === 'checkout' && (has('--force') || short('f'))) return every;
988
+ if (!['checkout', 'restore', 'rm', 'mv'].includes(sub)) return [];
989
+ // `git restore --staged` alone writes the index, and `git rm --cached` only that.
990
+ if (sub === 'restore' && (has('--staged') || short('S')) && !negates && !(has('--worktree') || short('W'))) return [];
991
+ if (sub === 'rm' && has('--cached') && !negates) return [];
992
+ const VALUED = {
993
+ checkout: ['-b', '-B', '--orphan', '--conflict', '-U', '--unified', '--inter-hunk-context', '--pathspec-from-file'],
994
+ restore: ['-s', '--source', '--conflict', '-U', '--unified', '--inter-hunk-context', '--pathspec-from-file'],
995
+ rm: ['--pathspec-from-file'],
996
+ mv: [],
997
+ };
998
+ const out = [];
999
+ if (has('--pathspec-from-file') || (sub !== 'mv' && sub !== 'rm' && (has('--patch') || short('p')))) out.push({ word: sub, any: true, dir });
1000
+ const pos = positionals(args, new Set(VALUED[sub]));
1001
+ if (sub === 'mv') {
1002
+ if (pos.length > 1) out.push({ word: pos.at(-1), into: pos.slice(0, -1), dir });
1003
+ for (const word of pos.slice(0, -1)) out.push({ word, removes: true, dir });
1004
+ return out;
1005
+ }
1006
+ for (const word of pos) {
1007
+ if (word.startsWith(':')) out.push({ word, any: true, dir });
1008
+ else out.push({ word, removes: true, pathspec: true, dir });
1009
+ }
1010
+ return out;
1011
+ }
1012
+
1013
+ // What the shell expands a write's word to when a member of a bracket expression in it was quoted or
1014
+ // escaped (`rm test/[a\]].test.js`): {pattern}, the word as `literalMembers` writes it, or {any} when
1015
+ // an expression in it is not read. The word is the end of one of the command's tokens, whose mask
1016
+ // says what was quoted. A git pathspec is not read here: git, not the shell, matches it, as written.
1017
+ function writePattern(toks, wr) {
1018
+ if (wr.any || wr.pathspec || typeof wr.word !== 'string' || !GLOB.test(wr.word)) return {};
1019
+ for (const t of toks) {
1020
+ if (typeof t.m !== 'string' || !t.m.includes('1') || !t.v.endsWith(wr.word)) continue;
1021
+ const [pattern, , unread] = literalMembers(wr.word, t.m.slice(t.v.length - wr.word.length));
1022
+ if (unread) return { any: true };
1023
+ if (pattern !== wr.word) return { pattern };
1024
+ }
1025
+ return {};
1026
+ }
1027
+
1028
+ // -> [{word, removes?, into?, any?, pathspec?, dir?}]: the paths a simple command writes. `removes`
1029
+ // also covers a directory holding the file; `into` lists source names for a destination that may be a
1030
+ // directory; `any` is a write whose paths the text does not name; `pathspec` is a git pathspec; `dir`
1031
+ // is the directory the path is named in when it is not the shell's (`cwd`).
1032
+ function writeTargets(seg, w, head, cwd) {
615
1033
  const out = redirectTargets(seg.toks).map((word) => ({ word }));
616
1034
  const args = w.slice(1);
617
1035
  if (head === 'tee') {
618
1036
  for (const word of positionals(args)) out.push({ word });
619
1037
  } else if (head === 'sed' && args.some((a) => /^-[A-Za-z]*i/.test(a) || a.startsWith('--in-place'))) {
620
1038
  for (const word of positionals(args, new Set(['-e', '-f', '--expression', '--file', '-l', '--line-length']))) out.push({ word });
621
- } else if (head === 'cp' || head === 'mv') {
1039
+ } else if (head === 'perl' || head === 'ruby') {
1040
+ for (const word of inPlaceFiles(args) ?? []) out.push({ word });
1041
+ } else if (/^g?awk$/.test(head) && args.some((a, k) => /^(-i|--include)$/.test(a) ? args[k + 1] === 'inplace' : /^(-i|--include=)inplace$/.test(a))) {
1042
+ for (const word of positionals(args, new Set(['-i', '--include', '-f', '--file', '-v', '--assign', '-F', '--field-separator']))) out.push({ word });
1043
+ } else if (head === 'dd') {
1044
+ for (const a of args) if (a.startsWith('of=')) out.push({ word: a.slice('of='.length) });
1045
+ } else if (COPIERS[head]) {
622
1046
  let target = args.find((a, k) => args[k - 1] === '-t' || args[k - 1] === '--target-directory');
623
1047
  const long = args.find((a) => a.startsWith('--target-directory='));
624
1048
  if (long) target = long.slice('--target-directory='.length);
625
- const pos = positionals(args, new Set(['-t', '--target-directory', '-S', '--suffix']));
626
- const sources = target === undefined ? pos.slice(0, -1) : pos;
627
- const dest = target ?? pos.at(-1);
1049
+ const pos = positionals(args, new Set(COPIERS[head]));
1050
+ // `ln <target>` with one name makes the link in the shell's directory under the target's name.
1051
+ const single = head === 'ln' && target === undefined && pos.length === 1;
1052
+ const sources = target === undefined && !single ? pos.slice(0, -1) : pos;
1053
+ const dest = single ? '.' : target ?? pos.at(-1);
628
1054
  if (dest !== undefined) out.push({ word: dest, into: sources });
629
1055
  if (head === 'mv') for (const word of sources) out.push({ word, removes: true });
630
1056
  } else if (head === 'rm' || head === 'unlink') {
631
1057
  for (const word of positionals(args)) out.push({ word, removes: true });
632
1058
  } else if (head === 'truncate') {
633
1059
  for (const word of positionals(args, new Set(['-s', '--size', '-r', '--reference']))) out.push({ word });
1060
+ } else if (head === 'git') {
1061
+ out.push(...gitWrites(w, cwd));
634
1062
  }
635
1063
  return out;
636
1064
  }
@@ -686,7 +1114,7 @@ function walk(seg, state, acc) {
686
1114
  if (toks.length && state.cwd !== null) acc.named.push({ word: state.cwd, dir: null, isDir: true });
687
1115
  for (const n of namedWords(seg.toks, toks[0])) acc.named.push({ ...n, dir: state.cwd, globstar: !!state.globstar });
688
1116
  if (!toks.length) {
689
- for (const word of redirectTargets(seg.toks)) acc.writes.push({ dir: state.cwd, word });
1117
+ for (const word of redirectTargets(seg.toks)) acc.writes.push({ dir: state.cwd, word, ...writePattern(seg.toks, { word }) });
690
1118
  return;
691
1119
  }
692
1120
  const w = toks.map((t) => t.v);
@@ -697,7 +1125,7 @@ function walk(seg, state, acc) {
697
1125
  if (why && acc.unjudgeable === null) acc.unjudgeable = why;
698
1126
  const host = hostRulesChange(w);
699
1127
  if (host && acc.hostRules === null) acc.hostRules = host;
700
- for (const t of writeTargets(seg, w, head)) acc.writes.push({ ...t, dir: state.cwd });
1128
+ for (const t of writeTargets(seg, w, head, state.cwd)) acc.writes.push({ ...t, ...writePattern(seg.toks, t), dir: t.dir === undefined ? state.cwd : t.dir });
701
1129
  const ownCommit = head === 'git' && w[gitSubIndex(w)] === 'commit';
702
1130
  if (state.cwd !== null && !MENTION_READERS.has(head) && !ownCommit) {
703
1131
  for (const x of w.slice(1)) if (!x.startsWith('-') && !/[$`]/.test(x)) acc.mentions.push({ dir: state.cwd, word: x });
@@ -722,27 +1150,45 @@ function walk(seg, state, acc) {
722
1150
  // An unquoted backtick ends the segment in the lexer, so the real target, the substitution's
723
1151
  // output, is not among `toks`: `cd `echo data`` would otherwise read as a cd with no target.
724
1152
  if (seg.subst) unknown(`${b} \`...\``);
1153
+ // A command of a pipeline, and one put in the background, runs in a subshell in Bash, so its cd
1154
+ // ends there; zsh runs a pipeline's last command in the shell itself. The text does not say which
1155
+ // shell reads it, so where the later commands run cannot be told.
1156
+ const detached = seg.piped === true || seg.stdin !== undefined || seg.background === true;
1157
+ // The shell expands an unquoted glob or brace expression before cd sees it: what the directory
1158
+ // is depends on the files there (issue #118).
1159
+ const expands = target !== undefined && (GLOB.test(toks[at].b)
1160
+ || (toks[at].b.includes('{') && (expandBraces(target, toks[at].m ?? '0'.repeat(target.length)) ?? []).join(' ') !== target));
1161
+ const shown = `${b}${target === undefined ? '' : ` ${target}`}`;
1162
+ if (detached) unknown(`${shown} in a pipeline or in the background`);
725
1163
  if (target === undefined) {
726
1164
  if (b === 'cd') acc.named.push({ word: os.homedir(), dir: null, isDir: true });
727
1165
  else unknown('pushd');
728
- } else if (target === '-' || /[$`]/.test(toks[at].x ?? target) || (target.startsWith('~') && !/^~(\/|$)/.test(target))) {
1166
+ } else if (expands || target === '-' || /[$`]/.test(toks[at].x ?? target) || (target.startsWith('~') && !/^~(\/|$)/.test(target))) {
729
1167
  unknown(`${b} ${target}`);
730
1168
  } else {
731
1169
  const t = fromGitBash((target === '~' || target.startsWith('~/') ? os.homedir() + target.slice(1) : target).replace(/\\/g, '/'));
732
1170
  if (state.cwd === null && !path.isAbsolute(t)) unknown(`${b} ${target}`);
733
1171
  else acc.named.push({ word: path.resolve(state.cwd ?? '', t), dir: null, isDir: true });
734
1172
  }
735
- if (b === 'pushd') state.stack.push({ cwd: state.cwd, label: state.label });
1173
+ if (b === 'pushd') state.stack.push({ cwd: state.cwd, label: state.label, why: state.why });
1174
+ state.why = undefined;
736
1175
  if (target === undefined) {
737
1176
  state.cwd = b === 'cd' ? os.homedir() : null;
738
1177
  state.label = b === 'cd' ? '~' : 'pushd';
739
- } else if (target === '-') {
1178
+ } else if (target === '-' || expands) {
740
1179
  state.cwd = null;
741
- state.label = '-';
1180
+ state.label = target;
742
1181
  } else {
743
- state.cwd = resolveDir(state.cwd, target);
1182
+ state.cwd = resolveDir(state.cwd, target, true);
744
1183
  state.label = target;
745
1184
  }
1185
+ if (detached) {
1186
+ state.cwd = null;
1187
+ // The reason a later commit or push is refused names the cause (verdict P6-S-52-r1 H-5).
1188
+ state.why = seg.background === true
1189
+ ? `${shown} is put in the background with &, so the guard does not follow it`
1190
+ : `${shown} is part of a pipeline, so the guard does not follow it`;
1191
+ }
746
1192
  return;
747
1193
  }
748
1194
  if (b === 'popd') {
@@ -750,6 +1196,7 @@ function walk(seg, state, acc) {
750
1196
  if (!prev && acc.cdUnknown === null) acc.cdUnknown = 'popd';
751
1197
  state.cwd = prev ? prev.cwd : null;
752
1198
  state.label = prev ? prev.label : 'popd';
1199
+ state.why = prev ? prev.why : undefined;
753
1200
  return;
754
1201
  }
755
1202
  if (SHELLS.has(b)) {
@@ -776,7 +1223,7 @@ function walk(seg, state, acc) {
776
1223
  return;
777
1224
  }
778
1225
  if (b !== 'git') return;
779
- let dir = state.cwd;
1226
+ let dir = dirExists(state.cwd) ? state.cwd : null;
780
1227
  let label = state.label;
781
1228
  let k = 1;
782
1229
  while (k < w.length && w[k].startsWith('-')) {
@@ -794,6 +1241,11 @@ function walk(seg, state, acc) {
794
1241
  }
795
1242
  const sub = w[k];
796
1243
  const args = w.slice(k + 1);
1244
+ const cut = cutOption(sub, args);
1245
+ if (cut && acc.unjudgeable === null) {
1246
+ acc.unjudgeable = `git ${sub} ${cut.cut} may be ${cut.full} cut short, which git accepts when no other option starts the same way`;
1247
+ acc.fix = `write ${cut.full} in full`;
1248
+ }
797
1249
  let inv;
798
1250
  if (sub === 'commit') inv = parseCommit(args);
799
1251
  else if (sub === 'push') inv = parsePush(args);
@@ -807,27 +1259,74 @@ function walk(seg, state, acc) {
807
1259
  else if (sub === 'merge' || sub === 'pull' || sub === 'rebase') inv = { kind: 'history' };
808
1260
  else if (sub === 'tag') inv = tagLists(args) ? { kind: 'other' } : { kind: 'history' };
809
1261
  else inv = { kind: 'other' };
810
- acc.invs.push({ ...inv, dir, label: dir === null ? label : (label ?? dir) });
1262
+ acc.invs.push({ ...inv, dir, label: dir === null ? label : (label ?? dir), why: dir === null ? state.why : undefined });
811
1263
  }
812
1264
 
813
1265
  // -> {invs, texts, mentions, writes, unjudgeable, hostRules}: every git/gh invocation in order, each
814
1266
  // command's text for rule 6, the paths written (rule 0c), and the first reason for rules 0a and 0b.
815
1267
  // cwd null means unknown.
816
1268
  function parse(command, cwd) {
817
- const acc = { invs: [], texts: [], mentions: [], writes: [], named: [], unjudgeable: null, hostRules: null, cdUnknown: null };
1269
+ const acc = { invs: [], texts: [], mentions: [], writes: [], named: [], unjudgeable: null, fix: undefined, hostRules: null, cdUnknown: null };
818
1270
  walkAll(lex(command), { cwd, label: cwd, stack: [] }, acc);
819
1271
  return acc;
820
1272
  }
821
1273
 
822
- // Walks segments in order; a `cd` inside a subshell `( ... )` ends with it, so the directory is put
823
- // back when the segments leave the parentheses.
1274
+ // Walks segments in order; a `cd` inside a subshell `( ... )` or a backtick substitution ends with
1275
+ // it, so the directory is put back when the segments leave the parentheses or pass the closing
1276
+ // backtick (issue #121). A brace group `{ ...; }` that is piped on or put in the background runs in a
1277
+ // subshell too, so its `cd` ends at the closing brace (verdict P6-S-52-r1 H-2); one that ends a
1278
+ // pipeline runs in a subshell in Bash and in the shell itself in zsh, so after a `cd` in it the
1279
+ // directory is unknown, as it is after a `cd` that ends a pipeline.
1280
+ //
1281
+ // Where a group opens and ends is read from the shell grammar (verdict P6-S-52-r2 H-2). `{` opens a
1282
+ // group where a command may start: first in a command, or after the words that may come before one
1283
+ // there (`!`, `time` and its `-p`, `if`, `then`, `elif`, `else`, `do`, `while`, `until`, another `{`,
1284
+ // `coproc` and its name, `function` and its name). `}` first in a command closes the group, and the
1285
+ // command it ends runs on through the redirections after the brace to the operator that ends it: the
1286
+ // lexer marks that command `piped` or `background` whatever redirections stand between (`} 2>&1 |`,
1287
+ // `} &>f &`). A `coproc` group always runs in a subshell. A `}` that closes no group read here means
1288
+ // the text was not read as the shell reads it, so where a `cd` before it lasts is not known.
824
1289
  function walkAll(segs, state, acc) {
1290
+ const snapshot = () => ({ cwd: state.cwd, label: state.label, why: state.why, stack: [...state.stack], globstar: state.globstar });
1291
+ const plain = (t) => t !== undefined && t.v === t.b && !t.m?.includes('1');
1292
+ const bare = (t, word) => plain(t) && t.v === word;
825
1293
  const saved = [];
1294
+ const groups = [];
826
1295
  for (const seg of segs) {
827
- const depth = seg.depth ?? 0;
828
- while (saved.length < depth) saved.push({ cwd: state.cwd, label: state.label, stack: [...state.stack], globstar: state.globstar });
1296
+ const depth = (seg.depth ?? 0) + (seg.tick ? 1 : 0);
1297
+ while (saved.length < depth) saved.push(snapshot());
829
1298
  while (saved.length > depth) Object.assign(state, saved.pop());
1299
+ let coproc = false;
1300
+ for (let k = 0; k < seg.toks.length; k++) {
1301
+ const t = seg.toks[k];
1302
+ if (!plain(t)) break;
1303
+ if (t.v === '{') {
1304
+ groups.push({ ...snapshot(), tail: seg.stdin !== undefined, detached: coproc });
1305
+ coproc = false;
1306
+ } else if (t.v === 'time') {
1307
+ while (bare(seg.toks[k + 1], '-p') || bare(seg.toks[k + 1], '--')) k += 1;
1308
+ } else if (t.v === 'coproc') {
1309
+ coproc = true;
1310
+ if (!bare(seg.toks[k + 1], '{') && bare(seg.toks[k + 2], '{')) k += 1;
1311
+ } else if (t.v === 'function') {
1312
+ k += 1;
1313
+ } else if (!KEYWORDS.has(t.v)) break;
1314
+ }
1315
+ const closes = bare(seg.toks[0], '}');
1316
+ const group = closes ? groups.pop() : undefined;
1317
+ if (closes && !group && acc.cdUnknown === null) acc.cdUnknown = 'a cd in a brace group whose opening brace the guard did not read';
1318
+ const detached = seg.piped === true || seg.background === true || group?.detached === true;
1319
+ // A redirection on the closing brace of such a group is judged from the directory outside it.
1320
+ if (group && detached) {
1321
+ const { tail, detached: always, ...before } = group;
1322
+ Object.assign(state, before);
1323
+ }
830
1324
  walk(seg, state, acc);
1325
+ if (group?.tail && !detached && state.cwd !== group.cwd) {
1326
+ if (acc.cdUnknown === null) acc.cdUnknown = 'a cd in a brace group that ends a pipeline';
1327
+ state.cwd = null;
1328
+ state.why = 'a cd in a brace group that ends a pipeline lasts in zsh and not in Bash, so the guard does not follow it';
1329
+ }
831
1330
  }
832
1331
  }
833
1332
 
@@ -887,7 +1386,7 @@ function covers(stager, file, top) {
887
1386
  function namesIntake(mentions, intakeAbs) {
888
1387
  return mentions.some(({ dir, word }) => {
889
1388
  const rel = path.relative(intakeAbs, path.resolve(real(dir), word));
890
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
1389
+ return rel === '' || !leaves(rel);
891
1390
  });
892
1391
  }
893
1392
 
@@ -898,7 +1397,7 @@ function frozenIntake(root, cfg, invs, mentions) {
898
1397
  if (!top) continue;
899
1398
  if (!quiet(() => (git(top, ['rev-parse', '--verify', 'HEAD']), true), false)) continue;
900
1399
  const intake = toPosix(path.relative(top, intakeAbs));
901
- if (intake.startsWith('..') || path.isAbsolute(intake)) continue;
1400
+ if (leaves(intake)) continue;
902
1401
  const inHead = (f) => quiet(() => (git(top, ['cat-file', '-e', `HEAD:${f}`]), true), false);
903
1402
  // A commit naming paths commits only those; the index counts too only with -i.
904
1403
  const onlyPaths = c.paths.length > 0 && !c.include;
@@ -930,27 +1429,78 @@ const fkey = (p) => (WIN ? p.toLowerCase() : p);
930
1429
  const GLOB = /[*?[]/;
931
1430
 
932
1431
  // A shell glob over POSIX paths as an anchored regular expression (`*` and `?` stay in one segment;
933
- // `[!...]` and `[^...]` are both a negated class, as Bash reads them).
934
- function globRe(pattern) {
935
- const src = pattern.replace(/[.+^${}()|\\]/g, '\\$&').replace(/\[(?:!|\\\^)/g, '[^').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]');
936
- return new RegExp(`^${src}$`, WIN ? 'i' : '');
1432
+ // `[!...]` and `[^...]` are both a negated class, as Bash reads them; a `[` nothing closes is itself).
1433
+ // Each bracket expression is read by `readBracket`, as Bash reads one. A range that runs backwards
1434
+ // (`[z-a]`) is left out of its expression, as Bash leaves it out: alone it matches nothing, so Bash
1435
+ // passes the word on as it is and the caller judges the literal word too (issue #119). Null only when
1436
+ // the expression built here does not compile. `star` is what `*` matches: within one segment for the
1437
+ // shell, across them for a git pathspec. The expression carries `unsure` when a bracket expression in
1438
+ // it is one the reader does not read to its end as Bash would: the caller then takes the word to be
1439
+ // one it cannot judge (verdict P6-S-52-r1 H-1, verdict P6-S-52-r2 B-1).
1440
+ function globRe(pattern, star = '[^/]*') {
1441
+ let src = '';
1442
+ let unsure = false;
1443
+ // A character that is not syntax. On Windows a letter stands for both of its cases, since a name
1444
+ // that is not a glob is looked up there without regard to case; the expression carries no `i` flag,
1445
+ // so that a negated bracket expression leaves out only the characters it names, as Bash does.
1446
+ const literal = (c) => {
1447
+ const lower = c.toLowerCase();
1448
+ const upper = c.toUpperCase();
1449
+ const forms = WIN && lower !== upper && lower.length === 1 && upper.length === 1 ? [lower, upper] : [c];
1450
+ const esc = forms.map((x) => `\\u${x.charCodeAt(0).toString(16).padStart(4, '0')}`).join('');
1451
+ return forms.length > 1 ? `[${esc}]` : esc;
1452
+ };
1453
+ for (let i = 0; i < pattern.length; i++) {
1454
+ const c = pattern[i];
1455
+ const cls = c === '[' ? readBracket(pattern, i) : null;
1456
+ if (cls?.unsure) {
1457
+ unsure = true;
1458
+ src += '[^/]*';
1459
+ i = cls.end;
1460
+ } else if (cls) {
1461
+ src += `(?!/)${classSrc(cls, WIN)}`;
1462
+ i = cls.end;
1463
+ } else if (c === '*') src += star;
1464
+ else if (c === '?') src += '[^/]';
1465
+ else src += literal(c);
1466
+ }
1467
+ try {
1468
+ const re = new RegExp(`^${src}$`);
1469
+ if (unsure) re.unsure = true;
1470
+ return re;
1471
+ } catch {
1472
+ return null;
1473
+ }
937
1474
  }
938
1475
 
939
1476
  // Whether a write {dir, word, removes?, into?} reaches the frozen file at absolute POSIX path `frozen`.
940
1477
  function reaches(wr, frozen) {
1478
+ if (wr.any) return true;
941
1479
  const word = fromGitBash(String(wr.word).replace(/\\/g, '/'));
942
1480
  if (word === '') return false;
1481
+ const star = wr.pathspec ? '.*' : '[^/]*';
1482
+ // The word is read as a glob as it stands and, when a member of a bracket expression in it was
1483
+ // quoted, as the pattern that keeps the quoting (`writePattern`): either reading may reach the test.
1484
+ const globs = [word, ...(wr.pattern === undefined ? [] : [fromGitBash(wr.pattern.replace(/\\/g, '/'))])].filter((g) => GLOB.test(g));
943
1485
  if (/[$`]/.test(word) || (wr.dir === null && !path.isAbsolute(word))) {
944
1486
  // The directory or the name is unknown: judge by the last segment.
945
1487
  const last = word.split('/').pop();
946
- return !/[$`]/.test(last) && (GLOB.test(last) ? globRe(last).test(path.posix.basename(frozen))
947
- : fkey(last) === fkey(path.posix.basename(frozen)));
1488
+ if (/[$`]/.test(last)) return false;
1489
+ for (const g of globs) {
1490
+ const lastRe = GLOB.test(g.split('/').pop()) ? globRe(g.split('/').pop(), star) : null;
1491
+ // A bracket expression the reader cannot read as Bash would may match the frozen test.
1492
+ if (lastRe?.unsure || lastRe?.test(path.posix.basename(frozen))) return true;
1493
+ }
1494
+ return fkey(last) === fkey(path.posix.basename(frozen));
948
1495
  }
949
- const target = toPosix(path.resolve(wr.dir === null ? '' : real(wr.dir), word));
950
- if (GLOB.test(word)) {
951
- const re = globRe(target);
952
- return re.test(frozen) || (wr.removes === true && frozen.split('/').some((_, k, all) => re.test(all.slice(0, k).join('/'))));
1496
+ const from = wr.dir === null ? '' : real(wr.dir);
1497
+ const target = toPosix(path.resolve(from, word));
1498
+ for (const g of globs) {
1499
+ const re = globRe(toPosix(path.resolve(from, g)), star);
1500
+ if (re?.unsure) return true;
1501
+ if (re && (re.test(frozen) || (wr.removes === true && frozen.split('/').some((_, k, all) => re.test(all.slice(0, k).join('/')))))) return true;
953
1502
  }
1503
+ // A glob that matches nothing is passed on as the literal word, which is judged as one below.
954
1504
  const canon = toPosix(real(target));
955
1505
  if (fkey(canon) === fkey(frozen)) return true;
956
1506
  if (wr.removes && fkey(frozen).startsWith(`${fkey(canon)}/`)) return true;
@@ -1018,6 +1568,45 @@ function namedWords(toks, head) {
1018
1568
  return out;
1019
1569
  }
1020
1570
 
1571
+ // A quoted or escaped character inside an unquoted bracket expression is a member of it and nothing
1572
+ // else, as Bash reads `d[a\]]ta`: there the escaped `]` does not close the expression. The lexer has
1573
+ // removed the quoting and kept it in the mask, so each bracket expression is read here with the mask
1574
+ // by `readBracket`, the one reader of bracket expressions, and written again as a pattern string that
1575
+ // reads the same with no mask: each quoted member becomes the collating symbol of its character
1576
+ // (`[.].]`), and a quoted backslash that of `BACKSLASH_MEMBER`, since a backslash in the string would
1577
+ // be taken for a path separator (verdict P6-S-52-r1 H-1, verdict P6-S-52-r2 B-1).
1578
+ // -> [word, mask, unsure]: `unsure` when an expression of the word is one the reader does not read.
1579
+ function literalMembers(v, m) {
1580
+ const quoted = (j) => m[j] === '1';
1581
+ let word = '';
1582
+ let mask = '';
1583
+ let i = 0;
1584
+ while (i < v.length) {
1585
+ const cls = v[i] === '[' && !quoted(i) ? readBracket(v, i, quoted) : null;
1586
+ if (cls?.unsure) return [v, m, true];
1587
+ if (cls === null) {
1588
+ // A `[` that was quoted, or that nothing closes, is that character: written as itself, it could
1589
+ // open an expression when the string is read again with no mask.
1590
+ const own = v[i] === '[';
1591
+ word += own ? `[[.${v[i]}.]]` : v[i];
1592
+ mask += own ? '0001000' : m[i];
1593
+ i += 1;
1594
+ continue;
1595
+ }
1596
+ for (let k = i; k <= cls.end; k++) {
1597
+ if (quoted(k)) {
1598
+ word += `[.${v[k] === '\\' ? BACKSLASH_MEMBER : v[k]}.]`;
1599
+ mask += '00100';
1600
+ } else {
1601
+ word += v[k];
1602
+ mask += m[k];
1603
+ }
1604
+ }
1605
+ i = cls.end + 1;
1606
+ }
1607
+ return [word, mask, false];
1608
+ }
1609
+
1021
1610
  // Appends to `out` the paths word `t` names from character `cut` on: each word its braces expand to,
1022
1611
  // with `~` as the home directory, and the path of a `<rev>:<path>` word.
1023
1612
  function wordPaths(t, cut, out) {
@@ -1031,16 +1620,31 @@ function wordPaths(t, cut, out) {
1031
1620
  return;
1032
1621
  }
1033
1622
  const glob = GLOB.test(t.b);
1034
- for (let w of variants) {
1623
+ // The same words with each quoted member of a bracket expression marked: what the shell expands.
1624
+ // The word as written stays the name that is judged and reported.
1625
+ const [pv, pm, unread] = glob ? literalMembers(v, m) : [v, m, false];
1626
+ const marked = pv === v ? null : t.b.includes('{') && t.b.includes('}') ? expandBraces(pv, pm) : [pv];
1627
+ // A word whose bracket expression is not read, before its braces expand or after, and one whose
1628
+ // marked form does not expand as the word does, is not judged by a guess: it is refused.
1629
+ const unsure = (w) => globRe(w.replace(/\\/g, '/'))?.unsure === true;
1630
+ if (unread || (marked !== null && marked?.length !== variants.length) || (glob && (marked ?? variants).some(unsure))) {
1631
+ out.push({ word: v, unsure: true });
1632
+ return;
1633
+ }
1634
+ const patterns = marked;
1635
+ const home = (w) => ((w === '~' || w.startsWith('~/')) && t.b.includes('~') ? os.homedir() + w.slice(1) : w);
1636
+ const REV = /^[^:]*:(?:[0-3]:)?(.+)$/;
1637
+ for (let k = 0; k < variants.length; k++) {
1035
1638
  // An unquoted `~` is the home directory; an unquoted glob character makes the word a glob.
1036
- if ((w === '~' || w.startsWith('~/')) && t.b.includes('~')) w = os.homedir() + w.slice(1);
1037
- out.push({ word: w, glob });
1639
+ const w = home(variants[k]);
1640
+ const pattern = patterns ? home(patterns[k]) : undefined;
1641
+ out.push({ word: w, glob, pattern });
1038
1642
  // `<rev>:<path>`, `:<path>` and `:<stage>:<path>` (the index): git reads the path from the
1039
1643
  // repository's top, or from the shell's directory when it starts with `./` or `../`.
1040
- const rev = /^[^:]*:(?:[0-3]:)?(.+)$/.exec(w);
1644
+ const rev = REV.exec(w);
1041
1645
  if (rev && !/^[A-Za-z]:[\\/]/.test(w)) {
1042
1646
  const p = rev[1];
1043
- out.push({ word: p, glob, fromTop: !/^\.\.?\//.test(p) });
1647
+ out.push({ word: p, glob, fromTop: !/^\.\.?\//.test(p), pattern: pattern === undefined ? undefined : REV.exec(pattern)?.[1] });
1044
1648
  }
1045
1649
  }
1046
1650
  }
@@ -1126,7 +1730,8 @@ function firstBrace(w, m) {
1126
1730
  // dot names. With `globstar` (the command ran `shopt -s globstar` first), a segment that is only `**`
1127
1731
  // is the directory itself and everything under it, at any depth (dot names and symlinked directories
1128
1732
  // aside). Null when a segment expands to more than `cap` entries, so the caller fails closed instead of
1129
- // judging a part.
1733
+ // judging a part; UNSURE when a segment holds a bracket expression the reader cannot read as Bash would.
1734
+ const UNSURE = Symbol('unsure');
1130
1735
  function expandGlob(base, word, globstar = false, cap = 20000) {
1131
1736
  const target = toPosix(path.resolve(base, word));
1132
1737
  const segs = target.split('/');
@@ -1158,6 +1763,9 @@ function expandGlob(base, word, globstar = false, cap = 20000) {
1158
1763
  for (const d of found) next.push(path.posix.join(d, seg));
1159
1764
  } else {
1160
1765
  const re = globRe(seg.replace(/\*\*+/g, '*'));
1766
+ // A segment that does not compile matches nothing: the word stays as written.
1767
+ if (re === null) return [];
1768
+ if (re.unsure) return UNSURE;
1161
1769
  for (const d of found) {
1162
1770
  let names = [];
1163
1771
  try {
@@ -1191,19 +1799,30 @@ function deniedPath(root, cfg, named) {
1191
1799
  // The path is judged as written (`data/link`) and as resolved: a symlink under a listed directory
1192
1800
  // that points out of the repository resolves to a `..` path, and its listed name must still count.
1193
1801
  const judgeRel = (rel, abs, isDir) => {
1194
- if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return null;
1802
+ if (rel === '' || leaves(rel)) return null;
1195
1803
  const r = toPosix(rel);
1196
1804
  let pattern = matchesDeny(r, patterns);
1197
1805
  if (pattern === null && (isDir || (fs.existsSync(abs) && fs.statSync(abs).isDirectory()))) pattern = denyDir(r, patterns);
1198
1806
  return pattern === null ? null : { rel: r, pattern };
1199
1807
  };
1200
- const judge = (abs, top, isDir) => judgeRel(path.relative(top, abs), abs, isDir) ?? judgeRel(path.relative(top, real(abs)), abs, isDir);
1201
- for (const { dir, word, fromTop, glob, wide, isDir, globstar } of named) {
1808
+ // A path named through a link or junction that leads to the repository, from outside it or from
1809
+ // inside, is judged where that link leads as well (issue #122).
1810
+ const judge = (abs, top, isDir) => {
1811
+ for (const p of [abs, real(abs), ...namesUnder(top, abs)]) {
1812
+ const hit = judgeRel(path.relative(top, p), abs, isDir);
1813
+ if (hit) return hit;
1814
+ }
1815
+ return null;
1816
+ };
1817
+ for (const { dir, word, fromTop, glob, wide, unsure, isDir, globstar, pattern } of named) {
1202
1818
  if (wide) return { wide: word };
1203
- const once = JSON.stringify([dir, word, fromTop, glob, isDir, globstar]);
1819
+ if (unsure) return { unsure: word };
1820
+ const once = JSON.stringify([dir, word, fromTop, glob, isDir, globstar, pattern]);
1204
1821
  if (seen.has(once)) continue;
1205
1822
  seen.add(once);
1206
1823
  const p = fromGitBash(word.replace(/\\/g, '/'));
1824
+ // What the shell expands: the word, with the quoted members of a bracket expression marked.
1825
+ const g = pattern === undefined ? p : fromGitBash(pattern.replace(/\\/g, '/'));
1207
1826
  const tops = [hookTop];
1208
1827
  if (dir !== null) {
1209
1828
  if (!topAt.has(dir)) topAt.set(dir, topOf(dir));
@@ -1214,9 +1833,10 @@ function deniedPath(root, cfg, named) {
1214
1833
  const base = fromTop ? top : dir === null ? null : real(dir);
1215
1834
  if (base === null && !path.isAbsolute(p)) continue;
1216
1835
  const candidates = [path.resolve(base ?? top, p)];
1217
- if (glob && GLOB.test(p)) {
1218
- const expanded = expandGlob(base ?? top, p, globstar);
1836
+ if (glob && GLOB.test(g)) {
1837
+ const expanded = expandGlob(base ?? top, g, globstar);
1219
1838
  if (expanded === null) return { wide: p };
1839
+ if (expanded === UNSURE) return { unsure: p };
1220
1840
  candidates.push(...expanded);
1221
1841
  }
1222
1842
  for (const abs of candidates) {
@@ -1232,20 +1852,27 @@ function deniedPath(root, cfg, named) {
1232
1852
 
1233
1853
  // ---- the hook ----
1234
1854
 
1235
- const unknownDir = (label) => deny(`cannot tell which branch ${label} is on; run the command from inside the repository`);
1855
+ // `why` is the cause when the directory is unknown for a reason other than its name: a `cd` in a
1856
+ // pipeline or in the background.
1857
+ const unknownDir = (label, why) => deny(why
1858
+ ? `cannot tell which directory git runs in, and so which branch it is on: ${why}; give the cd its own place in an && chain`
1859
+ : `cannot tell which branch ${label} is on; run the command from inside the repository`);
1236
1860
 
1237
1861
  export function handle(input, { root, cfg }) {
1238
1862
  const command = input?.tool_input?.command;
1239
1863
  if (typeof command !== 'string') throw new Error('tool_input.command is missing');
1240
1864
  const start = typeof input.cwd === 'string' && input.cwd !== '' ? resolveDir(null, input.cwd) : root;
1241
- const { invs, texts, mentions, writes, named, cdUnknown, unjudgeable: why, hostRules } = parse(command, start);
1865
+ const { invs, texts, mentions, writes, named, cdUnknown, unjudgeable: why, fix, hostRules } = parse(command, start);
1242
1866
  const protectedSet = new Set(cfg.protectedBranches);
1243
1867
 
1244
1868
  // (0a), in every session and on every branch (D-83)
1245
- if (why) return deny(`cannot judge this command (REQ-3.2): ${why}; run git and gh with literal arguments`);
1869
+ if (why) return deny(`cannot judge this command (REQ-3.2): ${why}; ${fix ?? 'run git and gh with literal arguments'}`);
1246
1870
  // (0b)
1871
+ if (hostRules?.unjudged) {
1872
+ return deny(`cannot judge this command (REQ-3.14): ${hostRules.unjudged}, so it cannot be told from a write to the git host's rules; ${hostRules.fix ?? "give the query in the command as -f query='...'"}`);
1873
+ }
1247
1874
  if (hostRules) {
1248
- return deny(`${hostRules} changes the git host's rules (REQ-3.14); a human runs it from their own terminal`);
1875
+ return deny(`${hostRules.change} changes the git host's rules (REQ-3.14); a human runs it from their own terminal`);
1249
1876
  }
1250
1877
  // (0c)
1251
1878
  const hit = frozenWrite(root, cfg, writes);
@@ -1257,6 +1884,9 @@ export function handle(input, { root, cfg }) {
1257
1884
  return deny(`cannot tell where ${cdUnknown} goes, so its paths cannot be judged against agents.denyPaths (REQ-3.13); cd to a literal directory`);
1258
1885
  }
1259
1886
  const named0d = deniedPath(root, cfg, named);
1887
+ if (named0d?.unsure) {
1888
+ return deny(`cannot tell what ${named0d.unsure} expands to, so it may name a path of agents.denyPaths (REQ-3.13); name the path without the bracket expression`);
1889
+ }
1260
1890
  if (named0d?.wide) {
1261
1891
  return deny(`${named0d.wide} expands too wide to judge against agents.denyPaths (REQ-3.13); name the paths or narrow the expression`);
1262
1892
  }
@@ -1281,7 +1911,7 @@ export function handle(input, { root, cfg }) {
1281
1911
 
1282
1912
  // (1)
1283
1913
  for (const c of invs.filter((i) => i.kind === 'commit')) {
1284
- if (c.branch === UNKNOWN) return unknownDir(c.label);
1914
+ if (c.branch === UNKNOWN) return unknownDir(c.label, c.why);
1285
1915
  if (c.branch !== null && protectedSet.has(c.branch)) return deny(`commit on protected branch ${c.branch}; create a slice branch`);
1286
1916
  }
1287
1917
  // (2)
@@ -1289,7 +1919,7 @@ export function handle(input, { root, cfg }) {
1289
1919
  for (const p of pushes) {
1290
1920
  if (p.all && cfg.protectedBranches.length) return deny(`push to protected branch ${cfg.protectedBranches[0]}`);
1291
1921
  for (const t of p.targets) {
1292
- if (t === null && p.branch === UNKNOWN) return unknownDir(p.label);
1922
+ if (t === null && p.branch === UNKNOWN) return unknownDir(p.label, p.why);
1293
1923
  const b = t === null ? p.branch : t;
1294
1924
  if (b !== null && protectedSet.has(b)) return deny(`push to protected branch ${b}`);
1295
1925
  }