@hibira-io/mcp-approval-gate 0.2.0 → 0.4.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.
package/src/shell.js ADDED
@@ -0,0 +1,748 @@
1
+ // Decides which shell commands from a coding agent wait for a second person's
2
+ // approval: deleting files, force pushes, deploys, infrastructure changes,
3
+ // publishing packages and database writes. Everything else runs as usual.
4
+ //
5
+ // The command is split the way a shell would (quotes, ;, &&, ||, |, $( ),
6
+ // heredocs), wrappers such as sudo, env, bash -c, ssh and npx are looked
7
+ // through, and each simple command is checked on its own. It is a safety net
8
+ // for honest mistakes, not a sandbox: an agent that wants to hide a command
9
+ // can, so keep real credentials for production out of the agent's reach too.
10
+
11
+ import { classifySql } from './sql.js';
12
+
13
+ const OPERATORS = ['&&', '||', '|&', ';;', ';', '|', '&', '\n', '(', ')'];
14
+
15
+ /**
16
+ * Splits a command line into simple commands. Returns
17
+ * [{ argv, heredoc, stdin, pipedFrom }] where heredoc is the body of a
18
+ * <<WORD heredoc, stdin is true when input comes from a file or pipe, and
19
+ * pipedFrom is the previous command of a pipeline.
20
+ */
21
+ export function splitShell(line) {
22
+ const out = [];
23
+ let argv = [];
24
+ let word = '';
25
+ let has = false;
26
+ let heredocs = [];
27
+ let cmd = { argv, heredoc: undefined, stdin: false };
28
+ let piped = false;
29
+ let prev;
30
+ const s = String(line ?? '');
31
+ const endWord = () => {
32
+ if (has || word) argv.push(word);
33
+ word = '';
34
+ has = false;
35
+ };
36
+ const endCommand = (op) => {
37
+ endWord();
38
+ if (argv.length) {
39
+ cmd.argv = argv;
40
+ if (piped && prev) {
41
+ cmd.stdin = true;
42
+ cmd.pipedFrom = prev;
43
+ }
44
+ out.push(cmd);
45
+ prev = cmd;
46
+ }
47
+ piped = op === '|' || op === '|&';
48
+ if (!piped) prev = undefined;
49
+ argv = [];
50
+ cmd = { argv, heredoc: undefined, stdin: false };
51
+ };
52
+ let i = 0;
53
+ while (i < s.length) {
54
+ const ch = s[i];
55
+ if (ch === '\\' && i + 1 < s.length) {
56
+ if (s[i + 1] !== '\n') word += s[i + 1];
57
+ has = true;
58
+ i += 2;
59
+ continue;
60
+ }
61
+ if (ch === "'") {
62
+ const end = s.indexOf("'", i + 1);
63
+ word += end === -1 ? s.slice(i + 1) : s.slice(i + 1, end);
64
+ has = true;
65
+ i = end === -1 ? s.length : end + 1;
66
+ continue;
67
+ }
68
+ if (ch === '"') {
69
+ i++;
70
+ while (i < s.length && s[i] !== '"') {
71
+ if (s[i] === '\\' && i + 1 < s.length && '"\\$`'.includes(s[i + 1])) {
72
+ word += s[i + 1];
73
+ i += 2;
74
+ } else if (s[i] === '$' && s[i + 1] === '(') {
75
+ const [inner, next] = balanced(s, i + 2);
76
+ out.push(...splitShell(inner));
77
+ word += `$(${inner})`;
78
+ i = next;
79
+ } else {
80
+ word += s[i++];
81
+ }
82
+ }
83
+ has = true;
84
+ i++;
85
+ continue;
86
+ }
87
+ if (ch === '$' && s[i + 1] === '(') {
88
+ const [inner, next] = balanced(s, i + 2);
89
+ out.push(...splitShell(inner));
90
+ word += `$(${inner})`;
91
+ i = next;
92
+ continue;
93
+ }
94
+ if (ch === '`') {
95
+ const end = s.indexOf('`', i + 1);
96
+ const inner = end === -1 ? s.slice(i + 1) : s.slice(i + 1, end);
97
+ out.push(...splitShell(inner));
98
+ word += `\`${inner}\``;
99
+ i = end === -1 ? s.length : end + 1;
100
+ continue;
101
+ }
102
+ if (ch === '#' && !has && !word) {
103
+ const end = s.indexOf('\n', i);
104
+ i = end === -1 ? s.length : end;
105
+ continue;
106
+ }
107
+ if (ch === '<' && s.startsWith('<<', i) && !s.startsWith('<<<', i)) {
108
+ endWord();
109
+ let j = i + 2;
110
+ if (s[j] === '-') j++;
111
+ while (s[j] === ' ' || s[j] === '\t') j++;
112
+ const m = /^(['"]?)([A-Za-z0-9_.-]+)\1/.exec(s.slice(j));
113
+ if (m) {
114
+ heredocs.push({ cmd, word: m[2] });
115
+ cmd.stdin = true;
116
+ i = j + m[0].length;
117
+ continue;
118
+ }
119
+ }
120
+ if (ch === '<' && s.startsWith('<<<', i)) {
121
+ endWord();
122
+ cmd.stdin = true;
123
+ cmd.herestring = true;
124
+ i += 3;
125
+ continue;
126
+ }
127
+ if (ch === '<' && s[i + 1] !== '(') {
128
+ endWord();
129
+ cmd.stdin = true;
130
+ i++;
131
+ while (s[i] === ' ' || s[i] === '\t') i++;
132
+ // Skip the file name.
133
+ while (i < s.length && !/[\s;&|()<>]/.test(s[i])) i++;
134
+ continue;
135
+ }
136
+ if (ch === '>' || (/[0-9]/.test(ch) && s[i + 1] === '>' && !word)) {
137
+ endWord();
138
+ if (ch !== '>') i++;
139
+ i++;
140
+ if (s[i] === '>' || s[i] === '|') i++;
141
+ if (s[i] === '&') {
142
+ i++;
143
+ while (/[0-9-]/.test(s[i] ?? '')) i++;
144
+ continue;
145
+ }
146
+ while (s[i] === ' ' || s[i] === '\t') i++;
147
+ while (i < s.length && !/[\s;&|()<>]/.test(s[i])) i++;
148
+ continue;
149
+ }
150
+ const op = OPERATORS.find((o) => s.startsWith(o, i));
151
+ if (op) {
152
+ if (op === '&' && (s[i + 1] === '>' || s[i - 1] === '>')) {
153
+ i++;
154
+ continue;
155
+ }
156
+ endCommand(op);
157
+ i += op.length;
158
+ if (op === '\n' && heredocs.length) {
159
+ for (const h of heredocs) {
160
+ const lines = [];
161
+ while (i < s.length) {
162
+ let end = s.indexOf('\n', i);
163
+ if (end === -1) end = s.length;
164
+ const l = s.slice(i, end);
165
+ i = end + 1;
166
+ if (l.trim() === h.word) break;
167
+ lines.push(l);
168
+ }
169
+ h.cmd.heredoc = (h.cmd.heredoc ? `${h.cmd.heredoc}\n` : '') + lines.join('\n');
170
+ }
171
+ heredocs = [];
172
+ }
173
+ continue;
174
+ }
175
+ if (ch === ' ' || ch === '\t') {
176
+ endWord();
177
+ i++;
178
+ continue;
179
+ }
180
+ word += ch;
181
+ i++;
182
+ }
183
+ endCommand(';');
184
+ return out;
185
+ }
186
+
187
+ function balanced(s, start) {
188
+ let depth = 1;
189
+ let i = start;
190
+ let quote = '';
191
+ while (i < s.length) {
192
+ const ch = s[i];
193
+ if (quote) {
194
+ if (ch === quote) quote = '';
195
+ else if (ch === '\\' && quote === '"') i++;
196
+ } else if (ch === "'" || ch === '"') quote = ch;
197
+ else if (ch === '(') depth++;
198
+ else if (ch === ')' && --depth === 0) return [s.slice(start, i), i + 1];
199
+ i++;
200
+ }
201
+ return [s.slice(start), s.length];
202
+ }
203
+
204
+ const base = (p) => String(p ?? '').split('/').pop();
205
+
206
+ // Commands that run the rest of their arguments as another command.
207
+ const WRAPPERS = {
208
+ sudo: /^-[ugCDhpRrTt]$|^--(user|group|chdir|host|prompt|role|type|close-from)$/,
209
+ doas: /^-[uC]$/,
210
+ env: /^-[uSC]$|^--(unset|chdir|split-string)$/,
211
+ nohup: null,
212
+ time: /^-[fo]$/,
213
+ nice: /^-n$|^--adjustment$/,
214
+ ionice: /^-[cnp]$/,
215
+ timeout: /^-[sk]$|^--(signal|kill-after)$/,
216
+ command: null,
217
+ exec: /^-a$/,
218
+ builtin: null,
219
+ xargs: /^-[aEeIiLlnPsd]$|^--(arg-file|delimiter|eof|replace|max-lines|max-args|max-procs|max-chars)$/,
220
+ watch: /^-[nd]$|^--(interval|differences)$/,
221
+ caffeinate: null,
222
+ stdbuf: null,
223
+ unbuffer: null,
224
+ chronic: null,
225
+ dotenv: /^-[ecv]$/,
226
+ 'op': null,
227
+ 'aws-vault': null,
228
+ };
229
+
230
+ const RUNNERS = {
231
+ npx: /^-p$|^--package$|^-c$|^--call$/,
232
+ bunx: /^-p$|^--package$/,
233
+ 'pnpx': null,
234
+ };
235
+
236
+ /** Drops leading VAR=value words and wrapper commands. Returns the real argv, or the inner shell strings to recurse into. */
237
+ function unwrap(argv, depth = 0) {
238
+ let a = argv.slice();
239
+ for (let guard = 0; guard < 20 && a.length; guard++) {
240
+ while (a.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a[0])) a.shift();
241
+ if (!a.length) break;
242
+ const name = base(a[0]);
243
+ if (['bash', 'sh', 'zsh', 'dash', 'ksh', 'fish'].includes(name)) {
244
+ const c = a.findIndex((w, k) => k > 0 && /^-[a-z]*c[a-z]*$/.test(w));
245
+ if (c !== -1 && a[c + 1] !== undefined) return { inner: [a[c + 1]] };
246
+ return { argv: a };
247
+ }
248
+ if (name === 'eval') return { inner: [a.slice(1).join(' ')] };
249
+ if (name === 'ssh') {
250
+ const rest = sshCommand(a.slice(1));
251
+ return rest ? { inner: [rest], remote: true } : { argv: a };
252
+ }
253
+ if (name === 'kubectl' && a[1] === 'exec') {
254
+ const d = a.indexOf('--');
255
+ return d !== -1 ? { inner: [a.slice(d + 1).join(' ')], remote: true, argv: a } : { argv: a };
256
+ }
257
+ if (name === 'docker' && (a[1] === 'exec' || a[1] === 'run')) return { argv: a };
258
+ if (name in WRAPPERS) {
259
+ const takesValue = WRAPPERS[name];
260
+ let k = 1;
261
+ if (name === 'timeout' || name === 'watch') {
262
+ while (k < a.length && a[k].startsWith('-')) k += takesValue?.test(a[k]) ? 2 : 1;
263
+ if (name === 'timeout') k++;
264
+ } else if (name === 'op' || name === 'aws-vault' || name === 'dotenv') {
265
+ const d = a.indexOf('--');
266
+ if (d === -1) return { argv: a };
267
+ k = d + 1;
268
+ } else {
269
+ while (k < a.length && a[k].startsWith('-')) {
270
+ if (a[k] === '--') { k++; break; }
271
+ k += takesValue?.test(a[k]) ? 2 : 1;
272
+ }
273
+ if (name === 'env' || name === 'sudo') while (k < a.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a[k])) k++;
274
+ }
275
+ a = a.slice(k);
276
+ continue;
277
+ }
278
+ if (name in RUNNERS || (['pnpm', 'yarn', 'bun'].includes(name) && ['dlx', 'exec', 'x'].includes(a[1])) ||
279
+ (name === 'npm' && ['exec', 'x'].includes(a[1])) || (name === 'bundle' && a[1] === 'exec') ||
280
+ (['poetry', 'uv', 'pipenv', 'rye', 'hatch', 'pdm'].includes(name) && a[1] === 'run') || name === 'uvx' || name === 'pipx' && a[1] === 'run') {
281
+ let k = name in RUNNERS || name === 'uvx' ? 1 : 2;
282
+ const takesValue = RUNNERS[name];
283
+ while (k < a.length && a[k].startsWith('-')) {
284
+ if (a[k] === '--') { k++; break; }
285
+ k += takesValue?.test(a[k]) ? 2 : 1;
286
+ }
287
+ if (k >= a.length) return { argv: a };
288
+ a = a.slice(k);
289
+ // npx package@version -> package
290
+ a[0] = a[0].replace(/^(@?[^@]+)@.*$/, '$1');
291
+ continue;
292
+ }
293
+ break;
294
+ }
295
+ return { argv: a };
296
+ }
297
+
298
+ function sshCommand(args) {
299
+ const valued = /^-[BbcDEeFIiJLlmOoPpQRSWw]$/;
300
+ let k = 0;
301
+ while (k < args.length && args[k].startsWith('-')) k += valued.test(args[k]) ? 2 : 1;
302
+ k++; // host
303
+ return k < args.length ? args.slice(k).join(' ') : undefined;
304
+ }
305
+
306
+ // Flag helpers: has(argv, '-f', '--force') also finds combined short flags (-rf).
307
+ function hasFlag(argv, short, ...long) {
308
+ return argv.some((w) => long.includes(w) || long.some((l) => w.startsWith(`${l}=`)) ||
309
+ (short && /^-[A-Za-z]+$/.test(w) && !w.startsWith('--') && w.slice(1).includes(short)));
310
+ }
311
+ const words = (argv) => argv.filter((w) => !w.startsWith('-'));
312
+
313
+ const SAFE_RM = /^(\.\/)?(node_modules|dist|build|out|\.next|\.nuxt|\.output|\.svelte-kit|\.turbo|\.cache|\.parcel-cache|\.vite|coverage|target|__pycache__|\.pytest_cache|\.mypy_cache|\.ruff_cache|\.venv|venv|\.tox|tmp|\.tmp|vendor\/bin)\/?$/;
314
+
315
+ function rmTargetsSafe(targets) {
316
+ return targets.length > 0 && targets.every((t) =>
317
+ !t.includes('..') && !t.includes('*') && (SAFE_RM.test(t) || /^\/tmp\/[^/]+/.test(t) || /^\$\{?TMPDIR\}?\/[^/]+/.test(t) ||
318
+ /^(\.\/)?[\w.-]+\/(node_modules|dist|build|\.next|coverage|target|__pycache__)\/?$/.test(t)));
319
+ }
320
+
321
+ const DEPLOY_SCRIPT = /(^|[:._-])(deploy|release|publish|destroy|teardown|prod|production|rollback|db[:._-]?(reset|drop|wipe|seed[:._-]?prod)|migrate[:._-]?prod)($|[:._-])/i;
322
+
323
+ const SQL_CLIENTS = {
324
+ psql: { flags: ['-c', '--command'], file: ['-f', '--file'] },
325
+ pgcli: { flags: ['-c', '--command'], file: [] },
326
+ mysql: { flags: ['-e', '--execute'], file: [] },
327
+ mariadb: { flags: ['-e', '--execute'], file: [] },
328
+ sqlite3: { positional: 1, file: [] },
329
+ sqlcmd: { flags: ['-Q', '-q'], file: ['-i'] },
330
+ 'clickhouse-client': { flags: ['-q', '--query'], file: ['--queries-file'] },
331
+ clickhouse: { flags: ['-q', '--query'], file: ['--queries-file'] },
332
+ duckdb: { flags: ['-c'], positional: 1, file: [] },
333
+ cqlsh: { flags: ['-e', '--execute'], file: ['-f', '--file'] },
334
+ snowsql: { flags: ['-q', '--query'], file: ['-f', '--filename'] },
335
+ bq: { sub: 'query' },
336
+ };
337
+
338
+ function flagValues(argv, flags) {
339
+ const out = [];
340
+ for (let k = 0; k < argv.length; k++) {
341
+ for (const f of flags) {
342
+ if (argv[k] === f && argv[k + 1] !== undefined) out.push(argv[k + 1]);
343
+ else if (f.startsWith('--') && argv[k].startsWith(`${f}=`)) out.push(argv[k].slice(f.length + 1));
344
+ else if (!f.startsWith('--') && argv[k].startsWith(f) && argv[k].length > f.length && !argv[k].startsWith('--')) out.push(argv[k].slice(f.length));
345
+ }
346
+ }
347
+ return out;
348
+ }
349
+
350
+ function sqlRule(name, argv, cmd) {
351
+ const spec = SQL_CLIENTS[name];
352
+ if (!spec) return undefined;
353
+ let sql = [];
354
+ if (spec.sub) {
355
+ if (argv[1] !== spec.sub) return undefined;
356
+ sql = words(argv.slice(2)).slice(-1);
357
+ } else {
358
+ sql = flagValues(argv, spec.flags ?? []);
359
+ if (!sql.length && spec.positional) {
360
+ const pos = words(argv.slice(1));
361
+ if (pos.length > spec.positional) sql = [pos.slice(spec.positional).join(' ')];
362
+ }
363
+ }
364
+ if (cmd.heredoc) sql.push(cmd.heredoc);
365
+ if (!sql.length && cmd.pipedFrom) {
366
+ const from = cmd.pipedFrom.argv;
367
+ if (['echo', 'printf'].includes(base(from[0]))) sql.push(words(from.slice(1)).join(' '));
368
+ else if (cmd.pipedFrom.heredoc) sql.push(cmd.pipedFrom.heredoc);
369
+ }
370
+ if (cmd.herestring && !sql.length) {
371
+ return { label: `${name} with SQL from a here-string`, kind: 'database' };
372
+ }
373
+ if (sql.length) {
374
+ const c = classifySql(sql.join(';\n'));
375
+ if (!c.write) return undefined;
376
+ return { label: `${name}: ${c.kinds.join(', ')}`, kind: 'database', warnings: c.warnings };
377
+ }
378
+ if (flagValues(argv, spec.file ?? []).length || cmd.stdin) {
379
+ return { label: `${name} runs SQL from a file or pipe`, kind: 'database' };
380
+ }
381
+ return undefined;
382
+ }
383
+
384
+ const REDIS_WRITES = /^(FLUSHALL|FLUSHDB|DEL|UNLINK|SET|MSET|HSET|HDEL|EXPIRE|RENAME|SHUTDOWN|CONFIG|DEBUG|SCRIPT|EVAL|LPUSH|RPUSH|SADD|SREM|ZADD|ZREM|INCR|DECR|XADD|XDEL|MIGRATE|RESTORE|REPLICAOF|SLAVEOF|SWAPDB|MOVE|COPY)$/i;
385
+ const MONGO_WRITES = /\.(drop|dropDatabase|delete(One|Many)?|remove|update(One|Many)?|replaceOne|insert(One|Many)?|bulkWrite|findOneAnd(Update|Replace|Delete)|createIndex|dropIndex(es)?|renameCollection)\s*\(/;
386
+
387
+ /** Rules for one unwrapped simple command. Returns { label, kind } or undefined. */
388
+ function rule(argv, cmd) {
389
+ const name = base(argv[0]);
390
+ const sub = argv[1];
391
+ const w = words(argv.slice(1));
392
+ switch (name) {
393
+ case 'rm': {
394
+ if (hasFlag(argv, 'r', '--recursive') || hasFlag(argv, 'R')) {
395
+ if (rmTargetsSafe(w)) return undefined;
396
+ return { label: 'deletes files recursively (rm -r)', kind: 'files' };
397
+ }
398
+ if (w.some((t) => t === '/' || t === '~' || t === '*' || t.startsWith('/') && t.split('/').length <= 2)) return { label: 'deletes files at the top of the disk', kind: 'files' };
399
+ return undefined;
400
+ }
401
+ case 'rmdir': return undefined;
402
+ case 'find':
403
+ if (argv.includes('-delete') || argv.some((x, k) => ['-exec', '-execdir', '-ok'].includes(x) && /^(rm|shred|unlink)$/.test(base(argv[k + 1])))) return { label: 'deletes the files find matches', kind: 'files' };
404
+ return undefined;
405
+ case 'shred': case 'wipefs': case 'srm':
406
+ return { label: `${name} destroys data`, kind: 'files' };
407
+ case 'dd':
408
+ if (argv.some((x) => /^of=\/dev\//.test(x))) return { label: 'dd writes to a disk device', kind: 'files' };
409
+ return undefined;
410
+ case 'truncate':
411
+ return argv.some((x) => /^(-s|--size)(=?0)?$/.test(x)) && argv.includes('0') || argv.some((x) => /^--size=0$|^-s0$/.test(x)) ? { label: 'truncate empties files', kind: 'files' } : undefined;
412
+ case 'shutdown': case 'reboot': case 'halt': case 'poweroff':
413
+ return { label: `${name} the machine`, kind: 'system' };
414
+ case 'systemctl':
415
+ return ['stop', 'disable', 'mask', 'kill', 'poweroff', 'reboot', 'halt'].includes(sub) ? { label: `systemctl ${sub}`, kind: 'system' } : undefined;
416
+ case 'git': return gitRule(argv);
417
+ case 'gh': {
418
+ const [a, b] = w;
419
+ if (a === 'repo' && ['delete', 'archive', 'rename'].includes(b)) return { label: `gh repo ${b}`, kind: 'git' };
420
+ if (a === 'release' && ['create', 'delete', 'delete-asset', 'edit'].includes(b)) return { label: `gh release ${b}`, kind: 'publish' };
421
+ if (a === 'pr' && b === 'merge') return { label: 'merges a pull request', kind: 'git' };
422
+ if (a === 'secret' && ['set', 'delete', 'remove'].includes(b)) return { label: `gh secret ${b}`, kind: 'secrets' };
423
+ if (a === 'variable' && ['set', 'delete'].includes(b)) return { label: `gh variable ${b}`, kind: 'secrets' };
424
+ if (a === 'workflow' && b === 'run') return { label: 'starts a GitHub Actions workflow', kind: 'deploy' };
425
+ if (a === 'api' && argv.some((x, k) => /^(-X|--method)$/.test(x) && /^(DELETE|PUT|PATCH|POST)$/i.test(argv[k + 1] ?? '') || /^(-X|--method=)(DELETE|PUT|PATCH)$/i.test(x))) return { label: 'gh api changes something', kind: 'git' };
426
+ return undefined;
427
+ }
428
+ case 'terraform': case 'tofu': case 'terragrunt': case 'tf': {
429
+ const verbs = ['apply', 'destroy', 'import', 'taint', 'untaint', 'force-unlock', 'run-all'];
430
+ if (verbs.includes(sub)) {
431
+ if (sub === 'run-all' && !['apply', 'destroy'].includes(argv[2])) return undefined;
432
+ return { label: `${name} ${sub === 'run-all' ? `run-all ${argv[2]}` : sub}`, kind: 'infra' };
433
+ }
434
+ if (sub === 'state' && ['rm', 'mv', 'push', 'replace-provider'].includes(argv[2])) return { label: `${name} state ${argv[2]}`, kind: 'infra' };
435
+ if (sub === 'workspace' && argv[2] === 'delete') return { label: `${name} workspace delete`, kind: 'infra' };
436
+ return undefined;
437
+ }
438
+ case 'pulumi':
439
+ if (['up', 'update', 'destroy', 'import', 'cancel'].includes(sub) || (sub === 'stack' && argv[2] === 'rm') || (sub === 'state' && ['delete', 'unprotect', 'move'].includes(argv[2])) || (sub === 'refresh' && hasFlag(argv, 'y', '--yes'))) return { label: `pulumi ${w.slice(0, 2).join(' ')}`, kind: 'infra' };
440
+ return undefined;
441
+ case 'cdk': case 'cdktf':
442
+ return ['deploy', 'destroy'].includes(sub) ? { label: `${name} ${sub}`, kind: 'infra' } : undefined;
443
+ case 'serverless': case 'sls':
444
+ return ['deploy', 'remove', 'rollback'].includes(sub) ? { label: `${name} ${sub}`, kind: 'deploy' } : undefined;
445
+ case 'sam':
446
+ return ['deploy', 'delete', 'sync'].includes(sub) ? { label: `sam ${sub}`, kind: 'deploy' } : undefined;
447
+ case 'kubectl': case 'oc': case 'kubecolor': {
448
+ const verbs = ['apply', 'create', 'delete', 'replace', 'patch', 'scale', 'autoscale', 'drain', 'cordon', 'uncordon', 'taint', 'edit', 'set', 'label', 'annotate', 'expose', 'run'];
449
+ const v = w[0];
450
+ if (verbs.includes(v)) return { label: `kubectl ${v}`, kind: 'infra' };
451
+ if (v === 'rollout' && ['restart', 'undo', 'pause', 'resume'].includes(w[1])) return { label: `kubectl rollout ${w[1]}`, kind: 'infra' };
452
+ return undefined;
453
+ }
454
+ case 'helm': case 'helmfile':
455
+ return ['install', 'upgrade', 'uninstall', 'delete', 'rollback', 'apply', 'sync', 'destroy'].includes(sub) ? { label: `${name} ${sub}`, kind: 'infra' } : undefined;
456
+ case 'docker': case 'podman': {
457
+ if (sub === 'push') return { label: `${name} push`, kind: 'publish' };
458
+ if (sub === 'system' && argv[2] === 'prune') return { label: `${name} system prune`, kind: 'files' };
459
+ if (sub === 'volume' && ['rm', 'prune'].includes(argv[2])) return { label: `${name} volume ${argv[2]}`, kind: 'files' };
460
+ if ((sub === 'compose' && argv.includes('down') || name === 'docker-compose' && sub === 'down') && hasFlag(argv, 'v', '--volumes')) return { label: 'compose down removes volumes', kind: 'files' };
461
+ if (sub === 'stack' && ['deploy', 'rm'].includes(argv[2])) return { label: `${name} stack ${argv[2]}`, kind: 'deploy' };
462
+ return undefined;
463
+ }
464
+ case 'docker-compose':
465
+ return sub === 'down' && hasFlag(argv, 'v', '--volumes') ? { label: 'compose down removes volumes', kind: 'files' } : undefined;
466
+ case 'vercel': case 'vc': {
467
+ if (['rm', 'remove', 'promote', 'rollback', 'alias', 'domains'].includes(sub) && !['ls', 'list', 'inspect'].includes(argv[2])) return { label: `vercel ${sub}`, kind: 'deploy' };
468
+ if (sub === 'env' && ['rm', 'add', 'remove', 'pull'].includes(argv[2]) && argv[2] !== 'pull') return { label: `vercel env ${argv[2]}`, kind: 'secrets' };
469
+ if (hasFlag(argv, null, '--prod', '--production') || argv.includes('--target=production') || flagValues(argv, ['--target']).includes('production')) return { label: 'deploys to production (vercel --prod)', kind: 'deploy' };
470
+ return undefined;
471
+ }
472
+ case 'netlify': case 'ntl':
473
+ if (sub === 'deploy' && hasFlag(argv, null, '--prod', '--prodIfUnlocked', '--prod-if-unlocked')) return { label: 'netlify deploy --prod', kind: 'deploy' };
474
+ if (['sites:delete', 'env:unset', 'env:set'].includes(sub)) return { label: `netlify ${sub}`, kind: 'deploy' };
475
+ return undefined;
476
+ case 'fly': case 'flyctl': {
477
+ if (['deploy', 'destroy', 'scale', 'launch'].includes(sub)) return { label: `${name} ${sub}`, kind: 'deploy' };
478
+ if (['apps', 'volumes', 'postgres', 'pg', 'machine', 'machines', 'secrets', 'ips', 'certs'].includes(sub) && ['destroy', 'delete', 'remove', 'rm', 'set', 'unset', 'import', 'release', 'stop', 'restart', 'kill', 'update', 'detach'].includes(argv[2])) return { label: `${name} ${sub} ${argv[2]}`, kind: 'deploy' };
479
+ return undefined;
480
+ }
481
+ case 'wrangler': {
482
+ if (['deploy', 'publish', 'delete', 'rollback'].includes(sub)) return { label: `wrangler ${sub}`, kind: 'deploy' };
483
+ if (sub === 'versions' && argv[2] === 'deploy') return { label: 'wrangler versions deploy', kind: 'deploy' };
484
+ if (sub === 'pages' && argv[2] === 'deploy' && !flagValues(argv, ['--branch']).some((b) => b !== 'main' && b !== 'master' && b !== 'production')) return { label: 'wrangler pages deploy', kind: 'deploy' };
485
+ if (sub === 'secret' && ['put', 'delete', 'bulk'].includes(argv[2])) return { label: `wrangler secret ${argv[2]}`, kind: 'secrets' };
486
+ if (['kv', 'kv:key', 'kv:namespace', 'r2', 'queues', 'd1', 'vectorize', 'hyperdrive'].includes(sub)) {
487
+ const verb = argv.find((x) => /^(delete|purge|bulk|put)$/.test(x));
488
+ if (verb) return { label: `wrangler ${sub} ${verb}`, kind: 'database' };
489
+ }
490
+ if (sub === 'd1' && argv[2] === 'execute' && argv.includes('--remote')) {
491
+ const sql = flagValues(argv, ['--command']);
492
+ if (!sql.length) return { label: 'wrangler d1 execute --remote from a file', kind: 'database' };
493
+ const c = classifySql(sql.join(';\n'));
494
+ return c.write ? { label: `wrangler d1 execute --remote: ${c.kinds.join(', ')}`, kind: 'database', warnings: c.warnings } : undefined;
495
+ }
496
+ if (sub === 'd1' && argv[2] === 'migrations' && argv[3] === 'apply' && argv.includes('--remote')) return { label: 'wrangler d1 migrations apply --remote', kind: 'database' };
497
+ return undefined;
498
+ }
499
+ case 'firebase':
500
+ return /^(deploy|hosting:disable|firestore:delete|database:(remove|set|update|push)|functions:delete|auth:import|apps:delete|projects:delete|hosting:channel:delete|ext:install|ext:uninstall)$/.test(sub ?? '') ? { label: `firebase ${sub}`, kind: 'deploy' } : undefined;
501
+ case 'heroku':
502
+ return /^(apps:destroy|destroy|pg:reset|pg:promote|pg:copy|releases:rollback|rollback|config:set|config:unset|ps:scale|scale|maintenance:on|container:release|run)$/.test(sub ?? '') ? { label: `heroku ${sub}`, kind: 'deploy' } : undefined;
503
+ case 'railway':
504
+ return ['up', 'down', 'delete', 'redeploy'].includes(sub) || (sub === 'variables' && argv.includes('--set')) ? { label: `railway ${sub}`, kind: 'deploy' } : undefined;
505
+ case 'render':
506
+ return argv.some((x) => /^(deploy|deploys|restart|delete|suspend)$/.test(x)) && !argv.includes('list') ? { label: `render ${w.slice(0, 2).join(' ')}`, kind: 'deploy' } : undefined;
507
+ case 'gcloud': {
508
+ const v = w.find((x) => /^(deploy|delete|destroy|update|create|set-iam-policy|add-iam-policy-binding|remove-iam-policy-binding|import|restore|reset|stop|patch|promote-replica|failover|rollback|replace|apply)$/.test(x));
509
+ if (v && !(w.includes('config') && w.includes('set'))) return { label: `gcloud ${w.slice(0, w.indexOf(v) + 1).join(' ')}`, kind: v === 'deploy' ? 'deploy' : 'infra' };
510
+ return undefined;
511
+ }
512
+ case 'gsutil':
513
+ return ['rm', 'rb'].includes(sub) || (sub === 'rsync' && hasFlag(argv, 'd')) ? { label: `gsutil ${sub}`, kind: 'files' } : undefined;
514
+ case 'az': {
515
+ const v = w.find((x) => /^(delete|purge|deploy|up|restart|stop|set|update|create|swap|reset|import|restore|failover)$/.test(x));
516
+ return v && !(w[0] === 'account' && v === 'set') && !(w[0] === 'config') ? { label: `az ${w.slice(0, w.indexOf(v) + 1).join(' ')}`, kind: 'infra' } : undefined;
517
+ }
518
+ case 'aws': {
519
+ const svc = w[0];
520
+ const op = w[1] ?? '';
521
+ if (svc === 's3') {
522
+ if (op === 'rm' || op === 'rb' || op === 'mv') return { label: `aws s3 ${op}`, kind: 'files' };
523
+ if (op === 'sync' && argv.includes('--delete')) return { label: 'aws s3 sync --delete', kind: 'files' };
524
+ if ((op === 'cp' || op === 'sync') && w.slice(2).some((x) => x.startsWith('s3://')) && words(argv).pop()?.startsWith('s3://')) return { label: `aws s3 ${op} uploads to S3`, kind: 'deploy' };
525
+ return undefined;
526
+ }
527
+ if (/^(delete|terminate|remove|put|update|modify|create|deregister|disable|detach|revoke|reboot|stop|restore|reset|deploy|execute|invoke|publish|start|attach|associate|disassociate|import|cancel|purge|run|send|tag|untag|set|replace|promote|failover|rotate|register|enable|apply|change|batch|upload|copy)(-|$)/.test(op) ||
528
+ (svc === 'cloudformation' && op === 'deploy') || svc === 'deploy') {
529
+ return { label: `aws ${svc} ${op}`, kind: 'infra' };
530
+ }
531
+ return undefined;
532
+ }
533
+ case 'eb':
534
+ return ['deploy', 'terminate', 'swap', 'scale', 'setenv', 'restore', 'abort'].includes(sub) ? { label: `eb ${sub}`, kind: 'deploy' } : undefined;
535
+ case 'doctl':
536
+ return w.some((x) => /^(delete|destroy|create-deployment|update|apply|deploy|purge)$/.test(x)) ? { label: `doctl ${w.slice(0, 3).join(' ')}`, kind: 'infra' } : undefined;
537
+ case 'supabase':
538
+ if (sub === 'db' && ['push', 'reset'].includes(argv[2]) && !(argv[2] === 'reset' && !argv.includes('--linked') && !flagValues(argv, ['--db-url']).length)) return { label: `supabase db ${argv[2]}`, kind: 'database' };
539
+ if (sub === 'db' && argv[2] === 'push') return { label: 'supabase db push', kind: 'database' };
540
+ if (['functions', 'secrets', 'projects', 'branches', 'storage'].includes(sub) && /^(deploy|delete|set|unset|rm|mv)$/.test(argv[2] ?? '')) return { label: `supabase ${sub} ${argv[2]}`, kind: 'deploy' };
541
+ if (sub === 'migration' && ['repair', 'up', 'squash'].includes(argv[2]) && (argv.includes('--linked') || flagValues(argv, ['--db-url']).length)) return { label: `supabase migration ${argv[2]}`, kind: 'database' };
542
+ return undefined;
543
+ case 'prisma':
544
+ if (sub === 'migrate' && ['deploy', 'reset', 'resolve'].includes(argv[2])) return { label: `prisma migrate ${argv[2]}`, kind: 'database' };
545
+ if (sub === 'db' && ['push', 'execute', 'seed'].includes(argv[2])) return { label: `prisma db ${argv[2]}`, kind: 'database' };
546
+ return undefined;
547
+ case 'drizzle-kit':
548
+ return ['push', 'migrate', 'drop'].includes(sub) || sub?.startsWith('push:') || sub?.startsWith('drop') ? { label: `drizzle-kit ${sub}`, kind: 'database' } : undefined;
549
+ case 'knex':
550
+ return /^(migrate:(latest|up|down|rollback|unlock)|seed:run)$/.test(sub ?? '') ? { label: `knex ${sub}`, kind: 'database' } : undefined;
551
+ case 'sequelize': case 'sequelize-cli':
552
+ return /^db:(drop|migrate(:undo(:all)?)?|seed(:all|:undo(:all)?)?)$/.test(sub ?? '') ? { label: `sequelize ${sub}`, kind: 'database' } : undefined;
553
+ case 'typeorm':
554
+ return /^(migration:(run|revert)|schema:(drop|sync)|query)$/.test(sub ?? '') ? { label: `typeorm ${sub}`, kind: 'database' } : undefined;
555
+ case 'alembic':
556
+ return ['upgrade', 'downgrade', 'stamp'].includes(sub) ? { label: `alembic ${sub}`, kind: 'database' } : undefined;
557
+ case 'flyway': case 'liquibase':
558
+ return argv.some((x) => /^(migrate|clean|repair|undo|update|rollback|drop-all|dropAll|baseline)/.test(x)) ? { label: `${name} ${w[0]}`, kind: 'database' } : undefined;
559
+ case 'atlas':
560
+ return sub === 'schema' && ['apply', 'clean'].includes(argv[2]) || sub === 'migrate' && ['apply', 'down'].includes(argv[2]) ? { label: `atlas ${sub} ${argv[2]}`, kind: 'database' } : undefined;
561
+ case 'dbmate': case 'goose': case 'migrate':
562
+ return argv.some((x) => /^(up|down|drop|rollback|reset|redo|force|migrate|up-to|down-to|goto)$/.test(x)) ? { label: `${name} ${w.find((x) => /^(up|down|drop|rollback|reset|redo|force|migrate|up-to|down-to|goto)$/.test(x))}`, kind: 'database' } : undefined;
563
+ case 'rails': case 'rake': case 'bin/rails':
564
+ return argv.some((x) => /^db:(drop|reset|migrate|rollback|schema:load|seed|setup|purge|truncate_all|migrate:redo|migrate:down|prepare)$/.test(x)) ? { label: `${name} ${argv.find((x) => x.startsWith('db:'))}`, kind: 'database' } : undefined;
565
+ case 'php': case 'artisan': {
566
+ const a = name === 'artisan' ? argv.slice(1) : base(argv[1]) === 'artisan' ? argv.slice(2) : undefined;
567
+ if (!a) return undefined;
568
+ if (/^(migrate(:fresh|:refresh|:reset|:rollback)?|db:wipe|db:seed|schema:dump|tinker|down|queue:flush|cache:clear|key:generate)$/.test(a[0] ?? '') && !(a[0] === 'migrate' && a.includes('--pretend'))) {
569
+ if (['cache:clear', 'key:generate', 'down', 'tinker'].includes(a[0]) && !a.includes('--force')) return a[0] === 'key:generate' ? { label: 'artisan key:generate replaces the app key', kind: 'secrets' } : undefined;
570
+ return { label: `artisan ${a[0]}`, kind: 'database' };
571
+ }
572
+ return undefined;
573
+ }
574
+ case 'python': case 'python3': case 'manage.py': case 'django-admin': {
575
+ const a = name === 'manage.py' || name === 'django-admin' ? argv.slice(1) : base(argv[1]) === 'manage.py' ? argv.slice(2) : undefined;
576
+ if (a && /^(flush|migrate|loaddata|sqlflush|reset_db|dbshell|createsuperuser)$/.test(a[0] ?? '')) return { label: `manage.py ${a[0]}`, kind: 'database' };
577
+ if (argv[1] === '-m' && argv[2] === 'twine' && argv[3] === 'upload') return { label: 'twine upload', kind: 'publish' };
578
+ return undefined;
579
+ }
580
+ case 'redis-cli': case 'valkey-cli': case 'keydb-cli': {
581
+ const cmdWord = w.find((x) => REDIS_WRITES.test(x));
582
+ if (cmdWord) return { label: `${name} ${cmdWord.toUpperCase()}`, kind: 'database' };
583
+ if (cmd.stdin && !w.length) return { label: `${name} runs commands from a file or pipe`, kind: 'database' };
584
+ return undefined;
585
+ }
586
+ case 'mongosh': case 'mongo': {
587
+ const js = [...flagValues(argv, ['--eval']), cmd.heredoc ?? ''].join('\n');
588
+ if (MONGO_WRITES.test(js)) return { label: `${name} changes data`, kind: 'database' };
589
+ if (flagValues(argv, ['--file', '-f']).length || w.some((x) => x.endsWith('.js'))) return { label: `${name} runs a script`, kind: 'database' };
590
+ return undefined;
591
+ }
592
+ case 'mongorestore': case 'pg_restore': case 'mysqlimport': case 'dropdb': case 'dropuser': case 'createdb':
593
+ return name === 'createdb' ? undefined : { label: name, kind: 'database' };
594
+ case 'npm': case 'pnpm': case 'yarn': case 'bun': {
595
+ if (['publish', 'unpublish', 'deprecate', 'dist-tag'].includes(sub) && !(sub === 'dist-tag' && ['ls', 'list'].includes(argv[2]))) return { label: `${name} ${sub}`, kind: 'publish' };
596
+ if (sub === 'owner' && ['add', 'rm'].includes(argv[2])) return { label: `${name} owner ${argv[2]}`, kind: 'publish' };
597
+ if (sub === 'npm' && argv[2] === 'publish') return { label: 'yarn npm publish', kind: 'publish' };
598
+ const script = sub === 'run' || sub === 'run-script' ? w[1] : name !== 'npm' && sub && !['install', 'add', 'remove', 'i', 'ci', 'test', 'build', 'dev', 'start', 'lint', 'exec', 'dlx', 'x', 'why', 'list', 'ls', 'outdated', 'audit', 'info', 'view', 'create', 'init', 'link', 'unlink', 'update', 'upgrade', 'up'].includes(sub) ? sub : undefined;
599
+ if (script && DEPLOY_SCRIPT.test(script)) return { label: `${name} runs the "${script}" script`, kind: 'deploy' };
600
+ return undefined;
601
+ }
602
+ case 'make': case 'just': case 'task': case 'mage': case 'nx': case 'turbo': {
603
+ const t = w.find((x) => DEPLOY_SCRIPT.test(x) && !x.includes('='));
604
+ return t ? { label: `${name} ${t}`, kind: 'deploy' } : undefined;
605
+ }
606
+ case 'cargo':
607
+ return ['publish', 'yank', 'owner'].includes(sub) ? { label: `cargo ${sub}`, kind: 'publish' } : undefined;
608
+ case 'twine':
609
+ return sub === 'upload' ? { label: 'twine upload', kind: 'publish' } : undefined;
610
+ case 'gem':
611
+ return ['push', 'yank', 'owner'].includes(sub) ? { label: `gem ${sub}`, kind: 'publish' } : undefined;
612
+ case 'poetry': case 'uv': case 'hatch': case 'flit': case 'pdm':
613
+ return sub === 'publish' ? { label: `${name} publish`, kind: 'publish' } : undefined;
614
+ case 'dotnet':
615
+ return sub === 'nuget' && ['push', 'delete'].includes(argv[2]) ? { label: `dotnet nuget ${argv[2]}`, kind: 'publish' } : undefined;
616
+ case 'nuget':
617
+ return ['push', 'delete'].includes(sub) ? { label: `nuget ${sub}`, kind: 'publish' } : undefined;
618
+ case 'mvn': case 'mvnw': case './mvnw':
619
+ return argv.some((x) => /^(deploy|release:perform|release:prepare)$/.test(x)) ? { label: 'mvn deploy', kind: 'publish' } : undefined;
620
+ case 'gradle': case 'gradlew': case './gradlew':
621
+ return argv.some((x) => /^(publish|publishToMavenCentral|publishAllPublicationsTo.*|publishPlugins|uploadArchives|.*[Dd]eploy.*|release)$/.test(x)) ? { label: `${name} ${argv.find((x) => /publish|[Dd]eploy|release|upload/.test(x))}`, kind: 'publish' } : undefined;
622
+ case 'goreleaser':
623
+ return sub === 'release' && !argv.includes('--snapshot') ? { label: 'goreleaser release', kind: 'publish' } : undefined;
624
+ case 'fastlane': case 'bundle':
625
+ return argv.some((x) => /^(release|deploy|beta|upload_to_app_store|deliver|pilot|supply|upload_to_play_store|appstore|production)$/.test(x)) ? { label: `fastlane ${w.find((x) => x !== 'exec' && x !== 'fastlane')}`, kind: 'publish' } : undefined;
626
+ case 'expo': case 'eas':
627
+ return (sub === 'submit' || sub === 'update' || (sub === 'build' && argv.includes('--auto-submit')) || sub === 'publish') ? { label: `${name} ${sub}`, kind: 'publish' } : undefined;
628
+ case 'vsce': case 'ovsx':
629
+ return ['publish', 'unpublish'].includes(sub) ? { label: `${name} ${sub}`, kind: 'publish' } : undefined;
630
+ case 'chmod': case 'chown':
631
+ return hasFlag(argv, 'R', '--recursive') && w.some((t) => t === '/' || /^\/(etc|usr|var|bin|home|Users)\/?$/.test(t)) ? { label: `${name} -R on a system folder`, kind: 'system' } : undefined;
632
+ case 'crontab':
633
+ return argv.includes('-r') ? { label: 'crontab -r removes every cron job', kind: 'system' } : undefined;
634
+ case 'kill': case 'pkill': case 'killall':
635
+ return w.includes('1') || w.includes('-1') ? { label: `${name} every process`, kind: 'system' } : undefined;
636
+ case 'curl': case 'http': case 'https': case 'xh': case 'wget': {
637
+ const m = flagValues(argv, ['-X', '--request', '--method']).map((x) => x.toUpperCase());
638
+ const httpieMethod = ['http', 'https', 'xh'].includes(name) && /^(DELETE|PUT|PATCH)$/i.test(w[0] ?? '') ? w[0].toUpperCase() : undefined;
639
+ const method = m[0] ?? httpieMethod;
640
+ const url = w.find((x) => /^https?:\/\//.test(x) || /^[\w.-]+\.[a-z]{2,}(\/|$)/.test(x));
641
+ if ((method === 'DELETE' || method === 'PUT' || method === 'PATCH') && url && !/^(https?:\/\/)?(localhost|127\.|0\.0\.0\.0|\[::1\])/.test(url)) return { label: `${method} request to ${url.replace(/^https?:\/\//, '').split(/[/?#]/)[0]}`, kind: 'api' };
642
+ return undefined;
643
+ }
644
+ case 'stripe':
645
+ return w.some((x) => /^(delete|refund|refunds|cancel|payouts|transfers)$/.test(x)) && argv.includes('--live') ? { label: `stripe ${w.slice(0, 2).join(' ')} --live`, kind: 'api' } : undefined;
646
+ default:
647
+ return sqlRule(name, argv, cmd);
648
+ }
649
+ }
650
+
651
+ function gitRule(argv) {
652
+ // Skip git's own options (git -C dir push ...).
653
+ let k = 1;
654
+ while (k < argv.length && argv[k].startsWith('-')) k += /^-(C|c)$|^--(git-dir|work-tree|namespace|exec-path)$/.test(argv[k]) ? 2 : 1;
655
+ const sub = argv[k];
656
+ const rest = argv.slice(k + 1);
657
+ const pos = words(rest);
658
+ switch (sub) {
659
+ case 'push':
660
+ if (hasFlag(rest, 'f', '--force', '--force-with-lease', '--force-if-includes', '--mirror', '--prune') || pos.slice(1).some((r) => r.startsWith('+'))) return { label: 'git push --force rewrites remote history', kind: 'git' };
661
+ if (hasFlag(rest, 'd', '--delete') || pos.slice(1).some((r) => r.startsWith(':') && r.length > 1)) return { label: 'git push deletes a remote branch or tag', kind: 'git' };
662
+ return undefined;
663
+ case 'reset':
664
+ return hasFlag(rest, null, '--hard', '--merge', '--keep') ? { label: 'git reset --hard throws away local changes', kind: 'git' } : undefined;
665
+ case 'clean':
666
+ return hasFlag(rest, 'f', '--force') && !hasFlag(rest, 'n', '--dry-run') ? { label: 'git clean deletes untracked files', kind: 'git' } : undefined;
667
+ case 'checkout':
668
+ return (rest.includes('--') && (pos.includes('.') || rest[rest.indexOf('--') + 1] === '.')) || hasFlag(rest, 'f', '--force') ? { label: 'git checkout throws away local changes', kind: 'git' } : undefined;
669
+ case 'restore':
670
+ return !hasFlag(rest, 'S', '--staged') || hasFlag(rest, 'W', '--worktree') ? (pos.includes('.') || pos.some((p) => p.includes('*')) || hasFlag(rest, null, '--source') ? { label: 'git restore throws away local changes', kind: 'git' } : undefined) : undefined;
671
+ case 'branch':
672
+ return hasFlag(rest, 'D') || (hasFlag(rest, 'd', '--delete') && hasFlag(rest, 'f', '--force')) || (hasFlag(rest, 'M') ) ? { label: 'git branch -D deletes an unmerged branch', kind: 'git' } : undefined;
673
+ case 'tag':
674
+ return hasFlag(rest, 'd', '--delete') || hasFlag(rest, 'f', '--force') ? { label: `git tag ${hasFlag(rest, 'd', '--delete') ? '-d' : '-f'}`, kind: 'git' } : undefined;
675
+ case 'stash':
676
+ return ['clear', 'drop'].includes(pos[0]) ? { label: `git stash ${pos[0]}`, kind: 'git' } : undefined;
677
+ case 'filter-branch': case 'filter-repo': case 'replace':
678
+ return { label: `git ${sub} rewrites history`, kind: 'git' };
679
+ case 'reflog':
680
+ return ['expire', 'delete'].includes(pos[0]) ? { label: `git reflog ${pos[0]}`, kind: 'git' } : undefined;
681
+ case 'update-ref':
682
+ return hasFlag(rest, 'd') ? { label: 'git update-ref -d', kind: 'git' } : undefined;
683
+ case 'gc':
684
+ return rest.some((x) => x.startsWith('--prune=now')) ? { label: 'git gc --prune=now', kind: 'git' } : undefined;
685
+ case 'rebase': case 'commit':
686
+ return undefined;
687
+ case 'lfs':
688
+ return pos[0] === 'prune' ? { label: 'git lfs prune', kind: 'git' } : undefined;
689
+ default:
690
+ return undefined;
691
+ }
692
+ }
693
+
694
+ function compile(list) {
695
+ return (list ?? []).filter(Boolean).map((p) => (p instanceof RegExp ? p : new RegExp(p)));
696
+ }
697
+
698
+ /**
699
+ * Decides one shell command line. opts.always and opts.never are regular
700
+ * expressions (strings or RegExp) tested against the whole line and each
701
+ * simple command; never wins over the built-in rules, always over never.
702
+ * Returns { gate, reasons: [{ label, kind, command, remote }], warnings }.
703
+ */
704
+ export function classifyShell(line, opts = {}) {
705
+ const always = compile(opts.always);
706
+ const never = compile(opts.never);
707
+ const reasons = [];
708
+ const warnings = [];
709
+ const seen = new Set();
710
+ const visit = (text, depth, remote) => {
711
+ if (depth > 6) {
712
+ reasons.push({ label: 'nested too deeply to check', kind: 'unknown', command: text.slice(0, 200), remote });
713
+ return;
714
+ }
715
+ let cmds;
716
+ try {
717
+ cmds = splitShell(text);
718
+ } catch {
719
+ reasons.push({ label: 'could not read the command', kind: 'unknown', command: text.slice(0, 200), remote });
720
+ return;
721
+ }
722
+ for (const c of cmds) {
723
+ const u = unwrap(c.argv);
724
+ for (const inner of u.inner ?? []) visit(inner, depth + 1, remote || u.remote);
725
+ if (!u.argv?.length) continue;
726
+ const simple = u.argv.join(' ');
727
+ if (always.some((r) => r.test(simple))) {
728
+ reasons.push({ label: 'matches your always-ask list', kind: 'custom', command: simple, remote });
729
+ continue;
730
+ }
731
+ if (never.some((r) => r.test(simple))) continue;
732
+ const r = rule(u.argv, c);
733
+ if (r && !seen.has(r.label + simple)) {
734
+ seen.add(r.label + simple);
735
+ reasons.push({ label: r.label, kind: r.kind, command: simple, remote });
736
+ warnings.push(...(r.warnings ?? []));
737
+ }
738
+ }
739
+ };
740
+ const whole = String(line ?? '');
741
+ if (always.some((r) => r.test(whole))) {
742
+ reasons.push({ label: 'matches your always-ask list', kind: 'custom', command: whole.slice(0, 200) });
743
+ } else if (never.some((r) => r.test(whole))) {
744
+ return { gate: false, reasons: [], warnings: [] };
745
+ }
746
+ visit(whole, 0, false);
747
+ return { gate: reasons.length > 0, reasons, warnings: [...new Set(warnings)] };
748
+ }