slicekit 0.0.1 → 0.1.2

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -3
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +21 -4
  5. package/src/adapters/githost/errors.js +17 -0
  6. package/src/adapters/githost/fixture.js +136 -0
  7. package/src/adapters/githost/gh-json.js +99 -0
  8. package/src/adapters/githost/github.js +127 -0
  9. package/src/adapters/githost/index.js +12 -0
  10. package/src/adapters/tracker/errors.js +53 -0
  11. package/src/adapters/tracker/fixture.js +71 -0
  12. package/src/adapters/tracker/github-issues.js +65 -0
  13. package/src/adapters/tracker/index.js +14 -0
  14. package/src/baseline.js +109 -0
  15. package/src/build/commit.js +201 -0
  16. package/src/build/decline.js +81 -0
  17. package/src/build/finish.js +155 -0
  18. package/src/build/order.js +158 -0
  19. package/src/build/overlap.js +173 -0
  20. package/src/build/parallel.js +50 -0
  21. package/src/build/pr.js +263 -0
  22. package/src/build/record.js +28 -0
  23. package/src/build/red.js +207 -0
  24. package/src/build/review.js +123 -0
  25. package/src/build/sync.js +47 -0
  26. package/src/build/verdict.js +410 -0
  27. package/src/build/worktree.js +169 -0
  28. package/src/check/ci-event.js +52 -0
  29. package/src/check/context.js +129 -0
  30. package/src/check/index.js +140 -0
  31. package/src/check/rules/.gitkeep +0 -0
  32. package/src/check/rules/ci-body.js +22 -0
  33. package/src/check/rules/ci-title.js +43 -0
  34. package/src/check/rules/citations.js +224 -0
  35. package/src/check/rules/commands.js +146 -0
  36. package/src/check/rules/coverage.js +248 -0
  37. package/src/check/rules/hooks.js +58 -0
  38. package/src/check/rules/journal.js +17 -0
  39. package/src/check/rules/layout.js +56 -0
  40. package/src/check/rules/managed.js +31 -0
  41. package/src/check/rules/queue.js +106 -0
  42. package/src/check/rules/references.js +249 -0
  43. package/src/check/rules/style.js +177 -0
  44. package/src/check/rules/trailer.js +67 -0
  45. package/src/cli/baseline.js +66 -0
  46. package/src/cli/branch.js +86 -0
  47. package/src/cli/build.js +239 -0
  48. package/src/cli/check.js +40 -0
  49. package/src/cli/decide.js +59 -0
  50. package/src/cli/gaps.js +73 -0
  51. package/src/cli/hook.js +28 -0
  52. package/src/cli/index.js +83 -0
  53. package/src/cli/init.js +96 -0
  54. package/src/cli/instructions.js +63 -0
  55. package/src/cli/intake.js +107 -0
  56. package/src/cli/journal.js +82 -0
  57. package/src/cli/plan.js +29 -0
  58. package/src/cli/pr.js +83 -0
  59. package/src/cli/process.js +59 -0
  60. package/src/cli/ready-label.js +119 -0
  61. package/src/cli/review.js +64 -0
  62. package/src/cli/spec.js +31 -0
  63. package/src/cli/stage.js +37 -0
  64. package/src/cli/state.js +106 -0
  65. package/src/cli/status.js +108 -0
  66. package/src/cli/update.js +62 -0
  67. package/src/cli/workflow.js +48 -0
  68. package/src/config.js +203 -0
  69. package/src/decisions.js +289 -0
  70. package/src/evidence.js +27 -0
  71. package/src/fs.js +38 -0
  72. package/src/gaps.js +271 -0
  73. package/src/git.js +209 -0
  74. package/src/githooks.js +37 -0
  75. package/src/hook-cli.js +63 -0
  76. package/src/hooks/io.js +205 -0
  77. package/src/hooks/paths.js +82 -0
  78. package/src/hooks/pre-bash.js +715 -0
  79. package/src/hooks/pre-compact.js +139 -0
  80. package/src/hooks/pre-edit.js +170 -0
  81. package/src/hooks/session-end.js +118 -0
  82. package/src/hooks/session-start.js +209 -0
  83. package/src/hooks/shapes.js +103 -0
  84. package/src/hooks/stop.js +37 -0
  85. package/src/hooks/subagent-marker.js +88 -0
  86. package/src/hooks/subagent-start.js +100 -0
  87. package/src/hooks/subagent-stop.js +106 -0
  88. package/src/ids.js +43 -0
  89. package/src/init.js +281 -0
  90. package/src/instructions.js +235 -0
  91. package/src/intake.js +409 -0
  92. package/src/journal.js +326 -0
  93. package/src/lock.js +35 -0
  94. package/src/markdown.js +155 -0
  95. package/src/paths.js +33 -0
  96. package/src/plan.js +25 -0
  97. package/src/pr.js +73 -0
  98. package/src/prbody.js +266 -0
  99. package/src/ready-label.js +107 -0
  100. package/src/redact.js +33 -0
  101. package/src/render/compare.js +23 -0
  102. package/src/render/entry.js +101 -0
  103. package/src/render/index.js +27 -0
  104. package/src/render/managed.js +128 -0
  105. package/src/render/manifest.js +24 -0
  106. package/src/render/settings.js +76 -0
  107. package/src/render/update.js +151 -0
  108. package/src/slicefile.js +173 -0
  109. package/src/spec-verify.js +58 -0
  110. package/src/stage.js +325 -0
  111. package/src/state/build.js +156 -0
  112. package/src/state/covers.js +58 -0
  113. package/src/state/index.js +191 -0
  114. package/src/state/sync.js +64 -0
  115. package/src/state/transitions.js +282 -0
  116. package/src/verdict.js +203 -0
  117. package/src/which.js +37 -0
  118. package/src/workflow.js +177 -0
  119. package/src/worktrees.js +68 -0
  120. package/templates/claude-code/agents/auditor.md +7 -0
  121. package/templates/claude-code/agents/designer.md +7 -0
  122. package/templates/claude-code/agents/developer.md +7 -0
  123. package/templates/claude-code/agents/fixer.md +7 -0
  124. package/templates/claude-code/agents/ops.md +7 -0
  125. package/templates/claude-code/agents/reviewer.md +7 -0
  126. package/templates/claude-code/commands/slicekit-audit.md +7 -0
  127. package/templates/claude-code/commands/slicekit-build.md +7 -0
  128. package/templates/claude-code/commands/slicekit-gaps.md +6 -0
  129. package/templates/claude-code/commands/slicekit-intake.md +7 -0
  130. package/templates/claude-code/commands/slicekit-ops.md +7 -0
  131. package/templates/claude-code/commands/slicekit-plan.md +6 -0
  132. package/templates/claude-code/commands/slicekit-release.md +7 -0
  133. package/templates/claude-code/commands/slicekit-review.md +7 -0
  134. package/templates/claude-code/commands/slicekit-specify.md +6 -0
  135. package/templates/claude-code/commands/slicekit.md +7 -0
  136. package/templates/claude-code/hooks.json +90 -0
  137. package/templates/claude-code/manifest.json +171 -0
  138. package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
  139. package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
  140. package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
  141. package/templates/docs/BUILD.md +5 -0
  142. package/templates/docs/decisions.md +15 -0
  143. package/templates/docs/intake/.keep +0 -0
  144. package/templates/docs/observability.md +25 -0
  145. package/templates/docs/phases/.keep +0 -0
  146. package/templates/docs/platform.md +25 -0
  147. package/templates/docs/releases/.keep +0 -0
  148. package/templates/docs/runbook.md +21 -0
  149. package/templates/docs/spec/00-overview.md +8 -0
  150. package/templates/docs/spec/contracts/.keep +0 -0
  151. package/templates/docs/spec/gaps.md +6 -0
  152. package/templates/docs/spec/stack.md +3 -0
  153. package/templates/githooks/pre-commit +79 -0
  154. package/templates/githooks/pre-merge-commit +79 -0
  155. package/templates/githooks/prepare-commit-msg +110 -0
  156. package/templates/instructions/agents/auditor.md +33 -0
  157. package/templates/instructions/agents/designer.md +21 -0
  158. package/templates/instructions/agents/developer.md +49 -0
  159. package/templates/instructions/agents/fixer.md +41 -0
  160. package/templates/instructions/agents/ops.md +21 -0
  161. package/templates/instructions/agents/reviewer.md +63 -0
  162. package/templates/instructions/commands/build.md +234 -0
  163. package/templates/instructions/commands/gaps.md +65 -0
  164. package/templates/instructions/commands/intake.md +90 -0
  165. package/templates/instructions/commands/plan.md +60 -0
  166. package/templates/instructions/commands/review.md +117 -0
  167. package/templates/instructions/commands/specify.md +49 -0
  168. package/templates/style.json +11 -0
  169. package/templates/workflow/pins.json +6 -0
  170. package/templates/workflow/slicekit.yml +110 -0
@@ -0,0 +1,715 @@
1
+ // pre-bash (REQ-3.2, REQ-2.1, REQ-1.2): the PreToolUse guard on Bash. Fails closed through io.js.
2
+ //
3
+ // Rules in order, first deny wins: (1) commit on a protected branch; (2) push to a protected branch;
4
+ // (3) any force push; (4) a commit that changes a frozen intake snapshot; (5) from a subagent: commit,
5
+ // push, merge, pull, rebase, cherry-pick, revert, am, tag (other than listing), `gh pr` writes or a
6
+ // non-GET `gh api`; (6) a command matching cfg.destructive.
7
+ //
8
+ // "From a subagent" means the input carries a non-empty `agent_id`: Claude Code sets it on every tool
9
+ // call made inside a subagent and never in the main session (an `--agent` session has `agent_type`
10
+ // alone). The subagent marker is not read here: it is per session, so it cannot tell the main session's
11
+ // own commit from its subagent's.
12
+ //
13
+ // Limits: this reads the command as a shell would on its surface. It splits on operators outside
14
+ // quotes, treats here-document bodies as data, strips shell keywords, env prefixes and wrappers
15
+ // (command/exec/sudo/env/timeout/nice/xargs/...), follows `cd`, `pushd`, `git -C`, `git checkout` and
16
+ // `bash -c "..."`. A directory it cannot resolve makes a commit or push refuse rather than pass.
17
+ // It does not expand variables, aliases, eval, functions or encoded payloads: deliberate obfuscation
18
+ // gets through, and the git hooks (S-06's .githooks) are the backstop for commits and pushes.
19
+ // Known gaps: `--git-dir` / `GIT_DIR` pointing at another repository are not followed (the branch is
20
+ // read from the shell's directory); a command substitution inside double quotes (`echo "$(git ...)"`)
21
+ // is not split out; `echo '...' | bash` (a piped string, not a here-document) and a shell function
22
+ // (`function f { ...; }; f`) are not followed; the default destructive list misses `rm -fr /`
23
+ // spellings and absolute paths inside the worktree; `gh api` with `-f`, `-F` or `--input` and no `-X`
24
+ // is an implicit POST that a subagent may still send; SQL read from a file (`psql -f f.sql`,
25
+ // `cat f.sql | psql`) is not matched against the destructive list.
26
+ import fs from 'node:fs';
27
+ import os from 'node:os';
28
+ import path from 'node:path';
29
+ import { compileDestructive } from '../config.js';
30
+ import { git, GitError, currentBranch } from '../git.js';
31
+ import { kitPaths } from '../paths.js';
32
+ import { allow, deny } from './io.js';
33
+ import { fromGitBash, real, toPosix } from './paths.js';
34
+
35
+ // ---- tokenising ----
36
+
37
+ // Unquoted, each of these ends a command: && || ; | & newline, subshell parens and backticks.
38
+ const SEPARATORS = new Set([';', '\n', '|', '&', '(', ')', '`']);
39
+ const DELIM_END = /[\s;&|()<>`]/;
40
+
41
+ // -> [{toks: [{v, b}], heredocs: [string], stdin?}]: one entry per simple command. `v` is the word with
42
+ // quotes removed; `b` is only its unquoted characters. Here-document bodies are data, attached to the
43
+ // command that opened them; `stdin` is the command piped into this one.
44
+ function lex(command) {
45
+ const s = String(command);
46
+ const out = [];
47
+ let cur = { toks: [], heredocs: [] };
48
+ let word = null;
49
+ let bare = '';
50
+ let pending = [];
51
+ const add = (text, quoted) => {
52
+ word = (word ?? '') + text;
53
+ if (!quoted) bare += text;
54
+ };
55
+ const endWord = () => {
56
+ if (word !== null) cur.toks.push({ v: word, b: bare });
57
+ word = null;
58
+ bare = '';
59
+ };
60
+ const endSegment = () => {
61
+ endWord();
62
+ const ended = cur;
63
+ if (cur.toks.length) out.push(cur);
64
+ cur = { toks: [], heredocs: [] };
65
+ return ended;
66
+ };
67
+ let i = 0;
68
+ while (i < s.length) {
69
+ const c = s[i];
70
+ if (c === "'") {
71
+ const j = s.indexOf("'", i + 1);
72
+ const end = j === -1 ? s.length : j;
73
+ add(s.slice(i + 1, end), true);
74
+ i = end + 1;
75
+ } else if (c === '"') {
76
+ let j = i + 1;
77
+ let buf = '';
78
+ while (j < s.length && s[j] !== '"') {
79
+ if (s[j] === '\\' && j + 1 < s.length && '"\\$`\n'.includes(s[j + 1])) {
80
+ buf += s[j + 1];
81
+ j += 2;
82
+ } else {
83
+ buf += s[j];
84
+ j += 1;
85
+ }
86
+ }
87
+ add(buf, true);
88
+ i = j + 1;
89
+ } else if (c === '\\') {
90
+ if (i + 1 < s.length && s[i + 1] !== '\n') add(s[i + 1], false);
91
+ i += 2;
92
+ } else if (c === '<' && s[i + 1] === '<' && s[i + 2] === '<') {
93
+ // A here-string: a redirect, its operand is the next word.
94
+ endWord();
95
+ cur.toks.push({ v: '<<<', b: '<<<' });
96
+ i += 3;
97
+ } else if (c === '(' && s[i + 1] === '(') {
98
+ // Arithmetic, `((...))` or `$((...))`: one word, never a here-document or a subshell.
99
+ let depth = 0;
100
+ let j = i;
101
+ for (; j < s.length; j++) {
102
+ if (s[j] === '(') depth += 1;
103
+ else if (s[j] === ')') {
104
+ depth -= 1;
105
+ if (depth === 0) break;
106
+ }
107
+ }
108
+ add(s.slice(i, j + 1), false);
109
+ i = j + 1;
110
+ } else if (c === '<' && s[i + 1] === '<') {
111
+ // A here-document: `<<WORD`, `<<-WORD`, `<<'WORD'`. Its body starts at the next newline.
112
+ endWord();
113
+ let j = i + 2;
114
+ const dash = s[j] === '-';
115
+ if (dash) j += 1;
116
+ while (s[j] === ' ' || s[j] === '\t') j += 1;
117
+ let delim = '';
118
+ while (j < s.length && !DELIM_END.test(s[j])) {
119
+ if (s[j] === "'" || s[j] === '"') {
120
+ const k = s.indexOf(s[j], j + 1);
121
+ const end = k === -1 ? s.length : k;
122
+ delim += s.slice(j + 1, end);
123
+ j = end + 1;
124
+ } else if (s[j] === '\\') {
125
+ delim += s[j + 1] ?? '';
126
+ j += 2;
127
+ } else {
128
+ delim += s[j];
129
+ j += 1;
130
+ }
131
+ }
132
+ if (delim !== '') pending.push({ delim, dash, seg: cur });
133
+ i = j;
134
+ } else if (c === ' ' || c === '\t' || c === '\r') {
135
+ endWord();
136
+ i += 1;
137
+ } else if (SEPARATORS.has(c)) {
138
+ const ended = endSegment();
139
+ if (c === '|' && s[i + 1] === '|') i += 1;
140
+ else if (c === '|') cur.stdin = ended;
141
+ i += 1;
142
+ if (c === '\n' && pending.length) {
143
+ for (const p of pending) {
144
+ const body = [];
145
+ while (i < s.length) {
146
+ const nl = s.indexOf('\n', i);
147
+ const e = nl === -1 ? s.length : nl;
148
+ const line = s.slice(i, e).replace(/\r$/, '');
149
+ i = e + 1;
150
+ if ((p.dash ? line.replace(/^\t+/, '') : line) === p.delim) break;
151
+ body.push(line);
152
+ }
153
+ p.seg.heredocs.push(body.join('\n'));
154
+ }
155
+ pending = [];
156
+ }
157
+ } else if (c === '#' && word === null) {
158
+ while (i < s.length && s[i] !== '\n') i += 1;
159
+ } else {
160
+ add(c, false);
161
+ i += 1;
162
+ }
163
+ }
164
+ endSegment();
165
+ return out;
166
+ }
167
+
168
+ // -> string[][]: one array of words (quotes removed) per simple command.
169
+ export function segments(command) {
170
+ return lex(command).map((seg) => seg.toks.map((t) => t.v));
171
+ }
172
+
173
+ const base = (word) => path.posix.basename(word.replace(/\\/g, '/')).toLowerCase().replace(/\.exe$/, '');
174
+
175
+ // Redirections are not arguments: `> file`, `2>file`, `<in`, `<<< word`.
176
+ function dropRedirects(toks) {
177
+ const out = [];
178
+ for (let k = 0; k < toks.length; k++) {
179
+ const m = /^\d*(<<<|>>?|<|>&|<&|&>)(.*)$/.exec(toks[k].b === toks[k].v ? toks[k].v : '');
180
+ if (!m) out.push(toks[k]);
181
+ else if (m[2] === '') k += 1;
182
+ }
183
+ return out;
184
+ }
185
+
186
+ // Words that only open a construct; the command follows them.
187
+ const KEYWORDS = new Set(['if', 'then', 'elif', 'else', 'do', 'while', 'until', '!', '{']);
188
+ // Wrappers that run the rest of the line as the command: short options that take a separate value,
189
+ // long options that do (without `=`), and how many positionals precede the command.
190
+ const WRAPPERS = {
191
+ command: { short: '', long: [], skip: 0 },
192
+ exec: { short: 'a', long: [], skip: 0 },
193
+ builtin: { short: '', long: [], skip: 0 },
194
+ nohup: { short: '', long: [], skip: 0 },
195
+ time: { short: 'fo', long: ['--format', '--output'], skip: 0 },
196
+ winpty: { short: '', long: [], skip: 0 },
197
+ sudo: { short: 'ugChpDrtUg', long: ['--user', '--group', '--host', '--prompt', '--chdir'], skip: 0 },
198
+ env: { short: 'uCS', long: ['--unset', '--chdir', '--split-string'], skip: 0 },
199
+ timeout: { short: 'sk', long: ['--signal', '--kill-after'], skip: 1 },
200
+ nice: { short: 'n', long: ['--adjustment'], skip: 0 },
201
+ ionice: { short: 'cnpPu', long: ['--class', '--classdata', '--pid', '--pgid', '--uid'], skip: 0 },
202
+ stdbuf: { short: 'ioe', long: ['--input', '--output', '--error'], skip: 0 },
203
+ xargs: {
204
+ short: 'IinPLlEesad',
205
+ long: ['--replace', '--max-args', '--max-procs', '--max-lines', '--eof', '--max-chars', '--arg-file', '--delimiter'],
206
+ skip: 0,
207
+ },
208
+ };
209
+
210
+ // Strip keywords, env assignments and wrappers until the word that is the command.
211
+ function stripPrefixes(toks) {
212
+ let w = dropRedirects(toks);
213
+ for (;;) {
214
+ if (!w.length) return w;
215
+ if (KEYWORDS.has(w[0].v)) {
216
+ w = w.slice(1);
217
+ continue;
218
+ }
219
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0].v)) {
220
+ w = w.slice(1);
221
+ continue;
222
+ }
223
+ const spec = WRAPPERS[base(w[0].v)];
224
+ if (!spec) return w;
225
+ w = w.slice(1);
226
+ while (w.length && w[0].v.startsWith('-') && w[0].v !== '-') {
227
+ const opt = w.shift().v;
228
+ if (opt === '--') break;
229
+ if (opt.startsWith('--')) {
230
+ if (spec.long.includes(opt) && w.length) w.shift();
231
+ } else if (opt.length === 2 && spec.short.includes(opt[1]) && w.length) {
232
+ w.shift();
233
+ }
234
+ }
235
+ w = w.slice(spec.skip);
236
+ }
237
+ }
238
+
239
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh']);
240
+
241
+ // ---- directories ----
242
+
243
+ // A directory the hook cannot resolve is null: commits and pushes there refuse rather than pass.
244
+ function resolveDir(from, target) {
245
+ if (/[$`]/.test(target)) return null;
246
+ let t = target;
247
+ if (t === '~' || t.startsWith('~/')) t = path.join(os.homedir(), t.slice(1));
248
+ else if (t.startsWith('~')) return null;
249
+ t = fromGitBash(t);
250
+ if (from === null && !path.isAbsolute(t)) return null;
251
+ const abs = path.resolve(from ?? '', t);
252
+ try {
253
+ return fs.statSync(abs).isDirectory() ? abs : null;
254
+ } catch {
255
+ return null;
256
+ }
257
+ }
258
+
259
+ // ---- git argument parsing ----
260
+
261
+ const GIT_GLOBAL_VALUE = new Set(['-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--super-prefix']);
262
+
263
+ function parsePush(args) {
264
+ const VALUE = new Set(['--push-option', '--repo', '--receive-pack', '--exec']);
265
+ let force = false;
266
+ let all = false;
267
+ let del = false;
268
+ let endOpts = false;
269
+ const positionals = [];
270
+ for (let k = 0; k < args.length; k++) {
271
+ const a = args[k];
272
+ if (!endOpts && a === '--') {
273
+ endOpts = true;
274
+ } else if (!endOpts && a.startsWith('--')) {
275
+ const name = a.split('=')[0];
276
+ if (name === '--force' || name === '--force-with-lease' || name === '--force-if-includes') force = true;
277
+ else if (name === '--all' || name === '--mirror' || name === '--branches') all = true;
278
+ else if (name === '--delete') del = true;
279
+ else if (VALUE.has(name) && !a.includes('=')) k += 1;
280
+ } else if (!endOpts && a.startsWith('-') && a.length > 1) {
281
+ if (a === '-o') {
282
+ k += 1;
283
+ continue;
284
+ }
285
+ if (a.includes('f')) force = true;
286
+ if (a.includes('d')) del = true;
287
+ } else {
288
+ positionals.push(a);
289
+ }
290
+ }
291
+ // null in targets means the current branch.
292
+ const targets = [];
293
+ const refspecs = positionals.slice(1);
294
+ for (const spec of refspecs) {
295
+ let r = spec;
296
+ if (r.startsWith('+')) {
297
+ force = true;
298
+ r = r.slice(1);
299
+ }
300
+ if (r === ':') {
301
+ all = true;
302
+ continue;
303
+ }
304
+ let target;
305
+ if (del) target = r;
306
+ else if (r.includes(':')) target = r.slice(r.indexOf(':') + 1) || r.slice(0, r.indexOf(':'));
307
+ else target = r;
308
+ if (target === 'HEAD' || target === '@') target = null;
309
+ targets.push(target === null ? null : target.replace(/^refs\/heads\//, ''));
310
+ }
311
+ if (!refspecs.length && !all) targets.push(null);
312
+ return { kind: force ? 'force-push' : 'push', force, all, targets };
313
+ }
314
+
315
+ function parseCommit(args) {
316
+ const VALUE_SHORT = 'mFcCt';
317
+ const VALUE_LONG = new Set(['--message', '--file', '--reuse-message', '--reedit-message', '--fixup', '--squash',
318
+ '--author', '--date', '--cleanup', '--template', '--trailer']);
319
+ let all = false;
320
+ let whole = false;
321
+ let include = false;
322
+ let endOpts = false;
323
+ const paths = [];
324
+ for (let k = 0; k < args.length; k++) {
325
+ const a = args[k];
326
+ if (!endOpts && a === '--') {
327
+ endOpts = true;
328
+ } else if (!endOpts && a.startsWith('--')) {
329
+ const name = a.split('=')[0];
330
+ if (name === '--all') all = true;
331
+ else if (name === '--include') include = true;
332
+ else if (name === '--pathspec-from-file') whole = true;
333
+ if ((VALUE_LONG.has(name) || name === '--pathspec-from-file') && !a.includes('=')) k += 1;
334
+ } else if (!endOpts && a.startsWith('-') && a.length > 1) {
335
+ for (let j = 1; j < a.length; j++) {
336
+ if (a[j] === 'a') all = true;
337
+ if (a[j] === 'i') include = true;
338
+ if (VALUE_SHORT.includes(a[j])) {
339
+ if (j === a.length - 1) k += 1;
340
+ break;
341
+ }
342
+ }
343
+ } else {
344
+ paths.push(a);
345
+ }
346
+ }
347
+ return { kind: 'commit', all, include, whole: whole || all, paths };
348
+ }
349
+
350
+ // git add / rm / mv: what the command stages before a commit in the same line.
351
+ function parseStage(op, args) {
352
+ let whole = false;
353
+ let endOpts = false;
354
+ const paths = [];
355
+ for (const a of args) {
356
+ if (!endOpts && a === '--') endOpts = true;
357
+ else if (!endOpts && a.startsWith('--')) {
358
+ const name = a.split('=')[0];
359
+ if (name === '--all' || name === '--update' || name === '--pathspec-from-file') whole = true;
360
+ } else if (!endOpts && a.startsWith('-') && a.length > 1) {
361
+ if (op === 'add' && /[Au]/.test(a)) whole = true;
362
+ } else paths.push(a);
363
+ }
364
+ return { kind: 'stage', op, whole: whole && !paths.length, paths };
365
+ }
366
+
367
+ // The branch a later commit in the same command will be on, if this changes it. UNKNOWN for `-`.
368
+ export const UNKNOWN = Symbol('unknown');
369
+ // `created` is true when the name is certainly the new branch; otherwise the evaluator carries the name
370
+ // only when it is protected or names an existing local branch (else it was a path or a commit).
371
+ function parseSwitch(sub, args) {
372
+ const NEW = sub === 'switch'
373
+ ? new Set(['-c', '-C', '--create', '--force-create', '--orphan'])
374
+ : new Set(['-b', '-B', '--orphan']);
375
+ const NOT_SWITCH = new Set(['-p', '--patch', '--ours', '--theirs', '-m', '--merge', '--pathspec-from-file']);
376
+ let track = false;
377
+ const positionals = [];
378
+ for (let k = 0; k < args.length; k++) {
379
+ const a = args[k];
380
+ if (a === '--') return { kind: 'other' };
381
+ if (NOT_SWITCH.has(a.split('=')[0])) return { kind: 'other' };
382
+ if (NEW.has(a)) return args[k + 1] === undefined ? { kind: 'other' } : { kind: 'switch', to: args[k + 1], created: true };
383
+ const eq = a.indexOf('=');
384
+ if (eq > 0 && NEW.has(a.slice(0, eq))) return { kind: 'switch', to: a.slice(eq + 1), created: true };
385
+ if (a === '--track' || a.startsWith('--track=') || a === '-t') track = true;
386
+ else if (a === '--detach' || a === '-d') return { kind: 'switch', to: null, created: true };
387
+ else if (!a.startsWith('-') || a === '-') positionals.push(a);
388
+ }
389
+ // `git checkout <b> <paths>` restores files and stays put.
390
+ if (positionals.length !== 1) return { kind: 'other' };
391
+ const p = positionals[0];
392
+ if (p === '-') return { kind: 'switch', to: UNKNOWN, created: true };
393
+ // --track origin/main creates main.
394
+ if (track) return { kind: 'switch', to: p.includes('/') ? p.slice(p.indexOf('/') + 1) : p, created: true };
395
+ return { kind: 'switch', to: p, created: false };
396
+ }
397
+
398
+ // From a subagent, every gh pr subcommand but these is a write.
399
+ const PR_READS = new Set(['view', 'list', 'status', 'checks', 'diff']);
400
+
401
+ // gh pr <sub> that writes -> 'pr'; gh api with a method other than GET -> 'api-write'; else null.
402
+ function classifyGh(w) {
403
+ let k = 1;
404
+ const skipFlags = () => {
405
+ while (k < w.length && w[k].startsWith('-')) k += w[k] === '-R' || w[k] === '--repo' ? 2 : 1;
406
+ };
407
+ skipFlags();
408
+ const group = w[k];
409
+ k += 1;
410
+ if (group === 'pr') {
411
+ skipFlags();
412
+ return w[k] !== undefined && !PR_READS.has(w[k]) ? 'pr' : null;
413
+ }
414
+ if (group === 'api') {
415
+ let method = 'GET';
416
+ for (let j = k; j < w.length; j++) {
417
+ if ((w[j] === '-X' || w[j] === '--method') && w[j + 1] !== undefined) method = w[j + 1];
418
+ else if (w[j].startsWith('--method=')) method = w[j].slice('--method='.length);
419
+ else if (/^-X./.test(w[j])) method = w[j].slice(2);
420
+ }
421
+ return method.toUpperCase() === 'GET' ? null : 'api-write';
422
+ }
423
+ return null;
424
+ }
425
+
426
+ // ---- rule 6: the text a destructive pattern is matched against ----
427
+
428
+ // Commands that only read or print their arguments.
429
+ const READERS = new Set(['echo', 'printf', 'grep', 'egrep', 'fgrep', 'rg']);
430
+ // Database clients: their here-documents are the statements they run.
431
+ const DB_CLIENTS = new Set(['psql', 'mysql', 'sqlite3', 'sqlcmd']);
432
+ // Commands that read a path without changing it: naming intake there is not changing it.
433
+ const MENTION_READERS = new Set(['cat', 'ls', 'head', 'tail', 'less', 'more', 'grep', 'rg', 'find', 'stat', 'wc']);
434
+ const MESSAGE_OPTS = new Set(['-m', '-F', '--message', '--file']);
435
+
436
+ // Index of git's subcommand, past its global options.
437
+ function gitSubIndex(w) {
438
+ let k = 1;
439
+ while (k < w.length && w[k].startsWith('-')) k += w[k] === '-C' || GIT_GLOBAL_VALUE.has(w[k]) ? 2 : 1;
440
+ return k;
441
+ }
442
+
443
+ // -> the segment's command text (quotes removed, their content kept) without commit messages; null to
444
+ // skip a command that only reads or prints its arguments.
445
+ function destructiveText(toks, heredocs) {
446
+ const b = base(toks[0].v);
447
+ if (READERS.has(b)) return null;
448
+ let keep = toks;
449
+ if (b === 'git') {
450
+ const w = toks.map((t) => t.v);
451
+ const k = gitSubIndex(w);
452
+ if (w[k] === 'grep' || w[k] === 'log') return null;
453
+ if (w[k] === 'commit') {
454
+ keep = [];
455
+ for (let j = 0; j < toks.length; j++) {
456
+ const v = toks[j].v;
457
+ if (j > k && (MESSAGE_OPTS.has(v) || /^-[^-]*[mF]$/.test(v))) j += 1;
458
+ else if (j > k && (/^--(message|file)=/.test(v) || /^-[^-]*[mF]./.test(v))) continue;
459
+ else keep.push(toks[j]);
460
+ }
461
+ }
462
+ }
463
+ const words = keep.map((t) => t.v);
464
+ return (DB_CLIENTS.has(b) ? [...words, ...heredocs] : words).join(' ');
465
+ }
466
+
467
+ // `git tag` with no arguments, or in list mode, only reads.
468
+ const tagLists = (args) => args.length === 0 || args.some((a) => a === '-l' || a === '--list' || a.startsWith('--list='));
469
+
470
+ // One simple command -> invocations {kind, dir, label, ...}; `state` carries cd/pushd forward.
471
+ function walk(seg, state, acc) {
472
+ const toks = stripPrefixes(seg.toks);
473
+ if (!toks.length) return;
474
+ const w = toks.map((t) => t.v);
475
+ const text = destructiveText(toks, seg.heredocs);
476
+ if (text !== null) acc.texts.push(text);
477
+ const head = base(w[0]);
478
+ const ownCommit = head === 'git' && w[gitSubIndex(w)] === 'commit';
479
+ if (state.cwd !== null && !MENTION_READERS.has(head) && !ownCommit) {
480
+ for (const x of w.slice(1)) if (!x.startsWith('-') && !/[$`]/.test(x)) acc.mentions.push({ dir: state.cwd, word: x });
481
+ }
482
+ const b = base(w[0]);
483
+ if (b === 'cd' || b === 'pushd') {
484
+ const target = w.slice(1).find((x) => !x.startsWith('-') || x === '-');
485
+ if (b === 'pushd') state.stack.push({ cwd: state.cwd, label: state.label });
486
+ if (target === undefined) {
487
+ state.cwd = b === 'cd' ? os.homedir() : null;
488
+ state.label = b === 'cd' ? '~' : 'pushd';
489
+ } else if (target === '-') {
490
+ state.cwd = null;
491
+ state.label = '-';
492
+ } else {
493
+ state.cwd = resolveDir(state.cwd, target);
494
+ state.label = target;
495
+ }
496
+ return;
497
+ }
498
+ if (b === 'popd') {
499
+ const prev = state.stack.pop();
500
+ state.cwd = prev ? prev.cwd : null;
501
+ state.label = prev ? prev.label : 'popd';
502
+ return;
503
+ }
504
+ if (SHELLS.has(b)) {
505
+ const k = w.findIndex((x, idx) => idx > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(x));
506
+ let bodies;
507
+ if (k !== -1 && w[k + 1] !== undefined) bodies = [w[k + 1]];
508
+ else if (seg.heredocs.length) bodies = seg.heredocs;
509
+ else bodies = seg.stdin ? seg.stdin.heredocs : [];
510
+ for (const body of bodies) {
511
+ const inner = { cwd: state.cwd, label: state.label, stack: [] };
512
+ for (const s of lex(body)) walk(s, inner, acc);
513
+ }
514
+ return;
515
+ }
516
+ if (b === 'gh') {
517
+ const kind = classifyGh(w);
518
+ if (kind) acc.invs.push({ kind, dir: state.cwd, label: state.label });
519
+ return;
520
+ }
521
+ if (b !== 'git') return;
522
+ let dir = state.cwd;
523
+ let label = state.label;
524
+ let k = 1;
525
+ while (k < w.length && w[k].startsWith('-')) {
526
+ if (w[k] === '-C') {
527
+ if (w[k + 1] !== undefined) {
528
+ dir = resolveDir(dir, w[k + 1]);
529
+ label = w[k + 1];
530
+ }
531
+ k += 2;
532
+ } else if (GIT_GLOBAL_VALUE.has(w[k])) {
533
+ k += 2;
534
+ } else {
535
+ k += 1;
536
+ }
537
+ }
538
+ const sub = w[k];
539
+ const args = w.slice(k + 1);
540
+ let inv;
541
+ if (sub === 'commit') inv = parseCommit(args);
542
+ else if (sub === 'push') inv = parsePush(args);
543
+ else if (sub === 'add' || sub === 'rm' || sub === 'mv' || sub === 'stage') inv = parseStage(sub === 'stage' ? 'add' : sub, args);
544
+ else if (sub === 'checkout' || sub === 'switch') inv = parseSwitch(sub, args);
545
+ // These make commits too: rule 1 holds them to the protected branches; rule 4 does not apply.
546
+ else if (sub === 'cherry-pick' || sub === 'revert' || sub === 'am') {
547
+ inv = { kind: 'commit', replay: true, all: false, include: false, whole: false, paths: [] };
548
+ }
549
+ // These change history without a commit of their own: only a subagent is refused them (rule 5).
550
+ else if (sub === 'merge' || sub === 'pull' || sub === 'rebase') inv = { kind: 'history' };
551
+ else if (sub === 'tag') inv = tagLists(args) ? { kind: 'other' } : { kind: 'history' };
552
+ else inv = { kind: 'other' };
553
+ acc.invs.push({ ...inv, dir, label: dir === null ? label : (label ?? dir) });
554
+ }
555
+
556
+ // -> {invs, texts, mentions}: every git/gh invocation in order, and each command's text for rule 6.
557
+ // cwd null means unknown.
558
+ function parse(command, cwd) {
559
+ const acc = { invs: [], texts: [], mentions: [] };
560
+ const state = { cwd, label: cwd, stack: [] };
561
+ for (const seg of lex(command)) walk(seg, state, acc);
562
+ return acc;
563
+ }
564
+
565
+ export const invocations = (command, cwd = process.cwd()) => parse(command, cwd).invs;
566
+
567
+ // -> {kind: 'commit'|'push'|'force-push'|'pr'|'other', branchArg?} for the first such invocation.
568
+ export function classifyGit(command) {
569
+ for (const inv of invocations(command)) {
570
+ if (inv.kind === 'commit' || inv.kind === 'pr') return { kind: inv.kind };
571
+ if (inv.kind === 'push' || inv.kind === 'force-push') {
572
+ const branchArg = inv.targets.find((t) => t !== null);
573
+ return branchArg === undefined ? { kind: inv.kind } : { kind: inv.kind, branchArg };
574
+ }
575
+ }
576
+ return { kind: 'other' };
577
+ }
578
+
579
+ // ---- repository facts, each safe outside a repository ----
580
+
581
+ function quiet(fn, fallback) {
582
+ try {
583
+ return fn();
584
+ } catch (e) {
585
+ if (e instanceof GitError) return fallback;
586
+ throw e;
587
+ }
588
+ }
589
+
590
+ // -> branch name; null for no branch (detached HEAD, or not a repository); UNKNOWN when git failed otherwise.
591
+ function branchIn(dir) {
592
+ try {
593
+ return currentBranch(dir);
594
+ } catch (e) {
595
+ if (e instanceof GitError) return /not a git repository/i.test(e.stderr) ? null : UNKNOWN;
596
+ throw e;
597
+ }
598
+ }
599
+
600
+ const lines = (text) => (text === '' ? [] : text.split('\n'));
601
+ const localBranch = (dir, name) => quiet(() => (git(dir, ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]), true), false);
602
+ const topOf = (dir) => (dir === null ? null : quiet(() => real(git(dir, ['rev-parse', '--show-toplevel'])), null));
603
+
604
+ // ---- rule 4: frozen intake ----
605
+
606
+ function covers(stager, file, top) {
607
+ if (stager.whole) return true;
608
+ for (const p of stager.paths) {
609
+ if (/[*?[]/.test(p) || p.startsWith(':')) return true;
610
+ const rel = toPosix(path.relative(top, path.resolve(real(stager.dir), p)));
611
+ if (rel === '' || rel === '.') return true;
612
+ if (file === rel || file.startsWith(`${rel}/`)) return true;
613
+ }
614
+ return false;
615
+ }
616
+
617
+ // Whether a word some command in the line names resolves under the intake directory.
618
+ function namesIntake(mentions, intakeAbs) {
619
+ return mentions.some(({ dir, word }) => {
620
+ const rel = path.relative(intakeAbs, path.resolve(real(dir), word));
621
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
622
+ });
623
+ }
624
+
625
+ function frozenIntake(root, cfg, invs, mentions) {
626
+ const intakeAbs = kitPaths(real(root), cfg).intake;
627
+ for (const c of invs.filter((i) => i.kind === 'commit' && !i.replay && i.dir !== null)) {
628
+ const top = topOf(c.dir);
629
+ if (!top) continue;
630
+ if (!quiet(() => (git(top, ['rev-parse', '--verify', 'HEAD']), true), false)) continue;
631
+ const intake = toPosix(path.relative(top, intakeAbs));
632
+ if (intake.startsWith('..') || path.isAbsolute(intake)) continue;
633
+ const inHead = (f) => quiet(() => (git(top, ['cat-file', '-e', `HEAD:${f}`]), true), false);
634
+ // A commit naming paths commits only those; the index counts too only with -i.
635
+ const onlyPaths = c.paths.length > 0 && !c.include;
636
+ if (!onlyPaths) {
637
+ const staged = lines(git(top, ['diff', '--cached', '--name-only', '--', intake]));
638
+ const hit = staged.find(inHead);
639
+ if (hit) return hit;
640
+ }
641
+ const stagers = onlyPaths ? [] : invs.filter((i) => i.kind === 'stage' && i.dir !== null && topOf(i.dir) === top);
642
+ if (c.whole || c.paths.length) stagers.push(c);
643
+ if (!stagers.length) continue;
644
+ const changed = lines(git(top, ['diff', '--name-only', 'HEAD', '--', intake]));
645
+ const tracked = lines(git(top, ['ls-tree', '-r', '--name-only', 'HEAD', '--', intake]));
646
+ // Another command in the line may change intake before -a reads the tree: every intake file counts.
647
+ const touched = c.all && namesIntake(mentions, intakeAbs);
648
+ for (const s of stagers) {
649
+ const candidates = s.op === 'rm' || s.op === 'mv' || (s === c && touched) ? tracked : changed;
650
+ const f = candidates.find((file) => covers(s, file, top) && inHead(file));
651
+ if (f) return f;
652
+ }
653
+ }
654
+ return null;
655
+ }
656
+
657
+ // ---- the hook ----
658
+
659
+ const unknownDir = (label) => deny(`cannot tell which branch ${label} is on; run the command from inside the repository`);
660
+
661
+ export function handle(input, { root, cfg }) {
662
+ const command = input?.tool_input?.command;
663
+ if (typeof command !== 'string') throw new Error('tool_input.command is missing');
664
+ const start = typeof input.cwd === 'string' && input.cwd !== '' ? resolveDir(null, input.cwd) : root;
665
+ const { invs, texts, mentions } = parse(command, start);
666
+ const protectedSet = new Set(cfg.protectedBranches);
667
+
668
+ // The branch each commit and push runs on, following checkouts earlier in the same command.
669
+ const switched = new Map();
670
+ for (const inv of invs) {
671
+ if (inv.dir === null) {
672
+ inv.branch = UNKNOWN;
673
+ continue;
674
+ }
675
+ const key = topOf(inv.dir) ?? inv.dir;
676
+ if (inv.kind === 'switch') {
677
+ const named = inv.created || protectedSet.has(inv.to) || localBranch(inv.dir, inv.to);
678
+ if (named) switched.set(key, inv.to);
679
+ }
680
+ else inv.branch = switched.has(key) ? switched.get(key) : branchIn(inv.dir);
681
+ }
682
+
683
+ // (1)
684
+ for (const c of invs.filter((i) => i.kind === 'commit')) {
685
+ if (c.branch === UNKNOWN) return unknownDir(c.label);
686
+ if (c.branch !== null && protectedSet.has(c.branch)) return deny(`commit on protected branch ${c.branch}; create a slice branch`);
687
+ }
688
+ // (2)
689
+ const pushes = invs.filter((i) => i.kind === 'push' || i.kind === 'force-push');
690
+ for (const p of pushes) {
691
+ if (p.all && cfg.protectedBranches.length) return deny(`push to protected branch ${cfg.protectedBranches[0]}`);
692
+ for (const t of p.targets) {
693
+ if (t === null && p.branch === UNKNOWN) return unknownDir(p.label);
694
+ const b = t === null ? p.branch : t;
695
+ if (b !== null && protectedSet.has(b)) return deny(`push to protected branch ${b}`);
696
+ }
697
+ }
698
+ // (3)
699
+ if (pushes.some((p) => p.force)) return deny('force push refused');
700
+ // (4)
701
+ const frozen = frozenIntake(root, cfg, invs, mentions);
702
+ if (frozen) return deny(`intake snapshot ${frozen} is frozen; add a new snapshot`);
703
+ // (5)
704
+ if (invs.some((i) => ['commit', 'history', 'push', 'force-push', 'pr', 'api-write'].includes(i.kind))) {
705
+ if (typeof input.agent_id === 'string' && input.agent_id !== '') {
706
+ return deny('agents do not run git; report and let the command commit');
707
+ }
708
+ }
709
+ // (6)
710
+ const patterns = compileDestructive(cfg);
711
+ for (let k = 0; k < patterns.length; k++) {
712
+ if (texts.some((t) => patterns[k].test(t))) return deny(`destructive command refused by rule ${cfg.destructive[k]}`);
713
+ }
714
+ return allow();
715
+ }