@williacj/rigger 0.0.0-stage → 0.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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +370 -2
  3. package/package.json +56 -4
  4. package/scripts/doc-reference-check.mjs +59 -0
  5. package/scripts/gate-check.mjs +249 -0
  6. package/scripts/lib/pack-result.mjs +9 -0
  7. package/scripts/record-commit.mjs +67 -0
  8. package/src/cli/doctor.mjs +1021 -0
  9. package/src/cli/init.mjs +384 -0
  10. package/src/cli/once.mjs +489 -0
  11. package/src/cli/pause.mjs +56 -0
  12. package/src/cli/plan.mjs +106 -0
  13. package/src/cli/recording.mjs +52 -0
  14. package/src/cli/report.mjs +242 -0
  15. package/src/cli/resume.mjs +96 -0
  16. package/src/cli/rigger.mjs +12 -0
  17. package/src/cli/run.mjs +10 -0
  18. package/src/cli/setup-board.mjs +108 -0
  19. package/src/cli/verbs.mjs +82 -0
  20. package/src/cli/verdict.mjs +180 -0
  21. package/src/config/validate.mjs +960 -0
  22. package/src/execution/groups.mjs +185 -0
  23. package/src/execution/kept-output.mjs +21 -0
  24. package/src/execution/role.mjs +171 -0
  25. package/src/execution/run.mjs +490 -0
  26. package/src/execution/step.mjs +26 -0
  27. package/src/execution/workspace.mjs +866 -0
  28. package/src/observation/push.mjs +103 -0
  29. package/src/observation/report.mjs +415 -0
  30. package/src/observation/sink.mjs +271 -0
  31. package/src/package-commit.json +1 -0
  32. package/src/scheduling/admission.mjs +390 -0
  33. package/src/scheduling/clock.mjs +98 -0
  34. package/src/scheduling/lane.mjs +160 -0
  35. package/src/scheduling/loop.mjs +1738 -0
  36. package/src/scheduling/pull-order.mjs +46 -0
  37. package/src/substrate/data-ref.mjs +147 -0
  38. package/src/substrate/forge/assets.mjs +5 -0
  39. package/src/substrate/forge/graphql.mjs +258 -0
  40. package/src/substrate/forge/item-write.mjs +74 -0
  41. package/src/substrate/forge/read.mjs +998 -0
  42. package/src/substrate/forge/repository-write.mjs +152 -0
  43. package/src/substrate/forge/runners.mjs +510 -0
  44. package/src/substrate/forge/schema-write.mjs +70 -0
  45. package/src/substrate/forge/write-made.mjs +40 -0
  46. package/src/substrate/git-environment.mjs +54 -0
  47. package/src/substrate/host.mjs +23 -0
  48. package/src/substrate/launchd.mjs +23 -0
  49. package/src/substrate/process-table.sh +48 -0
  50. package/src/substrate/process.mjs +2474 -0
  51. package/src/substrate/providers/adapters.mjs +8 -0
  52. package/src/substrate/providers/claude.mjs +427 -0
  53. package/src/substrate/providers/codex.mjs +349 -0
  54. package/src/substrate/standard-error.mjs +134 -0
  55. package/src/substrate/worktrees.mjs +517 -0
  56. package/src/workflow/clock-mark.mjs +40 -0
  57. package/src/workflow/escalation.mjs +110 -0
  58. package/src/workflow/facts.mjs +92 -0
  59. package/src/workflow/first-above.mjs +17 -0
  60. package/src/workflow/form-check.mjs +88 -0
  61. package/src/workflow/gate.mjs +62 -0
  62. package/src/workflow/judges.mjs +695 -0
  63. package/src/workflow/marker.mjs +265 -0
  64. package/src/workflow/next-action.mjs +456 -0
  65. package/src/workflow/status-issue.mjs +268 -0
  66. package/src/workflow/transitions.mjs +588 -0
  67. package/templates/claude/agents/architect.md +116 -0
  68. package/templates/claude/agents/engineer.md +57 -0
  69. package/templates/claude/agents/pm.md +114 -0
  70. package/templates/claude/agents/reviewer.md +37 -0
  71. package/templates/claude/agents/spike-engineer.md +80 -0
  72. package/templates/claude/hooks/refuse-reserved-git-commands.mjs +909 -0
  73. package/templates/claude/settings.json +50 -0
  74. package/templates/claude/skills/acceptance/SKILL.md +275 -0
  75. package/templates/claude/skills/agent-style/SKILL.md +78 -0
  76. package/templates/claude/skills/code-review/SKILL.md +242 -0
  77. package/templates/claude/skills/proposal/SKILL.md +175 -0
  78. package/templates/claude/skills/spec-style/SKILL.md +112 -0
  79. package/templates/claude/skills/tdd/SKILL.md +230 -0
  80. package/templates/codex/config.toml +19 -0
  81. package/templates/doc-reference-check.md +25 -0
  82. package/templates/githooks/pre-push +24 -0
  83. package/templates/github/workflows/rigger-gate.yml +209 -0
  84. package/templates/launchd/com.williacj.rigger.plist +31 -0
  85. package/templates/rigger.config.mjs +78 -0
@@ -0,0 +1,909 @@
1
+ // ABOUTME: Claude Code's PreToolUse gate on Bash. Refuses reserved git spellings and literal
2
+ // pushes to the default branch, whose name it reads from the local remote HEAD.
3
+ // Reads the hook payload on stdin; prints a deny decision, or nothing when it has no objection.
4
+
5
+ import { spawnSync } from 'node:child_process';
6
+ import { readFileSync } from 'node:fs';
7
+
8
+ const EVENT = 'PreToolUse';
9
+
10
+ // A permission rule is a lexical prefix, so it can say "this command" and "anything starting with
11
+ // this text", and cannot say "this command with any argument except these". That is the control
12
+ // AGENTS.md asks for, so it is made here instead.
13
+
14
+ // Two refusals, because either alone can be lost. The decision carries the reason; exit 2 blocks
15
+ // even where the decision is not read, and an exit code Claude Code does not recognise lets the
16
+ // command through.
17
+ function refuse(reason) {
18
+ process.stdout.write(
19
+ JSON.stringify({
20
+ hookSpecificOutput: {
21
+ hookEventName: EVENT,
22
+ permissionDecision: 'deny',
23
+ permissionDecisionReason: reason,
24
+ },
25
+ }),
26
+ );
27
+ process.stderr.write(`${reason}\n`);
28
+ process.exit(2);
29
+ }
30
+
31
+ /** No objection. The permission rules and the prompt decide from here. */
32
+ function stepAside() {
33
+ process.exit(0);
34
+ }
35
+
36
+ class Unreadable extends Error {}
37
+
38
+ const OPERATORS = ['&&', '||', ';', '|', '&', '\n'];
39
+
40
+ /**
41
+ * Bash's two-character redirection operators whose second character is also the spelling of a
42
+ * control operator. Read as one token, or the operator list above claims the second character and
43
+ * divides a command where bash divides none.
44
+ */
45
+ const REDIRECTION_OPERATOR = new Set(['<&', '>&', '>|']);
46
+
47
+ // Bash owns what a here-document is. This is a copy of the part of that rule the gate needs, so
48
+ // this is where the copy can disagree with bash, and what it does about each disagreement.
49
+ //
50
+ // A `<<` opens a here-document only where bash reads a command's words, and only where a
51
+ // redirection may begin. Skipping a body is the gate choosing not to read text, so a `<<` this
52
+ // lexer honours and bash ignores skips commands bash goes on to run — which is why the notion of
53
+ // where one can open must not exceed bash's. Bash reads no command word inside a quoted string,
54
+ // a comment, an arithmetic expression, a parameter expansion or a backtick substitution. The
55
+ // first, second, third and fifth the lexer takes whole. The fourth, and `$[ ]` with it, are not
56
+ // modelled: instead this gate honours a `<<` only where the word being read is empty or is the
57
+ // file descriptor it redirects, which places a `<<` inside any word-internal construct out of
58
+ // reach without modelling any of them. That list was taken from bash by running it, and `[[ ]]`
59
+ // and a `case` pattern are absent from it because bash rejects a `<<` in either.
60
+ //
61
+ // That placement rule is narrower than bash's, which is a cost rather than a claim about bash:
62
+ // bash ends a word at `<` and `>`, so it begins a redirection straight after another
63
+ // redirection's target, and `cat >out<<EOF` is a here-document to bash and unreadable here. It is
64
+ // kept narrow deliberately. Honouring a `<<` because its word began with a redirection would
65
+ // honour `echo >${x:-<<W}` too, where bash reads no redirection at all and runs what follows —
66
+ // measured, and the reason the rule is not widened to the target.
67
+ //
68
+ // Where the copy still disagrees, it refuses:
69
+ // - A body bash would end at end of input. Bash warns and runs the command; a permission
70
+ // decision has no warning to give, and the alternative is skipping to the end of the text.
71
+ // - A `<<` this gate cannot place: inside a word, as in `cat foo<<EOF`, `a=1<<EOF` and
72
+ // `let x=1<<EOF`, and directly after a redirection, as in `cat >out<<EOF` and `cat <<A<<B`.
73
+ // Bash makes every one of those a here-document. The gate cannot tell them apart from a `<<`
74
+ // inside a construct of that word, so all of them are unreadable here.
75
+ // - `$( (subshell) )`, whose first `)` this lexer pairs with the `$(`. Nothing is skipped.
76
+ //
77
+ // And one disagreement it does not settle by refusing, because it never did: the gate reads
78
+ // inside no command substitution and no subshell as commands, so `$(git push --force)`, its
79
+ // backtick spelling, and `( git push --force )` are all permitted and all run. That predates this
80
+ // lexer, is card #84, and nothing here widens or narrows it.
81
+
82
+ /** Where bash ends an unquoted word: a blank, or one of the characters that begin an operator. */
83
+ const METACHARACTER = /[ \t\n|&;()<>]/;
84
+
85
+ /**
86
+ * Read the delimiter word of a here-document, from the first character after `<<` or `<<-`.
87
+ *
88
+ * Bash ends that word at an unquoted metacharacter and removes its quoting to get the delimiter,
89
+ * so `<<'EOF'`, `<<"EOF"` and `<<\EOF` all close on a line reading `EOF`. Blanks may separate the
90
+ * word from the operator.
91
+ */
92
+ function delimiterAt(text, start) {
93
+ let i = start;
94
+ while (text[i] === ' ' || text[i] === '\t') i++;
95
+ let delimiter = '';
96
+
97
+ for (; i < text.length; i++) {
98
+ const ch = text[i];
99
+ if (ch === "'" || ch === '"') {
100
+ const close = text.indexOf(ch, i + 1);
101
+ if (close === -1) throw new Unreadable('the command has an unbalanced quote');
102
+ delimiter += text.slice(i + 1, close);
103
+ i = close;
104
+ continue;
105
+ }
106
+ if (ch === '\\' && i + 1 < text.length) {
107
+ delimiter += text[++i];
108
+ continue;
109
+ }
110
+ if (METACHARACTER.test(ch)) break;
111
+ delimiter += ch;
112
+ }
113
+
114
+ if (!delimiter) throw new Unreadable('a here-document names no delimiter');
115
+ return { delimiter, end: i };
116
+ }
117
+
118
+ /**
119
+ * A line with its ending removed. A line feed ends a line, and *every* carriage return before that
120
+ * line feed belongs to the ending rather than to the text: bash closes a body named `W` on a line
121
+ * reading `W`, `W\r`, `W\r\r` and so on without limit, so the rule is a run of them and not one.
122
+ * Measured on this machine to a depth of six.
123
+ *
124
+ * A run of carriage returns only. A trailing space or tab closes no body, measured the same way,
125
+ * so this takes carriage returns rather than trailing whitespace — trimming whitespace would close
126
+ * bodies bash leaves open.
127
+ *
128
+ * Reading any of that run as text is how a body comes to be read as continuing past the line bash
129
+ * ended it at, with the commands after it skipped. Stripping the whole run can only end a body
130
+ * earlier, which surfaces more text as commands and can hide none.
131
+ */
132
+ const withoutEnding = (line) => line.replace(/\r+$/, '');
133
+
134
+ /**
135
+ * Skip the bodies the here-documents on the line just ended will be fed. A body is data on
136
+ * standard input: it ends at a line that is exactly the delimiter, nothing in it is ever run, and
137
+ * so nothing in it is read as shell text. `<<-` strips leading tabs from the body lines and from
138
+ * that closing line.
139
+ *
140
+ * A body with no closing line is unreadable rather than skipped. Bash ends such a body at end of
141
+ * input and runs the command anyway; refusing instead is the safe half of that disagreement,
142
+ * because a `<<` this gate reads and bash does not cannot then swallow the commands after it.
143
+ */
144
+ function skipBodies(text, start, pending) {
145
+ let i = start;
146
+ for (const { delimiter, stripTabs } of pending) {
147
+ const closing = withoutEnding(delimiter);
148
+ for (;;) {
149
+ if (i >= text.length) throw new Unreadable('a here-document has no closing delimiter');
150
+ const breakAt = text.indexOf('\n', i);
151
+ const end = breakAt === -1 ? text.length : breakAt;
152
+ const read = withoutEnding(text.slice(i, end));
153
+ const line = stripTabs ? read.replace(/^\t+/, '') : read;
154
+ i = breakAt === -1 ? end : breakAt + 1;
155
+ if (line === closing) break;
156
+ if (breakAt === -1) throw new Unreadable('a here-document has no closing delimiter');
157
+ }
158
+ }
159
+ return i;
160
+ }
161
+
162
+ /**
163
+ * The index of the parenthesis that closes an arithmetic expression, given the index of the first
164
+ * of the two that open it — `$((` and `((` alike.
165
+ *
166
+ * `<<` inside either is bash's left shift rather than a redirection, so the expression is taken
167
+ * whole and nothing in it is lexed. One that never closes is unreadable.
168
+ */
169
+ function arithmeticEnd(text, firstParen) {
170
+ let depth = 0;
171
+ for (let i = firstParen; i < text.length; i++) {
172
+ if (text[i] === '(') depth++;
173
+ else if (text[i] === ')' && --depth === 0) return i;
174
+ }
175
+ throw new Unreadable('the command has an unclosed arithmetic expression');
176
+ }
177
+
178
+ /**
179
+ * Split a command line into the separate commands it runs, each as a token list, honouring quotes
180
+ * and backslash escapes. An unbalanced quote is unreadable rather than a guess.
181
+ */
182
+ function commandsIn(text) {
183
+ const commands = [];
184
+ let tokens = [];
185
+ let token = '';
186
+ let open = false; // a token is open even when it lexed to the empty string, as "" does
187
+ let quote = null;
188
+ let word = ''; // the word being read, which is what says whether a redirection may begin here
189
+ const pending = []; // the here-documents opened on the line being read, in the order bash feeds them
190
+ const suspended = []; // the quote each open `$(` interrupted, restored when it closes
191
+ let quotedSubst = 0; // how many of those quotes were real, so the text is inside one after all
192
+
193
+ // A token is what the rules are read against; a word is bash's grammar. They differ, because
194
+ // quoting leaves the token and never the word: `""` lexes to an empty token and a real word.
195
+ const add = (read) => {
196
+ token += read;
197
+ word += read;
198
+ open = true;
199
+ };
200
+ const endToken = () => {
201
+ if (open) tokens.push(token);
202
+ token = '';
203
+ word = '';
204
+ open = false;
205
+ };
206
+ const endCommand = () => {
207
+ endToken();
208
+ if (tokens.length) commands.push(tokens);
209
+ tokens = [];
210
+ };
211
+
212
+ for (let i = 0; i < text.length; i++) {
213
+ const ch = text[i];
214
+
215
+ // Arithmetic, in the `$(( ))` expansion form and in the `(( ))` command form. Read before the
216
+ // quote state, because an expansion is inside double quotes as often as outside them, and is
217
+ // not shell text in either place. The command form only begins where a command may.
218
+ if ((quote === null || quote === '"') && text.startsWith('$((', i)) {
219
+ const end = arithmeticEnd(text, i + 1);
220
+ add(text.slice(i, end + 1));
221
+ i = end;
222
+ continue;
223
+ }
224
+ if (quote === null && word === '' && text.startsWith('((', i)) {
225
+ const end = arithmeticEnd(text, i);
226
+ add(text.slice(i, end + 1));
227
+ i = end;
228
+ continue;
229
+ }
230
+ // A comment runs to the end of the line and bash reads no word in any of it. The line feed is
231
+ // left to the loop, because a here-document opened earlier on this line takes its body after
232
+ // it — `cat <<EOF # a note` is one here-document and one comment.
233
+ if (quote === null && word === '' && ch === '#') {
234
+ const breakAt = text.indexOf('\n', i);
235
+ i = (breakAt === -1 ? text.length : breakAt) - 1;
236
+ continue;
237
+ }
238
+ // A backtick substitution looks for its own here-document bodies inside itself, so a `<<` in
239
+ // one takes nothing from the lines after it. Taken whole, as `$( )`'s contents already are.
240
+ if (quote === null && ch === '`') {
241
+ const close = text.indexOf('`', i + 1);
242
+ if (close === -1) throw new Unreadable('the command has an unclosed backtick substitution');
243
+ add(text.slice(i, close + 1));
244
+ i = close;
245
+ continue;
246
+ }
247
+
248
+ // `$( )` is a command in its own right, and stays one inside double quotes, so a `<<` in it
249
+ // opens a real here-document. Its text is still collected into the word being built, because
250
+ // the words around a substitution belong to the command that wrote it.
251
+ if ((quote === null || quote === '"') && ch === '$' && text[i + 1] === '(') {
252
+ suspended.push(quote);
253
+ if (quote !== null) quotedSubst++;
254
+ quote = null;
255
+ add('$(');
256
+ i++;
257
+ continue;
258
+ }
259
+
260
+ if (quote) {
261
+ if (ch === '\\' && quote === '"' && i + 1 < text.length) add(text[++i]);
262
+ else if (ch === quote) {
263
+ quote = null;
264
+ open = true;
265
+ } else add(ch);
266
+ continue;
267
+ }
268
+
269
+ if (ch === ')' && suspended.length) {
270
+ quote = suspended.pop();
271
+ if (quote !== null) quotedSubst--;
272
+ add(')');
273
+ continue;
274
+ }
275
+ if (ch === "'" || ch === '"') {
276
+ quote = ch;
277
+ // The quoting marks the word without entering the token, which is where it is stripped.
278
+ word += ch;
279
+ open = true;
280
+ continue;
281
+ }
282
+ if (ch === '\\' && i + 1 < text.length) {
283
+ add(text[++i]);
284
+ continue;
285
+ }
286
+ // `<&`, `>&` and `>|` are single redirection operators to bash, so the `&` or `|` in one is no
287
+ // control operator and divides no commands. Read here, before the operator list below can
288
+ // split `2>&1` into `2>` and `1`, or `>| out` into `>` and `out`, and leave the program of
289
+ // `2>&1 git push --force` in a command of its own behind a bare descriptor. The operators
290
+ // written out of operator characters entirely — `<<`, `>>`, `<>` — never had the problem.
291
+ //
292
+ // This narrows what counts as an operator, so text that was two commands becomes one and the
293
+ // words of the second become trailing words of the first. That can hide nothing: a command's
294
+ // program is its first word, and none of these operators had a program after it in any
295
+ // spelling — measured, and the pull request reports what bash ran for each. The one other
296
+ // effect is that such a word is no longer empty where a `<<` follows it, so `2>&1<<EOF` turns
297
+ // from a here-document this gate honours into one it cannot place and refuses. That is the
298
+ // direction that skips no text.
299
+ if (REDIRECTION_OPERATOR.has(text.slice(i, i + 2))) {
300
+ add(text.slice(i, i + 2));
301
+ i++;
302
+ continue;
303
+ }
304
+ if (ch === '<' && text[i + 1] === '<') {
305
+ // A here-string carries its data on this line, so it opens no body and skips nothing.
306
+ if (text[i + 2] === '<') {
307
+ add('<<<');
308
+ i += 2;
309
+ continue;
310
+ }
311
+ // Bash begins a redirection at the start of a word, or straight after the file descriptor
312
+ // it redirects, and nowhere else. A `<<` further into a word is inside some construct of
313
+ // that word — `${x:-<<W}`, `$[1<<W]` — and a `<<` this gate cannot place is one it must not
314
+ // skip a body for, because the text it skipped would be commands bash goes on to run.
315
+ if (word !== '' && !/^\d+$/.test(word)) {
316
+ throw new Unreadable('a `<<` appears where a here-document cannot be placed');
317
+ }
318
+ const stripTabs = text[i + 2] === '-';
319
+ const { delimiter, end } = delimiterAt(text, i + (stripTabs ? 3 : 2));
320
+ pending.push({ delimiter, stripTabs });
321
+ // The redirection stays in the token list rather than being dropped, because a word removed
322
+ // here is a word an option that takes a value would swallow from further along the command.
323
+ add((stripTabs ? '<<-' : '<<') + delimiter);
324
+ i = end - 1;
325
+ continue;
326
+ }
327
+ if (ch === '\n' && pending.length) {
328
+ i = skipBodies(text, i + 1, pending) - 1;
329
+ pending.length = 0;
330
+ word = '';
331
+ if (!quotedSubst) endCommand();
332
+ continue;
333
+ }
334
+ if (quotedSubst) {
335
+ token += ch;
336
+ open = true;
337
+ // A substitution inside double quotes stands where one word does, so its blanks and its
338
+ // operators divide no commands. They still divide its words, which is what places a `<<`.
339
+ if (ch === ' ' || ch === '\t' || ch === '\n' || OPERATORS.includes(ch)) word = '';
340
+ else word += ch;
341
+ continue;
342
+ }
343
+ if (ch === ' ' || ch === '\t' || ch === '\r') {
344
+ endToken();
345
+ continue;
346
+ }
347
+ if (OPERATORS.includes(text.slice(i, i + 2))) {
348
+ endCommand();
349
+ i++;
350
+ continue;
351
+ }
352
+ if (OPERATORS.includes(ch)) {
353
+ endCommand();
354
+ continue;
355
+ }
356
+
357
+ add(ch);
358
+ }
359
+
360
+ if (quote) throw new Unreadable('the command has an unbalanced quote');
361
+ if (suspended.length) throw new Unreadable('the command has an unclosed command substitution');
362
+ if (pending.length) throw new Unreadable('a here-document has no closing delimiter');
363
+ endCommand();
364
+ return commands;
365
+ }
366
+
367
+ const basename = (word) => word.split(/[\\/]/).pop();
368
+
369
+ /** Git's options that sit before the subcommand and swallow the word after them. */
370
+ const GIT_GLOBALS_TAKING_A_VALUE = new Set([
371
+ '-c',
372
+ '-C',
373
+ '--config-env',
374
+ '--exec-path',
375
+ '--git-dir',
376
+ '--namespace',
377
+ '--work-tree',
378
+ ]);
379
+
380
+ /** Each subcommand's options that swallow the word after them, so a value is never read as a flag. */
381
+ const VALUE_OPTIONS = {
382
+ commit: {
383
+ long: new Set([
384
+ '--author',
385
+ '--cleanup',
386
+ '--date',
387
+ '--file',
388
+ '--fixup',
389
+ '--message',
390
+ '--pathspec-from-file',
391
+ '--reedit-message',
392
+ '--reuse-message',
393
+ '--squash',
394
+ '--template',
395
+ '--trailer',
396
+ ]),
397
+ short: new Set(['m', 'F', 'C', 'c', 't']),
398
+ },
399
+ push: {
400
+ long: new Set(['--exec', '--push-option', '--receive-pack', '--repo']),
401
+ short: new Set(['o']),
402
+ },
403
+ branch: {
404
+ long: new Set([
405
+ '--contains',
406
+ '--format',
407
+ '--merged',
408
+ '--no-contains',
409
+ '--no-merged',
410
+ '--points-at',
411
+ '--set-upstream-to',
412
+ '--sort',
413
+ ]),
414
+ short: new Set(['u']),
415
+ },
416
+ };
417
+
418
+ const isCluster = (token) => /^-[A-Za-z]+$/.test(token);
419
+ const longName = (token) => token.split('=')[0];
420
+
421
+ /**
422
+ * Walk one git invocation, handing each option and each operand to the caller. Options after a bare
423
+ * `--` are operands, and a value is never offered as an option.
424
+ */
425
+ function walkArguments(words, subcommand, onOption, onOperand) {
426
+ const values = VALUE_OPTIONS[subcommand] ?? { long: new Set(), short: new Set() };
427
+ let operandsOnly = false;
428
+
429
+ for (let i = 0; i < words.length; i++) {
430
+ const word = words[i];
431
+
432
+ if (operandsOnly || word === '-' || !word.startsWith('-')) {
433
+ onOperand(word);
434
+ continue;
435
+ }
436
+ if (word === '--') {
437
+ operandsOnly = true;
438
+ continue;
439
+ }
440
+
441
+ if (word.startsWith('--')) {
442
+ onOption(longName(word), word);
443
+ if (values.long.has(word)) i++;
444
+ continue;
445
+ }
446
+
447
+ onOption(word, word);
448
+ if (isCluster(word)) {
449
+ const letters = word.slice(1);
450
+ for (let n = 0; n < letters.length; n++) {
451
+ onOption(`-${letters[n]}`, word);
452
+ if (!values.short.has(letters[n])) continue;
453
+ // Everything after an option that takes a value is that value rather than more flags.
454
+ // `-m"a message"` lexes to one token, and the letters of the message are not options.
455
+ // Where the option is the last letter, the value is the word after it instead.
456
+ if (n === letters.length - 1) i++;
457
+ break;
458
+ }
459
+ }
460
+ }
461
+ }
462
+
463
+ const RESERVED = {
464
+ commit: (option) =>
465
+ // -n is git's own short spelling of --no-verify on commit. On push it means --dry-run, which is
466
+ // why this rule is bound to the subcommand rather than to the flag.
467
+ option === '--no-verify' || option === '-n'
468
+ ? 'a commit that skips the hooks (--no-verify)'
469
+ : null,
470
+ push: (option) =>
471
+ option === '--no-verify'
472
+ ? 'a push that skips the hooks (--no-verify)'
473
+ : option === '--force' || option === '-f' || longName(option) === '--force-with-lease' || longName(option) === '--force-if-includes'
474
+ ? 'a force push'
475
+ : option === '--delete' || option === '-d'
476
+ ? 'deleting a remote branch'
477
+ : null,
478
+ branch: (option) =>
479
+ option === '--delete' || option === '-d' || option === '-D'
480
+ ? 'deleting a branch'
481
+ : null,
482
+ };
483
+
484
+ const PUSH_RESERVED_OPERAND = (word) =>
485
+ word.startsWith('+')
486
+ ? 'a force push (the +refspec form)'
487
+ : word.startsWith(':') && word.length > 1
488
+ ? 'deleting a remote branch (the :branch form)'
489
+ : null;
490
+
491
+ /** Refuse a refspec that spells the local remote's default branch as its destination. */
492
+ function literalDefaultPush(words, cwd) {
493
+ let remote = null;
494
+ const operands = [];
495
+ walkArguments(
496
+ words,
497
+ 'push',
498
+ (option, raw) => {
499
+ if (option === '--repo' && raw.startsWith('--repo=')) remote = raw.slice('--repo='.length);
500
+ },
501
+ (operand) => operands.push(operand),
502
+ );
503
+ remote ??= operands.shift();
504
+ if (!remote) return null;
505
+
506
+ const named = spawnSync('git', ['symbolic-ref', '-q', `refs/remotes/${remote}/HEAD`], {
507
+ cwd, encoding: 'utf8',
508
+ });
509
+ const prefix = `refs/remotes/${remote}/`;
510
+ const answer = named.stdout?.trim();
511
+ if (named.status !== 0 || !answer?.startsWith(prefix)) return null;
512
+ const branch = answer.slice(prefix.length);
513
+ if (!branch) return null;
514
+
515
+ for (const refspec of operands) {
516
+ const colon = refspec.lastIndexOf(':');
517
+ const destination = colon === -1 ? refspec : refspec.slice(colon + 1);
518
+ if (destination === branch || destination === `refs/heads/${branch}`) {
519
+ return `a push to the default branch ${branch}`;
520
+ }
521
+ }
522
+ return null;
523
+ }
524
+
525
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
526
+
527
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
528
+
529
+ // A shell keyword is a word, not an operator, so `commandsIn` leaves it as the first word of the
530
+ // command bash goes on to run and puts the program in the word after it. `{ git push --force; }`
531
+ // is one command whose words are `{`, `git`, `push`, `--force`, and a rule reading word one reads
532
+ // the brace. So the words below are stepped over to reach the program, the same way an
533
+ // environment assignment already is.
534
+ //
535
+ // Stepping over a word can only surface a program this gate was not reading, so it adds refusals
536
+ // and takes none away. The cost is the other direction: a word stepped over where bash reads no
537
+ // command is a refusal bash would not have earned, which is why the list is bash's reserved words
538
+ // rather than a guess, and why each entry was run under bash with `git` shadowed by a marker
539
+ // before it was added.
540
+
541
+ /**
542
+ * Bash's reserved words a command may follow directly. Absent, and why: `esac`, `fi`, `done` and
543
+ * `}` end a construct, so a command after one needs an operator first and is already word one;
544
+ * `for` and `select` are followed by a name rather than a command, and `for x in git push --force`
545
+ * is a word list bash runs no git from; `[[` opens a conditional bash runs no command inside. Each
546
+ * of those was measured rather than reasoned about, and the pull request reports what bash ran.
547
+ *
548
+ * `time` is absent for a different reason: it is also the name of a program, so it sits in
549
+ * `PREFIX_PROGRAMS` below, which reaches every spelling this list would — `time -p`, `time --` and
550
+ * `time { … }` alike — and also `/usr/bin/time`, which this list cannot, because it matches a whole
551
+ * word where the prefix list matches a basename. Holding it in both left one of them dead.
552
+ */
553
+ const KEYWORDS_A_COMMAND_MAY_FOLLOW = new Set([
554
+ '!',
555
+ '{',
556
+ 'coproc',
557
+ 'do',
558
+ 'elif',
559
+ 'else',
560
+ 'function',
561
+ 'if',
562
+ 'in',
563
+ 'then',
564
+ 'until',
565
+ 'while',
566
+ ]);
567
+
568
+ /**
569
+ * A redirection where bash reads a command's words. Bash reads one before the program as freely as
570
+ * after it, so `>out git push --force` runs git and the program sits after the redirection. The
571
+ * descriptor is a number or, in bash, a name in braces; the target is in this word or the next one,
572
+ * which is what says how many words to step over.
573
+ *
574
+ * The operators are ordered longest first. A two-character one read as its first character would
575
+ * take `>| out` for a redirection whose target is already in this word and stop before `out`.
576
+ *
577
+ * `<<` and `<<-` are absent because only their length could matter here and neither can reach it:
578
+ * the lexer above never leaves a bare `<<` or `<<-` token, since it reads the delimiter into the
579
+ * same word and refuses a here-document that names none. A `<<EOF` word is matched by `<` and
580
+ * stepped over as a word carrying its own target, which is what it is.
581
+ */
582
+ const REDIRECTION = /^(\{[A-Za-z_][A-Za-z0-9_]*\}|\d*)(<<<|<&|>&|<>|>>|>\||<|>)/;
583
+
584
+ /**
585
+ * Step over the words bash's grammar puts between the start of a command and the program it runs:
586
+ * assignments, reserved words, redirections, and the `case` pattern or `NAME()` header that
587
+ * introduces a body. Returns the words from the program on, which may be none.
588
+ *
589
+ * Everything here is bash's grammar. A program that runs another program named in its arguments is
590
+ * not — `env`, `nohup` and the rest are handled where the program is read, because each has its
591
+ * own option grammar and none of them is the shell's.
592
+ */
593
+ function programWords(given) {
594
+ let words = given;
595
+ for (;;) {
596
+ let start = 0;
597
+ while (start < words.length && ASSIGNMENT.test(words[start])) start++;
598
+ words = words.slice(start);
599
+ if (!words.length) return words;
600
+ const first = words[0];
601
+
602
+ if (KEYWORDS_A_COMMAND_MAY_FOLLOW.has(first)) {
603
+ words = words.slice(1);
604
+ // `coproc NAME compound` and `function NAME compound` name the thing before its body, so
605
+ // the body's first command is a word further on. Bash reads a NAME only before a compound
606
+ // command: in `coproc c git push --force` the `c` is the program, and bash runs `c`.
607
+ if ((first === 'coproc' || first === 'function') && words[1] === '{') words = words.slice(1);
608
+ continue;
609
+ }
610
+ // `case WORD in` is a header that runs nothing, and a pattern ends at the `)` that introduces
611
+ // its body — on the same line as the body's first command, because `)` is no operator here.
612
+ // The scan runs to the first word ending in `)` rather than testing one word, because the
613
+ // pattern may be several words and may itself hold a `)`.
614
+ if (first === 'case') {
615
+ const pattern = words.findIndex((word, at) => at > 0 && word.endsWith(')'));
616
+ if (pattern === -1) return [];
617
+ words = words.slice(pattern + 1);
618
+ continue;
619
+ }
620
+ // A word ending in `)` where a command may begin is a later `case` branch's pattern, or the
621
+ // `NAME()` header of a function definition. Only the first word is tested: a scan further
622
+ // along would step over `git push --force '--x)'` and reach nothing.
623
+ if (first.endsWith(')')) {
624
+ words = words.slice(1);
625
+ continue;
626
+ }
627
+ // The same pattern with the `)` set off by a blank, which lexes as its own word. Only the
628
+ // second word is read, so a `)` further along a command is not a pattern: `echo ')' hello`,
629
+ // `grep ')'` and `sed 's/x/)/'` are all left alone. The cost is `echo ')' git push --force`,
630
+ // where the second word lexes to exactly `)` once its quoting is removed and this steps over
631
+ // both — a refusal of text bash runs `echo` for, and the only one this rule costs.
632
+ if (words[1] === ')') {
633
+ words = words.slice(2);
634
+ continue;
635
+ }
636
+ // A redirection, which may be written before the program as freely as after it. Written
637
+ // `>out` the target is in this word; written `> out` it is the next one.
638
+ const redirection = REDIRECTION.exec(first);
639
+ if (redirection) {
640
+ words = words.slice(redirection[0].length === first.length ? 2 : 1);
641
+ continue;
642
+ }
643
+ return words;
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Programs that run a command named in their arguments. Stepping over one is not enough, because
649
+ * each has its own options and some take an operand before the command — `timeout 5 git …`,
650
+ * `nice -n 10 git …`, `env -u FOO git …`. Rather than carry an option grammar per program, every
651
+ * word after the prefix is read as a possible start of a command.
652
+ *
653
+ * That reads more words than bash runs, which can only add a refusal: it objects only where the
654
+ * words from one of them on spell a reserved command, so `nohup echo git status` and
655
+ * `command -v git` are untouched while `nohup git push --force` is refused. What it costs is a
656
+ * command whose arguments spell a reserved git command that bash passes to something else, as
657
+ * `nohup echo git push --force` does.
658
+ *
659
+ * `env` was the one name here before this list, and stepping over it was defeated by its own
660
+ * options. These are programs rather than shell grammar, so which of them exists is a fact about
661
+ * the host: a name absent from the host runs nothing, and the pull request records which were
662
+ * watched running git here and which bash reported absent.
663
+ *
664
+ * **This is an enumeration, so a prefix program not named here is fail-open**: the gate reads its
665
+ * first word, finds a name it does not know, and steps aside while bash goes on to run the git
666
+ * command in its arguments. Nothing in the rule closes the family — the names close themselves.
667
+ * A name that belongs here is added here, and no host's list of such programs is knowable from
668
+ * this file.
669
+ */
670
+ const PREFIX_PROGRAMS = new Set([
671
+ 'chrt',
672
+ 'command',
673
+ 'doas',
674
+ 'env',
675
+ 'exec',
676
+ 'flock',
677
+ 'ionice',
678
+ 'nice',
679
+ 'nohup',
680
+ 'setsid',
681
+ 'stdbuf',
682
+ 'sudo',
683
+ 'taskset',
684
+ 'time',
685
+ 'timeout',
686
+ 'unbuffer',
687
+ 'xargs',
688
+ ]);
689
+
690
+ /**
691
+ * Options of programs on `PREFIX_PROGRAMS` that carry a **whole command inside one word**. The
692
+ * prefix scan reads every word after the prefix looking for a program, so a command written inside
693
+ * one of those words is a word that is no program and the scan reaches nothing. `env -S` splits the
694
+ * word itself; `flock -c` and `sudo -s` / `-i` hand it to a shell, which is what `sudo`'s manual
695
+ * says of both its flags: if a command is specified, it is passed to the shell for execution via
696
+ * the shell's `-c` option.
697
+ *
698
+ * `letter` matches the short option, allowing for the flags it may sit behind in a cluster; `name`
699
+ * is the long one without its dashes. A program with more than one such option is read once per
700
+ * option, because the options are independent.
701
+ */
702
+ const COMMANDS_CARRIED_IN_A_WORD = new Map([
703
+ ['env', [{ letter: /^-[A-Za-z0-9]*S/, name: 'split-string' }]],
704
+ ['flock', [{ letter: /^-[A-Za-z0-9]*c/, name: 'command' }]],
705
+ ['sudo', [
706
+ { letter: /^-[A-Za-z0-9]*s/, name: 'shell' },
707
+ { letter: /^-[A-Za-z0-9]*i/, name: 'login' },
708
+ ]],
709
+ ]);
710
+
711
+ /**
712
+ * Every text that option can carry, in the order the words give them.
713
+ *
714
+ * The text may be written in the option's own word — `-S…` and `--split-string=…` — and it may be
715
+ * a word after it: `-S …` and `--split-string …` put it in the next one, and `sudo`'s flags take no
716
+ * argument at all, so the command is an operand and which operand depends on the options between
717
+ * the flag and it. **So every word after the option is read, and every match is read rather than
718
+ * the first.** That reads more words than any of these programs runs, which can only add a
719
+ * refusal — it objects only where the words from one of them on spell a reserved command — and it
720
+ * buys the one thing this host cannot check: nothing here has to know where a program stops
721
+ * parsing options, or which of two `-c` words it would take. `env` takes the first `-S`, which is
722
+ * measured; what `flock` takes is not, and the pull request says which is which.
723
+ *
724
+ * **A long option is matched by any non-empty prefix of its name**, because these programs parse
725
+ * with `getopt_long`, which resolves an unambiguous abbreviation to the option it abbreviates. So
726
+ * `--s=` is `env`'s `--split-string=`, `split-string` being its only long option beginning with
727
+ * `s`, and `--com=` is `flock`'s `--command=`. Which abbreviations are *unambiguous* is the
728
+ * program's own question and is not asked here: a prefix the program would reject as ambiguous is
729
+ * read as this option anyway, which can only add a refusal, and only to text that spells a
730
+ * reserved git command. So can a cluster whose earlier letter takes a value — `-uS` unsets a
731
+ * variable named `S` — for the same reason.
732
+ *
733
+ * The name must be non-empty, because every name begins with the empty string: match a bare `--`
734
+ * and a real option further along goes unread, which is a narrowing rather than a widening.
735
+ */
736
+ function commandsCarriedInAWord(words, option) {
737
+ const texts = [];
738
+ for (let at = 1; at < words.length; at++) {
739
+ const word = words[at];
740
+ let inTheWord;
741
+ if (word.startsWith('--')) {
742
+ const equals = word.indexOf('=');
743
+ const written = equals === -1 ? word.slice(2) : word.slice(2, equals);
744
+ if (written.length && option.name.startsWith(written)) {
745
+ inTheWord = equals === -1 ? '' : word.slice(equals + 1);
746
+ }
747
+ }
748
+ if (inTheWord === undefined) {
749
+ const short = option.letter.exec(word);
750
+ if (short) inTheWord = word.slice(short[0].length);
751
+ }
752
+ if (inTheWord === undefined) continue;
753
+ if (inTheWord !== '') texts.push(inTheWord);
754
+ texts.push(...words.slice(at + 1));
755
+ }
756
+ return texts;
757
+ }
758
+
759
+ /** Inspect one command. Returns the reason to refuse, or null. */
760
+ function objectionTo(given, depth, cwd) {
761
+ // A command may carry environment assignments and shell keywords before the program it runs:
762
+ // `GIT_AUTHOR_DATE=… git commit …` and `{ git push --force; }` both run git, and neither has it
763
+ // as word one.
764
+ const words = programWords(given);
765
+ if (!words.length) return null;
766
+
767
+ // A shell asked to run a command string is that command string; look inside it once.
768
+ const program = basename(words[0]);
769
+ if (SHELLS.has(program) && depth < 2) {
770
+ // -c may be written in a cluster, as `bash -lc "…"`.
771
+ const flag = words.findIndex((word) => word === '-c' || (isCluster(word) && word.includes('c')));
772
+ const script = flag === -1 ? undefined : words[flag + 1];
773
+ if (script !== undefined) {
774
+ for (const inner of commandsIn(script)) {
775
+ const objection = objectionTo(inner, depth + 1);
776
+ if (objection) return objection;
777
+ }
778
+ }
779
+ return null;
780
+ }
781
+
782
+ // `eval` joins its arguments with a blank and runs the result as shell text, so no one word is
783
+ // the command it runs and the text is re-read the way a shell's `-c` argument is.
784
+ if (program === 'eval' && depth < 2) {
785
+ for (const inner of commandsIn(words.slice(1).join(' '))) {
786
+ const objection = objectionTo(inner, depth + 1);
787
+ if (objection) return objection;
788
+ }
789
+ return null;
790
+ }
791
+
792
+ // `env -S`, `flock -c` and `sudo -s` / `-i` carry the whole command inside one word, so the scan
793
+ // below reads a word that is no program. Each such word's text is re-read instead, the way a
794
+ // shell's `-c` argument and `eval`'s joined arguments already are. The depth is passed on
795
+ // unchanged for the reason the prefix scan below passes it on: none of the three is a shell, and
796
+ // `env -S'bash -c "…"'` has to reach the script. There is no early return, because all three are
797
+ // also ordinary prefixes and `env -u FOO git push --force` is reached by the scan.
798
+ for (const option of COMMANDS_CARRIED_IN_A_WORD.get(program) ?? []) {
799
+ for (const text of commandsCarriedInAWord(words, option)) {
800
+ for (const inner of commandsIn(text)) {
801
+ const objection = objectionTo(inner, depth);
802
+ if (objection) return objection;
803
+ }
804
+ }
805
+ }
806
+
807
+ // A program that runs a command named in its arguments. Every word after it is read as a
808
+ // possible command, and each read is of a strictly shorter list, so a chain of prefixes ends.
809
+ // The depth is passed on unchanged, because a prefix is not a shell and must not spend the
810
+ // budget for looking inside one: `sudo bash -c '…'` has to reach the script.
811
+ if (PREFIX_PROGRAMS.has(program)) {
812
+ for (let at = 1; at < words.length; at++) {
813
+ const objection = objectionTo(words.slice(at), depth);
814
+ if (objection) return objection;
815
+ }
816
+ return null;
817
+ }
818
+
819
+ if (program !== 'git' && program !== 'git.exe') return null;
820
+
821
+ // Step over git's own options to reach the subcommand, and read the config it sets on the way.
822
+ let i = 1;
823
+ let subcommand = null;
824
+ let literalCwd = given[0] === words[0] ? cwd : null;
825
+ for (; i < words.length; i++) {
826
+ const word = words[i];
827
+ if (!word.startsWith('-')) {
828
+ subcommand = word;
829
+ i++;
830
+ break;
831
+ }
832
+ literalCwd = null;
833
+ if (word === '-c' || word === '--config-env') {
834
+ const setting = words[i + 1] ?? '';
835
+ if (/^core\.hooksPath\s*=/i.test(setting)) return 'turning the repository hooks off (core.hooksPath)';
836
+ i++;
837
+ continue;
838
+ }
839
+ // git documents --config-env=<name>=<envvar>, so the setting is inside this one word.
840
+ if (word.startsWith('--config-env=')) {
841
+ if (/^core\.hooksPath\s*=/i.test(word.slice('--config-env='.length))) {
842
+ return 'turning the repository hooks off (core.hooksPath)';
843
+ }
844
+ continue;
845
+ }
846
+ if (/^--git-dir=|^--work-tree=|^--namespace=|^--exec-path=/.test(word)) continue;
847
+ if (GIT_GLOBALS_TAKING_A_VALUE.has(word)) i++;
848
+ }
849
+
850
+ if (subcommand === null) return null;
851
+ const rule = RESERVED[subcommand];
852
+ if (!rule) return null;
853
+
854
+ let objection = null;
855
+ walkArguments(
856
+ words.slice(i),
857
+ subcommand,
858
+ (option) => {
859
+ objection ??= rule(option);
860
+ },
861
+ (operand) => {
862
+ if (subcommand === 'push') objection ??= PUSH_RESERVED_OPERAND(operand);
863
+ },
864
+ );
865
+ if (!objection && subcommand === 'push' && literalCwd) {
866
+ objection = literalDefaultPush(words.slice(i), literalCwd);
867
+ }
868
+ return objection;
869
+ }
870
+
871
+ function main() {
872
+ let payload;
873
+ try {
874
+ payload = JSON.parse(readFileSync(0, 'utf8'));
875
+ } catch {
876
+ refuse('This hook could not read what it was asked to rule on, so it refused.');
877
+ }
878
+
879
+ if (payload.tool_name !== 'Bash') stepAside();
880
+
881
+ const command = payload?.tool_input?.command;
882
+ if (typeof command !== 'string') {
883
+ refuse('This hook could not find the command to rule on, so it refused.');
884
+ }
885
+
886
+ let commands;
887
+ try {
888
+ commands = commandsIn(command);
889
+ } catch (error) {
890
+ refuse(`This hook could not read the command (${error.message}), so it refused.`);
891
+ }
892
+
893
+ for (const words of commands) {
894
+ const objection = objectionTo(words, 0, commands.length === 1 ? payload.cwd : null);
895
+ if (objection) {
896
+ refuse(
897
+ `AGENTS.md reserves this to the owner: ${objection}. Ask, rather than working around it.`,
898
+ );
899
+ }
900
+ }
901
+
902
+ stepAside();
903
+ }
904
+
905
+ try {
906
+ main();
907
+ } catch (error) {
908
+ refuse(`This hook failed (${error?.message ?? error}), so it refused rather than let the command run.`);
909
+ }