@aisac/cli 0.4.0-beta.21 → 0.4.0-beta.23

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.
@@ -0,0 +1,2166 @@
1
+ // @ts-check
2
+ /**
3
+ * The reserve of delegated approvals (spec aisac-engineering-manager D16, FR13).
4
+ *
5
+ * While the user has lent a worker's approvals to the manager, the worker's adapter
6
+ * asks this module, before anything else, whether a Codex approval request must still
7
+ * wait for the user in the worker's terminal. The decision is code only and reads the
8
+ * request alone: no model, no file system, no process. It fails closed: a request it
9
+ * cannot read in full is reserved, and an error inside it reserves the request as
10
+ * `opaque`.
11
+ *
12
+ * It reads command lines, not what they run: a script or a task runner target
13
+ * (`./deploy.sh`, `make release`, `npm run deploy`) reaches the manager, and the
14
+ * playbook is the control there (threat model).
15
+ */
16
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
17
+ import { preferencesPath } from '../extensions-preferences.mjs';
18
+ import {
19
+ GIT_OPTIONS_WITH_VALUE,
20
+ MAX_NESTING,
21
+ destructiveGuard,
22
+ gitGuard,
23
+ secretsGuard,
24
+ } from '../guardrails/guards.mjs';
25
+ import { effectiveWords, programName, splitShell } from '../guardrails/shell-words.mjs';
26
+
27
+ /** @typedef {'secrets'|'git'|'destructive'|'outward'|'privilege'|'opaque'|'permissions'|'files'} ReserveClass */
28
+ /**
29
+ * @typedef {object} ReserveContext
30
+ * @property {string[]} roots absolute real paths of the room's repository worktrees
31
+ * @property {string} stateRoot absolute path of the client's state root (the bus is `<stateRoot>/bus`)
32
+ * @property {string} home the user's home directory
33
+ * @property {string[]} hostConfigDirs absolute paths of host configuration directories
34
+ */
35
+ /** @typedef {{ method: string, params: unknown, filePaths?: string[] | null }} ApprovalRequest */
36
+ /** @typedef {{ reserved: true, class: ReserveClass } | { reserved: false }} ReserveResult */
37
+ /**
38
+ * @typedef {object} ApprovalDescription
39
+ * @property {'command' | 'fileChange' | 'permissions' | 'unknown'} kind
40
+ * @property {string | null} command
41
+ * @property {string | null} cwd
42
+ */
43
+
44
+ /** Longer command text is `opaque`; the decision record keeps the command cut at this length. */
45
+ export const MAX_DELEGABLE_COMMAND_LENGTH = 4000;
46
+
47
+ /**
48
+ * FR13's `outward` list: a program and the words that must follow it, contiguous and
49
+ * anywhere after the program (`gh -R o/r pr merge 1`). An entry of one word reserves
50
+ * every invocation of that program. It is matched on the effective command, after
51
+ * wrappers and package runners (`npx vercel`, `pnpm dlx wrangler`, `env A=1 terraform
52
+ * apply`, `yarn wrangler deploy`). The first group is the spec's list; the second holds
53
+ * equivalent forms and further cloud provider CLIs.
54
+ */
55
+ export const OUTWARD_COMMANDS = Object.freeze(
56
+ [
57
+ 'npm publish',
58
+ 'pnpm publish',
59
+ 'yarn publish',
60
+ 'cargo publish',
61
+ 'gem push',
62
+ 'twine upload',
63
+ 'docker push',
64
+ 'vercel',
65
+ 'wrangler',
66
+ 'netlify',
67
+ 'firebase',
68
+ 'fly',
69
+ 'terraform',
70
+ 'tofu',
71
+ 'pulumi',
72
+ 'kubectl',
73
+ 'helm',
74
+ 'supabase db',
75
+ 'supabase migration',
76
+ 'prisma migrate deploy',
77
+ 'gh pr merge',
78
+ 'gh release',
79
+ 'gh repo',
80
+ 'gh secret',
81
+ 'gh workflow',
82
+ 'aws',
83
+ 'gcloud',
84
+ 'az',
85
+ // Equivalent forms and siblings of the list above.
86
+ 'bun publish',
87
+ 'npm unpublish',
88
+ 'npm dist-tag',
89
+ 'npm deprecate',
90
+ 'twine register',
91
+ 'gem yank',
92
+ 'cargo yank',
93
+ 'poetry publish',
94
+ 'uv publish',
95
+ 'docker --push',
96
+ 'docker-compose push',
97
+ 'podman push',
98
+ 'buildah push',
99
+ 'flyctl',
100
+ 'terragrunt',
101
+ 'cdktf',
102
+ 'ansible',
103
+ 'ansible-playbook',
104
+ 'skaffold',
105
+ 'prisma migrate reset',
106
+ 'prisma db push',
107
+ 'prisma db execute',
108
+ 'sam',
109
+ 'cdk',
110
+ 'eksctl',
111
+ 'gsutil',
112
+ 'bq',
113
+ 'azd',
114
+ 'doctl',
115
+ 'heroku',
116
+ 'oci',
117
+ 'hcloud',
118
+ 'ssh',
119
+ 'scp',
120
+ 'sftp',
121
+ ].map((entry) => Object.freeze(entry.split(' '))),
122
+ );
123
+
124
+ const METHOD_COMMAND = 'item/commandExecution/requestApproval';
125
+ const METHOD_FILE_CHANGE = 'item/fileChange/requestApproval';
126
+ const METHOD_PERMISSIONS = 'item/permissions/requestApproval';
127
+ const PLAIN_ACCEPT = 'accept';
128
+ const COMMAND_KIND = 'command';
129
+ // The execution environment Codex 0.166.0 sends for the worker's own machine (measured
130
+ // by the MG2 spike); null or absent means the same. Any other one may be remote.
131
+ const LOCAL_ENVIRONMENT = 'local';
132
+ // Request fields of Codex 0.166.0 (`codex app-server generate-json-schema --experimental`,
133
+ // and the requests the MG2 spike measured). Another field with a value is a request this
134
+ // module cannot read in full. `commandActions` is Codex's own summary of `command`: it is
135
+ // known, never read; the classification reads `command`, which is what runs.
136
+ const COMMAND_PARAMS = new Set([
137
+ 'threadId',
138
+ 'turnId',
139
+ 'itemId',
140
+ 'startedAtMs',
141
+ 'approvalId',
142
+ 'command',
143
+ 'commandActions',
144
+ 'cwd',
145
+ 'environmentId',
146
+ 'kind',
147
+ 'reason',
148
+ 'additionalPermissions',
149
+ 'networkApprovalContext',
150
+ 'proposedExecpolicyAmendment',
151
+ 'proposedNetworkPolicyAmendments',
152
+ 'availableDecisions',
153
+ ]);
154
+ const FILE_CHANGE_PARAMS = new Set([
155
+ 'threadId',
156
+ 'turnId',
157
+ 'itemId',
158
+ 'startedAtMs',
159
+ 'grantRoot',
160
+ 'reason',
161
+ ]);
162
+
163
+ const BUS_DIRECTORY = 'bus';
164
+ const GIT_DIRECTORY = '.git';
165
+ const MEASURED_SHELLS = new Set(['bash', 'sh', 'zsh']);
166
+ const MEASURED_SHELL_FLAGS = new Set(['-lc', '-c']);
167
+ const MEASURED_WRAPPER_WORDS = 3;
168
+ const MAX_EFFECTIVE_COMMANDS = 256;
169
+ const MAX_BRACE_VARIANTS = 256;
170
+ const MAX_WORK_DIRECTORIES = 16;
171
+ const MAX_SEPARATOR_SCANS = 4;
172
+ // Words after a wrapper that are tried as the wrapped command, so an option value the
173
+ // tables below do not know cannot hide it.
174
+ const WRAPPER_SCAN_WINDOW = 12;
175
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
176
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/u;
177
+ const GLOB_CHARACTERS = /[*?[]/u;
178
+ const URI = /^[a-z][a-z0-9+.-]*:\/\//iu;
179
+ const PRIVILEGE_VARIABLES = /\b(?:AIBRAIN_STATE_DIR|CODEX_HOME|CLAUDE_CONFIG_DIR)\b/u;
180
+
181
+ const PRIVILEGE_PROGRAMS = new Set(['sudo', 'sudoedit', 'su', 'doas', 'pkexec', 'run0']);
182
+ const PREFIX_KEYWORDS = new Set([
183
+ '!',
184
+ '{',
185
+ '}',
186
+ 'if',
187
+ 'then',
188
+ 'else',
189
+ 'elif',
190
+ 'fi',
191
+ 'do',
192
+ 'done',
193
+ 'while',
194
+ 'until',
195
+ 'esac',
196
+ 'coproc',
197
+ ]);
198
+ // `for NAME in WORDS`, `select NAME in WORDS` and `case WORD in` run no program.
199
+ const CLAUSE_KEYWORDS = new Set(['for', 'select', 'case']);
200
+ const FUNCTION_KEYWORD = 'function';
201
+ const WATCH_PROGRAM = 'watch';
202
+ const WATCH_VALUE_OPTIONS = ['-n', '--interval', '-d', '--differences'];
203
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'ash', 'mksh', 'fish']);
204
+ const SHELL_VALUE_OPTIONS = new Set(['-o', '+o', '-O', '+O', '--rcfile', '--init-file']);
205
+ const SHELL_CODE_OPTIONS = new Set(['--command']);
206
+ const EXIT_OPTIONS = new Set(['-v', '-V', '--version', '-h', '--help']);
207
+ const DANGEROUS_SHELL_OPTIONS = new Set(['expand_aliases', 'dotglob', 'nocaseglob', 'extglob']);
208
+ const BUILTIN_DECLARATIONS = new Set(['export', 'declare', 'typeset', 'readonly', 'local']);
209
+
210
+ /**
211
+ * Wrappers that run the command after their options: the options that take a separate
212
+ * value, how many positional words come before the command, and the options whose
213
+ * value is a whole shell command.
214
+ * @typedef {{ values?: string[], positionals?: number, scripts?: string[], dynamicArgs?: boolean }} WrapperSpec
215
+ * @type {ReadonlyMap<string, WrapperSpec>}
216
+ */
217
+ const WRAPPERS = new Map(
218
+ Object.entries({
219
+ env: { values: ['-u', '--unset', '-C', '--chdir'], scripts: ['-S', '--split-string'] },
220
+ command: {},
221
+ builtin: {},
222
+ nohup: {},
223
+ exec: { values: ['-a'] },
224
+ nice: { values: ['-n', '--adjustment'] },
225
+ time: { values: ['-f', '--format', '-o', '--output'] },
226
+ timeout: { values: ['-s', '--signal', '-k', '--kill-after'], positionals: 1 },
227
+ gtimeout: { values: ['-s', '--signal', '-k', '--kill-after'], positionals: 1 },
228
+ stdbuf: { values: ['-i', '-o', '-e', '--input', '--output', '--error'] },
229
+ ionice: { values: ['-c', '--class', '-n', '--classdata'] },
230
+ setsid: {},
231
+ chrt: { positionals: 1 },
232
+ taskset: { values: ['-c', '--cpu-list'], positionals: 1 },
233
+ strace: { values: ['-o', '-e', '-p', '-s', '-u', '-E'] },
234
+ ltrace: { values: ['-o', '-e', '-p', '-s', '-u'] },
235
+ unbuffer: {},
236
+ caffeinate: { values: ['-w', '-t'] },
237
+ chronic: {},
238
+ nocache: {},
239
+ flock: {
240
+ values: ['-w', '--timeout', '-E', '--conflict-exit-code'],
241
+ positionals: 1,
242
+ scripts: ['-c', '--command'],
243
+ },
244
+ script: { scripts: ['-c', '--command'] },
245
+ 'cross-env': {},
246
+ 'env-cmd': { values: ['-f', '--file', '-e', '--environments', '-r', '--rc-file'] },
247
+ dotenv: { values: ['-e', '-c', '-v', '-p'] },
248
+ parallel: {},
249
+ xargs: {
250
+ values: ['-I', '-L', '-n', '-P', '-s', '-d', '-E', '-a', '--arg-file', '--delimiter'],
251
+ dynamicArgs: true,
252
+ },
253
+ sudo: {
254
+ values: [
255
+ '-u',
256
+ '-g',
257
+ '-C',
258
+ '-D',
259
+ '-h',
260
+ '-p',
261
+ '-r',
262
+ '-t',
263
+ '-U',
264
+ '--user',
265
+ '--group',
266
+ '--chdir',
267
+ ],
268
+ },
269
+ doas: { values: ['-u', '-C'] },
270
+ pkexec: { values: ['--user'] },
271
+ run0: { values: ['-u', '--user', '-g', '--group', '-D', '--chdir'] },
272
+ su: { scripts: ['-c', '--command'] },
273
+ }),
274
+ );
275
+ /** Package runners: the next word is a package's binary. */
276
+ const RUNNERS = new Set(['npx', 'pnpx', 'bunx']);
277
+ const RUNNER_VALUE_OPTIONS = ['-p', '--package', '-w', '--workspace'];
278
+ const RUNNER_SCRIPT_OPTIONS = ['-c', '--call'];
279
+ /** The subcommands of a package manager that run a package's binary. */
280
+ const MANAGER_RUNNERS = Object.freeze({
281
+ npm: new Set(['exec', 'x']),
282
+ pnpm: new Set(['dlx', 'exec']),
283
+ yarn: new Set(['dlx', 'exec']),
284
+ bun: new Set(['x']),
285
+ });
286
+ /** Package managers that run a local binary named as their first word (`yarn wrangler`). */
287
+ const BINARY_MANAGERS = new Set(['pnpm', 'yarn', 'bun']);
288
+ const MANAGER_VALUE_OPTIONS = [
289
+ '-C',
290
+ '--dir',
291
+ '--filter',
292
+ '-F',
293
+ '--cwd',
294
+ '-w',
295
+ '--workspace',
296
+ '--prefix',
297
+ ];
298
+
299
+ /**
300
+ * Interpreters other than the shells: an option that gives the program text inline or
301
+ * names a module, the options that take a separate value. Without either and without a
302
+ * script operand the interpreter reads its program from standard input.
303
+ * @type {ReadonlyArray<{ names: RegExp, code: RegExp, long: string[], values: string[] }>}
304
+ */
305
+ const INTERPRETERS = Object.freeze([
306
+ { names: /^python[0-9.]*$/u, code: /^-[A-Za-z]*[cm]/u, long: [], values: ['-W', '-X'] },
307
+ {
308
+ names: /^(?:node|nodejs)$/u,
309
+ code: /^-[A-Za-z]*[epc]/u,
310
+ long: ['--eval', '--print', '--test', '--run', '--check'],
311
+ values: [
312
+ '-r',
313
+ '--require',
314
+ '--import',
315
+ '--loader',
316
+ '--experimental-loader',
317
+ '-C',
318
+ '--conditions',
319
+ ],
320
+ },
321
+ { names: /^perl$/u, code: /^-[A-Za-z]*[eE]/u, long: [], values: [] },
322
+ { names: /^(?:ruby|lua|osascript)$/u, code: /^-[A-Za-z]*e/u, long: [], values: [] },
323
+ { names: /^php$/u, code: /^-[A-Za-z]*[rf]/u, long: [], values: [] },
324
+ ]);
325
+
326
+ // Variables that load code into, or redefine, the programs a command runs.
327
+ const INJECTION_VARIABLES = new Set([
328
+ 'PATH',
329
+ 'HOME',
330
+ 'ENV',
331
+ 'BASH_ENV',
332
+ 'SHELLOPTS',
333
+ 'BASHOPTS',
334
+ 'PS4',
335
+ 'PROMPT_COMMAND',
336
+ 'IFS',
337
+ 'GLOBIGNORE',
338
+ 'CDPATH',
339
+ 'ZDOTDIR',
340
+ 'XDG_CONFIG_HOME',
341
+ 'NODE_OPTIONS',
342
+ 'NODE_PATH',
343
+ 'PYTHONPATH',
344
+ 'PYTHONSTARTUP',
345
+ 'PYTHONHOME',
346
+ 'PERL5OPT',
347
+ 'PERL5LIB',
348
+ 'PERLLIB',
349
+ 'RUBYOPT',
350
+ 'RUBYLIB',
351
+ 'EDITOR',
352
+ 'VISUAL',
353
+ 'SSH_ASKPASS',
354
+ 'SUDO_ASKPASS',
355
+ ]);
356
+ const INJECTION_PREFIXES = ['LD_', 'DYLD_', 'GIT_', 'BASH_FUNC_', 'NPM_CONFIG_'];
357
+ const SAFE_GIT_VARIABLES = new Set([
358
+ 'GIT_AUTHOR_NAME',
359
+ 'GIT_AUTHOR_EMAIL',
360
+ 'GIT_AUTHOR_DATE',
361
+ 'GIT_COMMITTER_NAME',
362
+ 'GIT_COMMITTER_EMAIL',
363
+ 'GIT_COMMITTER_DATE',
364
+ 'GIT_TERMINAL_PROMPT',
365
+ ]);
366
+ const PAGER_VARIABLES = new Set(['PAGER', 'GIT_PAGER']);
367
+ const SAFE_PAGER_VALUES = new Set(['', 'cat']);
368
+
369
+ // `git` global options that take a separate value: the ones gitGuard skips, and more.
370
+ const GIT_GLOBAL_VALUE_OPTIONS = new Set([...GIT_OPTIONS_WITH_VALUE, '--super-prefix']);
371
+ const GIT_CONFIG_OPTION = '-c';
372
+ const SAFE_GIT_CONFIG_KEYS = new Set([
373
+ 'user.name',
374
+ 'user.email',
375
+ 'commit.gpgsign',
376
+ 'tag.gpgsign',
377
+ 'core.quotepath',
378
+ 'core.autocrlf',
379
+ 'init.defaultbranch',
380
+ 'pull.rebase',
381
+ 'merge.conflictstyle',
382
+ ]);
383
+ const SAFE_GIT_CONFIG_PREFIXES = ['advice.', 'color.'];
384
+ const PUSH_VALUE_OPTIONS = new Set(['-o', '--push-option', '--receive-pack', '--exec']);
385
+ const UNCLEAR_DESTINATIONS = new Set(['', 'HEAD', '@']);
386
+ const DYNAMIC_REFSPEC = /[$`*?[\]{}]/u;
387
+ const TAG_REFSPEC = 'tag';
388
+
389
+ const REMOVAL_PROGRAM = 'rm';
390
+ const FIND_PROGRAM = 'find';
391
+ const FIND_EXEC_ACTIONS = new Set(['-exec', '-execdir', '-ok', '-okdir']);
392
+ const FIND_EXEC_ENDS = new Set([';', '+']);
393
+ const FIND_DELETE = '-delete';
394
+ const FIND_NAME_TESTS = new Set([
395
+ '-name',
396
+ '-iname',
397
+ '-path',
398
+ '-ipath',
399
+ '-regex',
400
+ '-iregex',
401
+ '-wholename',
402
+ ]);
403
+ const FIND_PLACEHOLDER = '{}';
404
+ const ROOT_LIKE_DEPTH = 1;
405
+ const NO_PRESERVE_ROOT = '--no-preserve-root';
406
+ // Beyond destructive-guard: programs that format or wipe a device, `dd` writing to a
407
+ // device, and a recursive change of mode or owner on a root-like target.
408
+ const DEVICE_WIPERS = new Set(['mkfs', 'mke2fs', 'mkswap', 'wipefs']);
409
+ const MKFS_PREFIX = 'mkfs.';
410
+ const DD_PROGRAM = 'dd';
411
+ const DD_OUTPUT = 'of=';
412
+ const DEVICE_DIRECTORY = '/dev/';
413
+ const HARMLESS_DEVICES = new Set(['/dev/null', '/dev/stdout', '/dev/stderr', '/dev/tty']);
414
+ const OWNERSHIP_PROGRAMS = new Set(['chmod', 'chown', 'chgrp']);
415
+ const OWNERSHIP_RECURSIVE = /^-[A-Za-z]*R/u;
416
+
417
+ // FR13 `files`, the command row: a path a command names, outright, as one it writes or
418
+ // removes, outside every root. Temporary directories and the harmless devices are not
419
+ // reserved by it; a dynamic path (`$OUT`) is left to the playbook.
420
+ const TEMPORARY_DIRECTORIES = ['/tmp', '/var/tmp'];
421
+ const STDIO_OPERAND = '-';
422
+ const OPTION_END = '--';
423
+ // A `#` after one of these starts a comment; a redirection target ends at one of those.
424
+ const WORD_BREAK = /[\s;&|()]/u;
425
+ const TARGET_END = /[\s;&|()<>]/u;
426
+ const DESCRIPTOR = /[\d-]/u;
427
+ const DOUBLE_QUOTE_ESCAPE = /\\(["\\$`])/gu;
428
+ const GIT_PROGRAM = 'git';
429
+ const GIT_DIRECTORY_OPTION = '-C';
430
+ /** @type {ReadonlySet<string>} */
431
+ const NO_OPTIONS = new Set();
432
+ const TARGET_DIRECTORY_OPTIONS = ['-t', '--target-directory'];
433
+ const SUFFIX_OPTIONS = ['-S', '--suffix'];
434
+ /**
435
+ * @typedef {object} WriterSpec
436
+ * @property {'all' | 'last'} operands every operand is written or removed, or only the
437
+ * last one of two or more (the destination)
438
+ * @property {ReadonlySet<string>} [values] options that take a value
439
+ * @property {ReadonlySet<string>} [targets] options whose value is a written path
440
+ * @property {ReadonlySet<string>} [allWhen] options that make every operand written
441
+ */
442
+ /** @type {ReadonlyMap<string, WriterSpec>} */
443
+ const WRITERS = new Map([
444
+ ['mkdir', { operands: 'all', values: new Set(['-m', '--mode']) }],
445
+ ['touch', { operands: 'all', values: new Set(['-d', '--date', '-r', '--reference', '-t']) }],
446
+ ['rm', { operands: 'all' }],
447
+ ['rmdir', { operands: 'all' }],
448
+ ['unlink', { operands: 'all' }],
449
+ ['tee', { operands: 'all' }],
450
+ ['truncate', { operands: 'all', values: new Set(['-s', '--size', '-r', '--reference']) }],
451
+ ['chmod', { operands: 'all' }],
452
+ ['chown', { operands: 'all' }],
453
+ ['chgrp', { operands: 'all' }],
454
+ [
455
+ 'mv',
456
+ {
457
+ operands: 'all',
458
+ values: new Set(SUFFIX_OPTIONS),
459
+ targets: new Set(TARGET_DIRECTORY_OPTIONS),
460
+ },
461
+ ],
462
+ [
463
+ 'cp',
464
+ {
465
+ operands: 'last',
466
+ values: new Set(SUFFIX_OPTIONS),
467
+ targets: new Set(TARGET_DIRECTORY_OPTIONS),
468
+ },
469
+ ],
470
+ [
471
+ 'ln',
472
+ {
473
+ operands: 'last',
474
+ values: new Set(SUFFIX_OPTIONS),
475
+ targets: new Set(TARGET_DIRECTORY_OPTIONS),
476
+ },
477
+ ],
478
+ [
479
+ 'install',
480
+ {
481
+ operands: 'last',
482
+ values: new Set([
483
+ ...SUFFIX_OPTIONS,
484
+ '-m',
485
+ '--mode',
486
+ '-o',
487
+ '--owner',
488
+ '-g',
489
+ '--group',
490
+ '--strip-program',
491
+ ]),
492
+ targets: new Set(TARGET_DIRECTORY_OPTIONS),
493
+ allWhen: new Set(['-d', '--directory']),
494
+ },
495
+ ],
496
+ [
497
+ 'rsync',
498
+ {
499
+ operands: 'last',
500
+ values: new Set([
501
+ '-e',
502
+ '--rsh',
503
+ '-f',
504
+ '--filter',
505
+ '--exclude',
506
+ '--include',
507
+ '--exclude-from',
508
+ '--include-from',
509
+ '--files-from',
510
+ '--compare-dest',
511
+ '--copy-dest',
512
+ '--link-dest',
513
+ '--chmod',
514
+ '--chown',
515
+ '--rsync-path',
516
+ '--password-file',
517
+ '--port',
518
+ '--timeout',
519
+ '--bwlimit',
520
+ '--suffix',
521
+ '-B',
522
+ '--block-size',
523
+ '-M',
524
+ '--remote-option',
525
+ ]),
526
+ targets: new Set(['-T', '--temp-dir', '--partial-dir', '--backup-dir', '--log-file']),
527
+ },
528
+ ],
529
+ ]);
530
+ const UNZIP_PROGRAM = 'unzip';
531
+ const UNZIP_TARGETS = new Set(['-d']);
532
+ const TAR_PROGRAM = 'tar';
533
+ const TAR_TARGETS = new Set(['-C', '--directory']);
534
+ const TAR_VALUE_OPTIONS = new Set([
535
+ '-f',
536
+ '--file',
537
+ '-b',
538
+ '--blocking-factor',
539
+ '-T',
540
+ '--files-from',
541
+ '-X',
542
+ '--exclude-from',
543
+ '--exclude',
544
+ '-g',
545
+ '--listed-incremental',
546
+ '-F',
547
+ '--info-script',
548
+ '-K',
549
+ '-L',
550
+ '-N',
551
+ '-V',
552
+ '--label',
553
+ '-H',
554
+ '--format',
555
+ '--owner',
556
+ '--group',
557
+ '--mode',
558
+ '--transform',
559
+ ]);
560
+ // The operation letters of the first `tar` word, cut where a letter takes a value.
561
+ const TAR_OPERATION = /^-?([A-Za-z]+)/u;
562
+ const TAR_VALUE_LETTER = /[CfbFgHKLNTVX]/u;
563
+ // Creating, appending or updating: `-C` is then where tar reads from.
564
+ const TAR_READING_LETTERS = /[cruA]/u;
565
+ const TAR_READING_MODES = new Set(['--create', '--append', '--update', '--catenate']);
566
+ const SED_PROGRAM = 'sed';
567
+ const SED_SCRIPT_OPTIONS = new Set(['-e', '--expression', '-f', '--file']);
568
+ const SED_VALUE_OPTIONS = new Set([...SED_SCRIPT_OPTIONS, '-l', '--line-length']);
569
+ const SED_IN_PLACE = '--in-place';
570
+ const SED_CLUSTER = /^-([A-Za-z]*)/u;
571
+ const SED_VALUE_LETTER = /[efl]/u;
572
+ const PERL_PROGRAM = 'perl';
573
+ const PERL_IN_PLACE = 'i';
574
+ const PERL_CODE_SWITCHES = new Set(['e', 'E']);
575
+ // Switches whose argument is the rest of the word (`-Mstrict`, `-I lib`).
576
+ const PERL_ARGUMENT_SWITCHES = new Set(['d', 'D', 'I', 'm', 'M', 'x']);
577
+ // Switches followed by optional digits (`-l`, `-0777`, `-C7`).
578
+ const PERL_DIGIT_SWITCHES = new Set(['0', 'l', 'C']);
579
+ const PERL_SEPARATE_VALUE = 'I';
580
+ const GIT_CLONE_VALUE_OPTIONS = new Set([
581
+ '-o',
582
+ '--origin',
583
+ '-b',
584
+ '--branch',
585
+ '-u',
586
+ '--upload-pack',
587
+ '--reference',
588
+ '--reference-if-able',
589
+ '--depth',
590
+ '-c',
591
+ '--config',
592
+ '--template',
593
+ '-j',
594
+ '--jobs',
595
+ '--filter',
596
+ '--bundle-uri',
597
+ '--shallow-since',
598
+ '--shallow-exclude',
599
+ '--server-option',
600
+ ]);
601
+ const GIT_INIT_VALUE_OPTIONS = new Set(['--template', '-b', '--initial-branch']);
602
+ const GIT_SEPARATE_DIR = new Set(['--separate-git-dir']);
603
+ const GIT_WORKTREE_VALUE_OPTIONS = new Set(['-b', '-B', '--reason']);
604
+
605
+ const REMOTE_DATABASE_CLIENTS = new Set([
606
+ 'psql',
607
+ 'mysql',
608
+ 'mariadb',
609
+ 'sqlcmd',
610
+ 'clickhouse-client',
611
+ 'cockroach',
612
+ 'mongosh',
613
+ 'mongo',
614
+ 'redis-cli',
615
+ 'pg_restore',
616
+ ]);
617
+ // The host or server of a client; a URI value is caught as a word of its own.
618
+ const DATABASE_HOST_OPTIONS = new Set(['-h', '--host', '-S', '--server']);
619
+ const LOCAL_HOSTS = new Set(['', 'localhost', '127.0.0.1', '::1', '[::1]']);
620
+ const CONNINFO_HOST = /(?:^|\s)(?:host|hostaddr|service)=(\S*)/u;
621
+ const GH_API = 'api';
622
+ const GH_GRAPHQL = 'graphql';
623
+ const GH_METHOD_OPTIONS = new Set(['-X', '--method']);
624
+ const GH_FIELD_OPTIONS = new Set(['-f', '-F', '--field', '--raw-field', '--input']);
625
+ const READ_METHODS = new Set(['GET', 'HEAD']);
626
+ const RSYNC_REMOTE = /^(?:rsync:\/\/|[^/.\s][^/\s]*:)/u;
627
+ const AISAC_PROGRAMS = new Set(['aisac', 'aibrain']);
628
+ const AISAC_PACKAGE = /^@(?:aisac\/cli|brunobracaioli\/aibrain)(?:@|$)/u;
629
+ const AISAC_CLI_ENTRY = /(?:@aisac[\\/]cli|aibrain)[\\/].*cli\.mjs$/u;
630
+
631
+ /** Names a glob may stand for that the secret rules and the privilege class protect. */
632
+ const SECRET_SAMPLE_NAMES = [
633
+ '.env',
634
+ '.env.local',
635
+ '.env.production',
636
+ '.envrc',
637
+ '.npmrc',
638
+ '.netrc',
639
+ '.pgpass',
640
+ 'credentials.json',
641
+ 'id_rsa',
642
+ 'id_dsa',
643
+ 'id_ecdsa',
644
+ 'id_ed25519',
645
+ '.ssh',
646
+ '.aws',
647
+ '.gnupg',
648
+ ];
649
+
650
+ /**
651
+ * @typedef {object} Scope
652
+ * @property {string | null} cwd
653
+ * @property {string[]} roots
654
+ * @property {string} home
655
+ * @property {string[]} protectedDirs the state root, the bus and the host directories
656
+ * @property {string[]} protectedNames their basenames that start with a dot, lowercase
657
+ * @property {string[]} mentions lowercase spellings of them (absolute, `~/`, `$HOME/`)
658
+ * @property {string[]} criticalDirs what `rm -r` may not remove or contain
659
+ * @property {import('../guardrails/guards.mjs').GuardContext} guard
660
+ */
661
+ /** @typedef {{ words: string[], dynamicArgs: boolean }} EffectiveCommand */
662
+ /**
663
+ * @typedef {object} Reading
664
+ * @property {string[]} texts every shell text read: the command and its nested scripts
665
+ * @property {string[][]} words the words of every simple command, braces expanded
666
+ * @property {string[]} targets redirection targets
667
+ * @property {EffectiveCommand[]} commands every command a line may run, wrappers removed
668
+ * @property {string[]} dirs working directories the line may use (`cwd`, then `cd`)
669
+ * @property {boolean} opaque
670
+ * @property {boolean} privileged
671
+ */
672
+ /** @typedef {{ offset: number, end?: number, dynamicArgs?: boolean, lenient?: boolean }} Inner */
673
+ /** @typedef {{ start: number, end: number, dynamicArgs: boolean, lenient: boolean }} Candidate */
674
+
675
+ /** @param {unknown} value @returns {Record<string, unknown>} */
676
+ function record(value) {
677
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
678
+ ? /** @type {Record<string, unknown>} */ (value)
679
+ : {};
680
+ }
681
+
682
+ /** @param {unknown} value */
683
+ function present(value) {
684
+ return value !== null && value !== undefined;
685
+ }
686
+
687
+ /** @param {unknown} value @returns {value is string} */
688
+ function absolutePath(value) {
689
+ return typeof value === 'string' && isAbsolute(value) && !CONTROL_CHARACTERS.test(value);
690
+ }
691
+
692
+ /** @param {string} path @param {string} directory */
693
+ function within(path, directory) {
694
+ return (
695
+ path === directory || path.startsWith(directory.endsWith(sep) ? directory : directory + sep)
696
+ );
697
+ }
698
+
699
+ /** A word quoted so that the shell splitter reads it back as itself. @param {string} word */
700
+ function quoteWord(word) {
701
+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
702
+ }
703
+
704
+ /** @param {string[]} words */
705
+ function joinWords(words) {
706
+ return words.map(quoteWord).join(' ');
707
+ }
708
+
709
+ /**
710
+ * The inner command of the measured form `/bin/bash -lc '<cmd>'`, or null.
711
+ * @param {string[]} words @param {number} targets
712
+ */
713
+ function measuredInner(words, targets) {
714
+ if (words.length !== MEASURED_WRAPPER_WORDS || targets !== 0) return null;
715
+ const [shell = '', flag = '', inner = ''] = words;
716
+ return MEASURED_SHELLS.has(programName(shell)) && MEASURED_SHELL_FLAGS.has(flag) ? inner : null;
717
+ }
718
+
719
+ /** @param {unknown} command @returns {string | null} */
720
+ function commandText(command) {
721
+ if (typeof command === 'string') {
722
+ const parsed = splitShell(command);
723
+ const only = parsed.ok && parsed.commands.length === 1 ? parsed.commands[0] : undefined;
724
+ return (only && measuredInner(only.words, only.targets.length)) ?? command;
725
+ }
726
+ if (!Array.isArray(command) || !command.every((word) => typeof word === 'string')) return null;
727
+ const words = /** @type {string[]} */ (command);
728
+ return measuredInner(words, 0) ?? joinWords(words);
729
+ }
730
+
731
+ /**
732
+ * The request as the decision record and the manager see it. Never throws.
733
+ * @param {unknown} request
734
+ * @returns {ApprovalDescription}
735
+ */
736
+ export function describeApproval(request) {
737
+ /** @type {ApprovalDescription} */
738
+ const unknown = { kind: 'unknown', command: null, cwd: null };
739
+ try {
740
+ const { method, params } = record(request);
741
+ const fields = record(params);
742
+ const cwd = typeof fields.cwd === 'string' ? fields.cwd : null;
743
+ if (method === METHOD_COMMAND)
744
+ return { kind: 'command', command: commandText(fields.command), cwd };
745
+ if (method === METHOD_FILE_CHANGE) return { kind: 'fileChange', command: null, cwd: null };
746
+ if (method === METHOD_PERMISSIONS) return { kind: 'permissions', command: null, cwd };
747
+ return unknown;
748
+ } catch {
749
+ return unknown;
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Decide whether an approval request stays with the user (FR13 reserve).
755
+ * @param {ApprovalRequest} request
756
+ * @param {ReserveContext} context
757
+ * @returns {ReserveResult}
758
+ */
759
+ export function classifyApproval(request, context) {
760
+ try {
761
+ const reserveClass = classify(request, context);
762
+ return reserveClass === null ? { reserved: false } : { reserved: true, class: reserveClass };
763
+ } catch {
764
+ return { reserved: true, class: 'opaque' };
765
+ }
766
+ }
767
+
768
+ /** @param {ApprovalRequest} request @param {ReserveContext} context @returns {ReserveClass | null} */
769
+ function classify(request, context) {
770
+ const { method, params, filePaths } = record(request);
771
+ if (method !== METHOD_COMMAND && method !== METHOD_FILE_CHANGE) return 'permissions';
772
+ if (typeof params !== 'object' || params === null || Array.isArray(params)) return 'opaque';
773
+ const fields = record(params);
774
+ if (method === METHOD_FILE_CHANGE)
775
+ return classifyFileChange(fields, filePaths, buildScope(context, null));
776
+ const permissions = commandPermissions(fields);
777
+ if (permissions !== null) return permissions;
778
+ if (unknownFields(fields, COMMAND_PARAMS)) return 'opaque';
779
+ if (present(fields.kind) && fields.kind !== COMMAND_KIND) return 'opaque';
780
+ if (present(fields.environmentId) && fields.environmentId !== LOCAL_ENVIRONMENT) return 'opaque';
781
+ if (present(fields.cwd) && !absolutePath(fields.cwd)) return 'opaque';
782
+ const text = commandText(fields.command);
783
+ if (text === null || text.length > MAX_DELEGABLE_COMMAND_LENGTH) return 'opaque';
784
+ const scope = buildScope(context, absolutePath(fields.cwd) ? resolve(fields.cwd) : null);
785
+ return classifyCommand(text, scope);
786
+ }
787
+
788
+ /** @param {Record<string, unknown>} fields @param {Set<string>} known */
789
+ function unknownFields(fields, known) {
790
+ return Object.entries(fields).some(([key, value]) => !known.has(key) && present(value));
791
+ }
792
+
793
+ /**
794
+ * The `permissions` class of a command request: it asks for more than one run of one
795
+ * command, or its only accepted answers cover the session or change a policy.
796
+ * @param {Record<string, unknown>} fields @returns {ReserveClass | null}
797
+ */
798
+ function commandPermissions(fields) {
799
+ if (present(fields.additionalPermissions) || present(fields.networkApprovalContext))
800
+ return 'permissions';
801
+ const amendments = fields.proposedNetworkPolicyAmendments;
802
+ if (present(amendments) && !(Array.isArray(amendments) && amendments.length === 0))
803
+ return 'permissions';
804
+ const decisions = fields.availableDecisions;
805
+ if (present(decisions) && !(Array.isArray(decisions) && decisions.includes(PLAIN_ACCEPT)))
806
+ return 'permissions';
807
+ return null;
808
+ }
809
+
810
+ /** @param {string} path */
811
+ function normalized(path) {
812
+ return resolve(path);
813
+ }
814
+
815
+ /** @param {ReserveContext} context @param {string | null} cwd @returns {Scope} */
816
+ function buildScope(context, cwd) {
817
+ const { roots, stateRoot, home, hostConfigDirs } = record(context);
818
+ if (!absolutePath(home) || !absolutePath(stateRoot)) throw new TypeError('reserve context');
819
+ const validRoots = (Array.isArray(roots) ? roots : [])
820
+ .filter(absolutePath)
821
+ .map(normalized)
822
+ .filter((root) => root !== sep);
823
+ const hosts = (Array.isArray(hostConfigDirs) ? hostConfigDirs : [])
824
+ .filter(absolutePath)
825
+ .map(normalized);
826
+ const state = normalized(stateRoot);
827
+ const homeDir = normalized(home);
828
+ const protectedDirs = [state, join(state, BUS_DIRECTORY), ...hosts];
829
+ return {
830
+ cwd,
831
+ roots: validRoots,
832
+ home: homeDir,
833
+ protectedDirs,
834
+ protectedNames: [...new Set([state, ...hosts].map(dotName).filter((name) => name !== null))],
835
+ mentions: protectedDirs.flatMap((dir) => spellings(dir, homeDir)),
836
+ criticalDirs: [homeDir, state, ...validRoots, ...hosts],
837
+ guard: {
838
+ projectDir: cwd ?? validRoots[0] ?? homeDir,
839
+ home: homeDir,
840
+ prefsPath: preferencesPath(state),
841
+ codexConfigs: hosts.map((dir) => join(dir, 'config.toml')),
842
+ locale: 'en',
843
+ },
844
+ };
845
+ }
846
+
847
+ /** The lowercase basename of a directory when it starts with a dot. @param {string} dir */
848
+ function dotName(dir) {
849
+ const name = dir.split(sep).at(-1) ?? '';
850
+ return name.startsWith('.') ? name.toLowerCase() : null;
851
+ }
852
+
853
+ /** Lowercase spellings of a directory a command may use. @param {string} dir @param {string} home */
854
+ function spellings(dir, home) {
855
+ const forms = [dir];
856
+ if (within(dir, home) && dir !== home) {
857
+ const rest = dir.slice(home.length);
858
+ forms.push(`~${rest}`, `$home${rest}`, `\${home}${rest}`);
859
+ }
860
+ return forms.map((form) => form.toLowerCase());
861
+ }
862
+
863
+ // ---------------------------------------------------------------------------
864
+ // File changes
865
+
866
+ /**
867
+ * @param {Record<string, unknown>} fields @param {unknown} filePaths @param {Scope} scope
868
+ * @returns {ReserveClass | null}
869
+ */
870
+ function classifyFileChange(fields, filePaths, scope) {
871
+ if (present(fields.grantRoot)) return 'permissions';
872
+ if (unknownFields(fields, FILE_CHANGE_PARAMS)) return 'opaque';
873
+ if (!Array.isArray(filePaths) || filePaths.length === 0) return 'files';
874
+ return filePaths.every((path) => delegablePath(path, scope)) ? null : 'files';
875
+ }
876
+
877
+ /** @param {unknown} path @param {Scope} scope */
878
+ function delegablePath(path, scope) {
879
+ if (!absolutePath(path)) return false;
880
+ const target = normalized(path);
881
+ const root = deepestRoot(target, scope.roots);
882
+ if (root === null) return false;
883
+ if (scope.protectedDirs.some((dir) => within(target, dir))) return false;
884
+ const inside = relative(root, target).toLowerCase().split(sep);
885
+ if (inside.includes(GIT_DIRECTORY) || inside.some((part) => scope.protectedNames.includes(part)))
886
+ return false;
887
+ return [target, target.toLowerCase()].every(
888
+ (candidate) =>
889
+ secretsGuard({ tool_name: 'Write', tool_input: { file_path: candidate } }, scope.guard) ===
890
+ null,
891
+ );
892
+ }
893
+
894
+ /** The deepest root that holds a path, or null. @param {string} path @param {string[]} roots */
895
+ function deepestRoot(path, roots) {
896
+ const holders = roots.filter((root) => within(path, root));
897
+ return holders.length === 0 ? null : holders.reduce((a, b) => (b.length > a.length ? b : a));
898
+ }
899
+
900
+ // ---------------------------------------------------------------------------
901
+ // Commands
902
+
903
+ /** @param {string} text @param {Scope} scope @returns {ReserveClass | null} */
904
+ function classifyCommand(text, scope) {
905
+ /** @type {Reading} */
906
+ const reading = {
907
+ texts: [],
908
+ words: [],
909
+ targets: [],
910
+ commands: [],
911
+ dirs: scope.cwd === null ? [] : [scope.cwd],
912
+ opaque: false,
913
+ privileged: false,
914
+ };
915
+ readText(text, 0, reading, scope);
916
+ if (reading.opaque) return 'opaque';
917
+ if (touchesSecrets(reading, scope)) return 'secrets';
918
+ if (pushesProtected(reading, scope)) return 'git';
919
+ if (destroys(reading, scope)) return 'destructive';
920
+ if (reading.commands.some(outward)) return 'outward';
921
+ if (needsPrivilege(reading, scope)) return 'privilege';
922
+ if (writesOutsideRoots(reading, scope)) return 'files';
923
+ return null;
924
+ }
925
+
926
+ /**
927
+ * Read one shell text (the command, or a script nested in it) into the reading.
928
+ * @param {string} text @param {number} depth @param {Reading} reading @param {Scope} scope
929
+ */
930
+ function readText(text, depth, reading, scope) {
931
+ if (reading.opaque) return;
932
+ if (depth > MAX_NESTING || unreadableSyntax(text)) {
933
+ reading.opaque = true;
934
+ return;
935
+ }
936
+ const parsed = splitShell(text);
937
+ if (!parsed.ok) {
938
+ reading.opaque = true;
939
+ return;
940
+ }
941
+ reading.texts.push(text);
942
+ for (const item of parsed.commands) {
943
+ reading.targets.push(...item.targets);
944
+ const words = expandWords(item.words);
945
+ if (words === null) {
946
+ reading.opaque = true;
947
+ return;
948
+ }
949
+ reading.words.push(words);
950
+ readCommand(words, depth, reading, scope);
951
+ if (reading.opaque) return;
952
+ }
953
+ }
954
+
955
+ /**
956
+ * Shell syntax the splitter keeps inside a word without reading it: command and process
957
+ * substitution, heredocs and here-strings, ANSI-C and locale quoting, unclosed quotes.
958
+ * @param {string} text
959
+ */
960
+ function unreadableSyntax(text) {
961
+ let inDouble = false;
962
+ for (let index = 0; index < text.length; index += 1) {
963
+ const char = text[index];
964
+ const next = text[index + 1];
965
+ if (char === '\\') {
966
+ index += 1;
967
+ } else if (inDouble) {
968
+ if (char === '"') inDouble = false;
969
+ else if (char === '`' || (char === '$' && next === '(')) return true;
970
+ } else if (char === "'") {
971
+ const close = text.indexOf("'", index + 1);
972
+ if (close === -1) return true;
973
+ index = close;
974
+ } else if (char === '"') {
975
+ inDouble = true;
976
+ } else if (char === '#' && (index === 0 || /[\s;&|()]/u.test(text[index - 1] ?? ''))) {
977
+ const newline = text.indexOf('\n', index);
978
+ index = newline === -1 ? text.length : newline;
979
+ } else if (char === '`') {
980
+ return true;
981
+ } else if (char === '$' && (next === '(' || next === "'" || next === '"')) {
982
+ return true;
983
+ } else if ((char === '<' || char === '>') && next === '(') {
984
+ return true;
985
+ } else if (char === '<' && next === '<') {
986
+ return true;
987
+ }
988
+ }
989
+ return inDouble;
990
+ }
991
+
992
+ /**
993
+ * Brace expansion (`.{e,x}nv` is `.env .xnv`), as the shell does before it runs a word.
994
+ * A range (`{a..z}`) or more than MAX_BRACE_VARIANTS words is not read: null.
995
+ * @param {string[]} words @returns {string[] | null}
996
+ */
997
+ function expandWords(words) {
998
+ /** @type {string[]} */
999
+ const expanded = [];
1000
+ for (const word of words) {
1001
+ const variants = /\s/u.test(word) ? [word] : braceVariants(word);
1002
+ if (variants === null) return null;
1003
+ expanded.push(...variants);
1004
+ if (expanded.length > MAX_BRACE_VARIANTS) return null;
1005
+ }
1006
+ return expanded;
1007
+ }
1008
+
1009
+ /** @param {string} word @returns {string[] | null} */
1010
+ function braceVariants(word) {
1011
+ const group = braceGroup(word);
1012
+ if (group === null) return [word];
1013
+ if (group.alternatives === null) return null;
1014
+ /** @type {string[]} */
1015
+ const variants = [];
1016
+ for (const alternative of group.alternatives) {
1017
+ const more = braceVariants(word.slice(0, group.start) + alternative + word.slice(group.end));
1018
+ if (more === null) return null;
1019
+ variants.push(...more);
1020
+ if (variants.length > MAX_BRACE_VARIANTS) return null;
1021
+ }
1022
+ return variants;
1023
+ }
1024
+
1025
+ /**
1026
+ * The first brace group of a word that the shell expands, or null. `${...}` is a
1027
+ * parameter and `{}` or `{x}` are literal; a range has no alternatives (null).
1028
+ * @param {string} word
1029
+ * @returns {{ start: number, end: number, alternatives: string[] | null } | null}
1030
+ */
1031
+ function braceGroup(word) {
1032
+ for (let start = word.indexOf('{'); start !== -1; start = word.indexOf('{', start + 1)) {
1033
+ const end = closingBrace(word, start);
1034
+ if (end === -1) continue;
1035
+ if (word[start - 1] === '$') {
1036
+ start = end;
1037
+ continue;
1038
+ }
1039
+ const inner = word.slice(start + 1, end);
1040
+ const alternatives = splitTopLevel(inner);
1041
+ if (alternatives.length > 1) return { start, end: end + 1, alternatives };
1042
+ if (/^[^{}]+\.\.[^{}]+$/u.test(inner)) return { start, end: end + 1, alternatives: null };
1043
+ }
1044
+ return null;
1045
+ }
1046
+
1047
+ /** @param {string} word @param {number} start */
1048
+ function closingBrace(word, start) {
1049
+ let depth = 0;
1050
+ for (let index = start; index < word.length; index += 1) {
1051
+ if (word[index] === '{') depth += 1;
1052
+ else if (word[index] === '}') {
1053
+ depth -= 1;
1054
+ if (depth === 0) return index;
1055
+ }
1056
+ }
1057
+ return -1;
1058
+ }
1059
+
1060
+ /** @param {string} inner */
1061
+ function splitTopLevel(inner) {
1062
+ /** @type {string[]} */
1063
+ const parts = [];
1064
+ let depth = 0;
1065
+ let current = '';
1066
+ for (const char of inner) {
1067
+ if (char === ',' && depth === 0) {
1068
+ parts.push(current);
1069
+ current = '';
1070
+ continue;
1071
+ }
1072
+ if (char === '{') depth += 1;
1073
+ if (char === '}') depth -= 1;
1074
+ current += char;
1075
+ }
1076
+ parts.push(current);
1077
+ return parts;
1078
+ }
1079
+
1080
+ /**
1081
+ * Every command a simple command may run: itself, and what its wrappers, package
1082
+ * runners, `xargs`, `find -exec` and the like run in turn.
1083
+ * @param {string[]} words @param {number} depth @param {Reading} reading @param {Scope} scope
1084
+ */
1085
+ function readCommand(words, depth, reading, scope) {
1086
+ /** @type {Candidate[]} */
1087
+ const queue = [{ start: 0, end: words.length, dynamicArgs: false, lenient: false }];
1088
+ /** @type {Map<string, boolean>} whether a start was read strictly */
1089
+ const seen = new Map();
1090
+ while (queue.length > 0 && !reading.opaque) {
1091
+ const candidate = /** @type {Candidate} */ (queue.shift());
1092
+ const key = `${candidate.start}:${candidate.end}:${candidate.dynamicArgs}`;
1093
+ const strictBefore = seen.get(key);
1094
+ if (strictBefore === true || (strictBefore === false && candidate.lenient)) continue;
1095
+ seen.set(key, !candidate.lenient);
1096
+ const start = skipPrefix(words, candidate, reading);
1097
+ if (start === -1 || start >= candidate.end) continue;
1098
+ const head = words[start] ?? '';
1099
+ if (candidate.lenient && (head.startsWith('-') || /\s/u.test(head) || dynamicProgram(head)))
1100
+ continue;
1101
+ if (dynamicProgram(head) || reading.commands.length >= MAX_EFFECTIVE_COMMANDS) {
1102
+ reading.opaque = true;
1103
+ return;
1104
+ }
1105
+ /** @type {EffectiveCommand} */
1106
+ const command = {
1107
+ words: words.slice(start, candidate.end),
1108
+ dynamicArgs: candidate.dynamicArgs,
1109
+ };
1110
+ reading.commands.push(command);
1111
+ const nested = innerCommands(command, depth, reading, scope);
1112
+ // A lenient candidate is a guess past the wrapper's options: it adds commands to
1113
+ // check, but only the exact reading of a line can make it unreadable.
1114
+ if (candidate.lenient) reading.opaque = false;
1115
+ for (const inner of [...nested, ...afterSeparators(command.words)])
1116
+ queue.push({
1117
+ start: start + inner.offset,
1118
+ end: inner.end === undefined ? candidate.end : start + inner.end,
1119
+ dynamicArgs: candidate.dynamicArgs || inner.dynamicArgs === true,
1120
+ lenient: inner.lenient === true,
1121
+ });
1122
+ }
1123
+ }
1124
+
1125
+ /**
1126
+ * The index of the program word: assignments (checked) and shell keywords are skipped.
1127
+ * -1 for a clause that runs no program (`for x in ...`, `case x in`).
1128
+ * @param {string[]} words @param {Candidate} candidate @param {Reading} reading
1129
+ */
1130
+ function skipPrefix(words, candidate, reading) {
1131
+ let index = candidate.start;
1132
+ while (index < candidate.end) {
1133
+ const word = words[index] ?? '';
1134
+ if (ASSIGNMENT.test(word)) {
1135
+ if (!candidate.lenient && unsafeAssignment(word)) reading.opaque = true;
1136
+ index += 1;
1137
+ } else if (PREFIX_KEYWORDS.has(word)) index += 1;
1138
+ else if (word === FUNCTION_KEYWORD) index += 2;
1139
+ else if (CLAUSE_KEYWORDS.has(word)) return -1;
1140
+ else break;
1141
+ }
1142
+ return index;
1143
+ }
1144
+
1145
+ /** A program word the line cannot name in advance. @param {string} word */
1146
+ function dynamicProgram(word) {
1147
+ if (word === '[' || word === '[[') return false;
1148
+ return word.length === 0 || /[$`{}]/u.test(word) || GLOB_CHARACTERS.test(word);
1149
+ }
1150
+
1151
+ /** An assignment that loads code into, or redirects, what the command runs. @param {string} word */
1152
+ function unsafeAssignment(word) {
1153
+ const equals = word.indexOf('=');
1154
+ const name = word.slice(0, word[equals - 1] === '+' ? equals - 1 : equals);
1155
+ const value = word.slice(equals + 1);
1156
+ if (PAGER_VARIABLES.has(name)) return !SAFE_PAGER_VALUES.has(value);
1157
+ if (SAFE_GIT_VARIABLES.has(name)) return false;
1158
+ const upper = name.toUpperCase();
1159
+ return (
1160
+ INJECTION_VARIABLES.has(name) || INJECTION_PREFIXES.some((prefix) => upper.startsWith(prefix))
1161
+ );
1162
+ }
1163
+
1164
+ /** The program's name as the reserve compares it: basename, no `@version`, lowercase. @param {string} word */
1165
+ function programKey(word) {
1166
+ const at = word.lastIndexOf('@');
1167
+ return programName(at > 0 ? word.slice(0, at) : word).toLowerCase();
1168
+ }
1169
+
1170
+ /** `cmd -- other ...`: the words after a separator may be a command (`doppler run -- vercel`). @param {string[]} words @returns {Inner[]} */
1171
+ function afterSeparators(words) {
1172
+ /** @type {Inner[]} */
1173
+ const inner = [];
1174
+ for (let index = 1; index < words.length && inner.length < MAX_SEPARATOR_SCANS; index += 1)
1175
+ if (words[index] === '--' && index + 1 < words.length)
1176
+ inner.push({ offset: index + 1, lenient: true });
1177
+ return inner;
1178
+ }
1179
+
1180
+ /**
1181
+ * What one command runs in turn, as offsets into its words. Nested scripts are read
1182
+ * here (one level deeper) and stdin-fed interpreters make the reading opaque.
1183
+ * @param {EffectiveCommand} command @param {number} depth @param {Reading} reading @param {Scope} scope
1184
+ * @returns {Inner[]}
1185
+ */
1186
+ function innerCommands(command, depth, reading, scope) {
1187
+ const { words } = command;
1188
+ const program = programKey(words[0] ?? '');
1189
+ const nest = (/** @type {string} */ script) => readText(script, depth + 1, reading, scope);
1190
+ if (PRIVILEGE_PROGRAMS.has(program)) reading.privileged = true;
1191
+ const wrapper = WRAPPERS.get(program);
1192
+ if (wrapper !== undefined) return wrapperInner(words, wrapper, nest);
1193
+ if (program === WATCH_PROGRAM) {
1194
+ const index = wrapperEnd(words, { values: WATCH_VALUE_OPTIONS }, nest);
1195
+ nest(words.slice(index).join(' '));
1196
+ return [];
1197
+ }
1198
+ if (RUNNERS.has(program))
1199
+ return wrapperInner(
1200
+ words,
1201
+ { values: RUNNER_VALUE_OPTIONS, scripts: RUNNER_SCRIPT_OPTIONS },
1202
+ nest,
1203
+ );
1204
+ if (Object.hasOwn(MANAGER_RUNNERS, program)) return managerInner(program, words, nest);
1205
+ if (SHELLS.has(program)) return shellInner(command, reading, nest);
1206
+ if (INTERPRETERS.some((family) => family.names.test(program))) {
1207
+ if (command.dynamicArgs || readsProgramFromStdin(program, words)) reading.opaque = true;
1208
+ return [];
1209
+ }
1210
+ return builtinInner(program, command, reading, scope, nest);
1211
+ }
1212
+
1213
+ /**
1214
+ * The wrapped command: the exact position after the wrapper's options, and leniently
1215
+ * every word in the scan window, so an unknown option value cannot hide the command.
1216
+ * @param {string[]} words @param {WrapperSpec} spec @param {(script: string) => void} nest
1217
+ * @returns {Inner[]}
1218
+ */
1219
+ function wrapperInner(words, spec, nest) {
1220
+ const index = wrapperEnd(words, spec, nest);
1221
+ const dynamicArgs = spec.dynamicArgs === true;
1222
+ /** @type {Inner[]} */
1223
+ const inner = index < words.length ? [{ offset: index, dynamicArgs }] : [];
1224
+ const last = Math.min(words.length - 1, WRAPPER_SCAN_WINDOW);
1225
+ for (let offset = 1; offset <= last; offset += 1)
1226
+ if (offset !== index) inner.push({ offset, dynamicArgs, lenient: true });
1227
+ return inner;
1228
+ }
1229
+
1230
+ /**
1231
+ * The index of the wrapped command's first word: after the wrapper's options, their
1232
+ * values and its positional words. Option values that are a whole command are read.
1233
+ * @param {string[]} words @param {WrapperSpec} spec @param {(script: string) => void} nest
1234
+ */
1235
+ function wrapperEnd(words, spec, nest) {
1236
+ const values = new Set(spec.values ?? []);
1237
+ const scripts = new Set(spec.scripts ?? []);
1238
+ let index = 1;
1239
+ let positionals = spec.positionals ?? 0;
1240
+ while (index < words.length) {
1241
+ const word = words[index] ?? '';
1242
+ if (scripts.has(word)) {
1243
+ nest(words[index + 1] ?? '');
1244
+ index += 2;
1245
+ } else if (values.has(word)) index += 2;
1246
+ else if (word.startsWith('-')) index += 1;
1247
+ else if (positionals > 0) {
1248
+ positionals -= 1;
1249
+ index += 1;
1250
+ } else break;
1251
+ }
1252
+ return index;
1253
+ }
1254
+
1255
+ /**
1256
+ * `npm exec`, `pnpm dlx`, `yarn dlx`, `bun x` run a package's binary; `yarn wrangler`
1257
+ * and `pnpm vercel` run a local one.
1258
+ * @param {string} program @param {string[]} words @param {(script: string) => void} nest
1259
+ * @returns {Inner[]}
1260
+ */
1261
+ function managerInner(program, words, nest) {
1262
+ /** @type {Inner[]} */
1263
+ const inner = [];
1264
+ const runners = MANAGER_RUNNERS[/** @type {keyof typeof MANAGER_RUNNERS} */ (program)];
1265
+ const runnerIndex = words.findIndex((word, index) => index > 0 && runners.has(word));
1266
+ if (runnerIndex !== -1) {
1267
+ const after = wrapperInner(
1268
+ words.slice(runnerIndex),
1269
+ { values: RUNNER_VALUE_OPTIONS, scripts: RUNNER_SCRIPT_OPTIONS },
1270
+ nest,
1271
+ );
1272
+ inner.push(...after.map((entry) => ({ ...entry, offset: entry.offset + runnerIndex })));
1273
+ }
1274
+ if (BINARY_MANAGERS.has(program)) {
1275
+ const first = firstPositional(words, new Set(MANAGER_VALUE_OPTIONS));
1276
+ if (first !== -1) inner.push({ offset: first });
1277
+ }
1278
+ return inner;
1279
+ }
1280
+
1281
+ /** @param {string[]} words @param {Set<string>} values */
1282
+ function firstPositional(words, values) {
1283
+ for (let index = 1; index < words.length; index += 1) {
1284
+ const word = words[index] ?? '';
1285
+ if (values.has(word)) index += 1;
1286
+ else if (!word.startsWith('-')) return index;
1287
+ }
1288
+ return -1;
1289
+ }
1290
+
1291
+ /**
1292
+ * A shell: `-c` runs its first operand as a script; without a script operand it reads
1293
+ * its program from standard input (`curl ... | sh`), which no one can read in advance.
1294
+ * @param {EffectiveCommand} command @param {Reading} reading @param {(script: string) => void} nest
1295
+ * @returns {Inner[]}
1296
+ */
1297
+ function shellInner(command, reading, nest) {
1298
+ const { words } = command;
1299
+ let code = false;
1300
+ let stdin = false;
1301
+ let index = 1;
1302
+ for (; index < words.length; index += 1) {
1303
+ const word = words[index] ?? '';
1304
+ if (word === '-') {
1305
+ stdin = true;
1306
+ break;
1307
+ }
1308
+ if (word === '--') {
1309
+ index += 1;
1310
+ break;
1311
+ }
1312
+ const cluster = /^[-+][A-Za-z]+$/u.test(word);
1313
+ if (cluster && word.startsWith('-')) {
1314
+ code ||= word.includes('c');
1315
+ stdin ||= word.includes('s');
1316
+ }
1317
+ // `-o pipefail`, and a cluster that ends in `o` (`-euo pipefail`), take a value.
1318
+ if (SHELL_VALUE_OPTIONS.has(word) || (cluster && /[oO]$/u.test(word))) {
1319
+ if (DANGEROUS_SHELL_OPTIONS.has(words[index + 1] ?? '')) reading.opaque = true;
1320
+ index += 1;
1321
+ } else if (SHELL_CODE_OPTIONS.has(word) || word.startsWith('--command=')) code = true;
1322
+ else if (cluster) continue;
1323
+ else if (EXIT_OPTIONS.has(word)) return [];
1324
+ else if (!word.startsWith('-') && !word.startsWith('+')) break;
1325
+ }
1326
+ if (code) {
1327
+ const inline = words.find((word) => word.startsWith('--command='));
1328
+ nest(inline === undefined ? (words[index] ?? '') : inline.slice('--command='.length));
1329
+ } else if (stdin || index >= words.length || command.dynamicArgs) reading.opaque = true;
1330
+ return [];
1331
+ }
1332
+
1333
+ /** @param {string} program @param {string[]} words */
1334
+ function readsProgramFromStdin(program, words) {
1335
+ const family = INTERPRETERS.find((entry) => entry.names.test(program));
1336
+ if (family === undefined) return false;
1337
+ for (let index = 1; index < words.length; index += 1) {
1338
+ const word = words[index] ?? '';
1339
+ if (word === '-') return true;
1340
+ if (word === '--') return index + 1 >= words.length;
1341
+ if (!word.startsWith('-')) return false;
1342
+ if (family.code.test(word) || family.long.includes(word.split('=')[0] ?? '')) return false;
1343
+ if (EXIT_OPTIONS.has(word)) return false;
1344
+ if (family.values.includes(word)) index += 1;
1345
+ }
1346
+ return true;
1347
+ }
1348
+
1349
+ /**
1350
+ * Shell builtins and programs that run text of their own: `eval`, `trap`, `alias`,
1351
+ * `git submodule foreach`, `find -exec`, `watch`; `cd` moves the working directory.
1352
+ * @param {string} program @param {EffectiveCommand} command @param {Reading} reading
1353
+ * @param {Scope} scope @param {(script: string) => void} nest
1354
+ * @returns {Inner[]}
1355
+ */
1356
+ function builtinInner(program, command, reading, scope, nest) {
1357
+ const { words } = command;
1358
+ const args = words.slice(1);
1359
+ if (program === 'eval') reading.opaque = true;
1360
+ else if (program === 'trap' && args[0] !== undefined && !args[0].startsWith('-')) nest(args[0]);
1361
+ else if (program === 'alias')
1362
+ for (const arg of args) {
1363
+ const equals = arg.indexOf('=');
1364
+ if (equals > 0) nest(arg.slice(equals + 1));
1365
+ }
1366
+ else if (program === 'shopt') {
1367
+ if (args.some((arg) => DANGEROUS_SHELL_OPTIONS.has(arg))) reading.opaque = true;
1368
+ } else if (program === 'hash' || program === 'enable') {
1369
+ if (args.some((arg) => /^-[A-Za-z]*[pf]/u.test(arg))) reading.opaque = true;
1370
+ } else if (BUILTIN_DECLARATIONS.has(program)) {
1371
+ if (args.some((arg) => ASSIGNMENT.test(arg) && unsafeAssignment(arg))) reading.opaque = true;
1372
+ } else if (program === 'cd' || program === 'pushd') changeDirectory(args, reading, scope);
1373
+ else if (program === FIND_PROGRAM) return findInner(words);
1374
+ else if (program === 'git') return gitInner(words, reading, nest);
1375
+ return [];
1376
+ }
1377
+
1378
+ /** @param {string[]} args @param {Reading} reading @param {Scope} scope */
1379
+ function changeDirectory(args, reading, scope) {
1380
+ const target = args.find((arg) => !arg.startsWith('-'));
1381
+ const next =
1382
+ target === undefined || dynamicProgram(target)
1383
+ ? [scope.home]
1384
+ : reading.dirs.length === 0 && !isAbsolute(expandHome(target, scope.home))
1385
+ ? []
1386
+ : resolveAgainst(target, reading.dirs, scope.home);
1387
+ for (const dir of next)
1388
+ if (!reading.dirs.includes(dir) && reading.dirs.length < MAX_WORK_DIRECTORIES)
1389
+ reading.dirs.push(dir);
1390
+ }
1391
+
1392
+ /** `find ... -exec cmd {} ;`: the command between the action and its end. @param {string[]} words @returns {Inner[]} */
1393
+ function findInner(words) {
1394
+ /** @type {Inner[]} */
1395
+ const inner = [];
1396
+ for (let index = 1; index < words.length; index += 1) {
1397
+ if (!FIND_EXEC_ACTIONS.has(words[index] ?? '')) continue;
1398
+ const close = words.findIndex((word, at) => at > index && FIND_EXEC_ENDS.has(word));
1399
+ const end = close === -1 ? words.length : close;
1400
+ if (index + 1 < end) inner.push({ offset: index + 1, end, dynamicArgs: true });
1401
+ index = end;
1402
+ }
1403
+ return inner;
1404
+ }
1405
+
1406
+ /**
1407
+ * `git`: a `-c` that is not plainly harmless can define an alias or a command git
1408
+ * runs, so the line is opaque; `submodule foreach`, `rebase --exec`, `bisect run` and
1409
+ * `filter-branch` run commands of their own.
1410
+ * @param {string[]} words @param {Reading} reading @param {(script: string) => void} nest
1411
+ * @returns {Inner[]}
1412
+ */
1413
+ function gitInner(words, reading, nest) {
1414
+ let index = 1;
1415
+ while (index < words.length && (words[index] ?? '').startsWith('-')) {
1416
+ const option = words[index] ?? '';
1417
+ if (option === GIT_CONFIG_OPTION && !safeGitConfig(words[index + 1] ?? ''))
1418
+ reading.opaque = true;
1419
+ if (option.startsWith('--config-env') || option.startsWith('--exec-path='))
1420
+ reading.opaque = true;
1421
+ index += GIT_GLOBAL_VALUE_OPTIONS.has(option) ? 2 : 1;
1422
+ }
1423
+ const subcommand = words[index] ?? '';
1424
+ const args = words.slice(index + 1);
1425
+ if (subcommand === 'submodule' && args.includes('foreach'))
1426
+ nest(
1427
+ args
1428
+ .slice(args.indexOf('foreach') + 1)
1429
+ .filter((arg) => !arg.startsWith('-'))
1430
+ .join(' '),
1431
+ );
1432
+ else if (subcommand === 'bisect' && args[0] === 'run') return [{ offset: index + 2 }];
1433
+ else if (subcommand === 'rebase')
1434
+ for (const [at, arg] of args.entries()) {
1435
+ if (arg === '-x' || arg === '--exec') nest(args[at + 1] ?? '');
1436
+ else if (arg.startsWith('--exec=')) nest(arg.slice('--exec='.length));
1437
+ }
1438
+ else if (subcommand === 'filter-branch')
1439
+ for (const [at, arg] of args.entries())
1440
+ if (/^--[a-z-]*-filter$/u.test(arg)) nest(args[at + 1] ?? '');
1441
+ return [];
1442
+ }
1443
+
1444
+ /** @param {string} setting `key=value` */
1445
+ function safeGitConfig(setting) {
1446
+ const key = (setting.split('=')[0] ?? '').toLowerCase();
1447
+ return (
1448
+ SAFE_GIT_CONFIG_KEYS.has(key) ||
1449
+ SAFE_GIT_CONFIG_PREFIXES.some((prefix) => key.startsWith(prefix))
1450
+ );
1451
+ }
1452
+
1453
+ // ---------------------------------------------------------------------------
1454
+ // Classes
1455
+
1456
+ /**
1457
+ * A guard's text for one effective command, its program word lowercased (`GIT`, `RM`
1458
+ * on a case-insensitive file system).
1459
+ * @param {EffectiveCommand} command
1460
+ */
1461
+ function commandLine(command) {
1462
+ const [program = '', ...rest] = command.words;
1463
+ return joinWords([program.toLowerCase(), ...rest]);
1464
+ }
1465
+
1466
+ /** @param {Reading} reading */
1467
+ function guardTexts(reading) {
1468
+ return [...reading.texts, ...reading.commands.map(commandLine)];
1469
+ }
1470
+
1471
+ /** @param {string} command */
1472
+ function bash(command) {
1473
+ return { tool_name: 'Bash', tool_input: { command } };
1474
+ }
1475
+
1476
+ /** @param {Reading} reading @param {Scope} scope */
1477
+ function touchesSecrets(reading, scope) {
1478
+ const texts = guardTexts(reading);
1479
+ if (
1480
+ texts.some((text) =>
1481
+ [text, text.toLowerCase()].some((t) => secretsGuard(bash(t), scope.guard) !== null),
1482
+ )
1483
+ )
1484
+ return true;
1485
+ return [...reading.words.flat(), ...reading.targets].some((word) =>
1486
+ globMatches(word, SECRET_SAMPLE_NAMES),
1487
+ );
1488
+ }
1489
+
1490
+ /**
1491
+ * Whether a word with glob characters can stand for one of the names (`.en?`, `id_*`).
1492
+ * A segment that does not start with a dot never matches a dot name (no `dotglob`),
1493
+ * and a segment with no literal start (`*`, `*.json`) is not taken as naming one.
1494
+ * @param {string} word @param {string[]} names
1495
+ */
1496
+ function globMatches(word, names) {
1497
+ if (!GLOB_CHARACTERS.test(word) || /\s/u.test(word)) return false;
1498
+ return word
1499
+ .split(/[/\\]/u)
1500
+ .filter((segment) => GLOB_CHARACTERS.test(segment) && !GLOB_CHARACTERS.test(segment[0] ?? ''))
1501
+ .some((segment) => {
1502
+ const pattern = globPattern(segment);
1503
+ return names.some(
1504
+ (name) => (segment.startsWith('.') || !name.startsWith('.')) && pattern.test(name),
1505
+ );
1506
+ });
1507
+ }
1508
+
1509
+ /** @param {string} segment */
1510
+ function globPattern(segment) {
1511
+ let source = '';
1512
+ for (let index = 0; index < segment.length; index += 1) {
1513
+ const char = segment[index] ?? '';
1514
+ const close = char === '[' ? segment.indexOf(']', index + 2) : -1;
1515
+ if (char === '*') source += '.*';
1516
+ else if (char === '?') source += '.';
1517
+ else if (close !== -1) {
1518
+ const body = segment
1519
+ .slice(index + 1, close)
1520
+ .replace(/^!/u, '^')
1521
+ .replace(/[\\\]]/gu, '\\$&');
1522
+ source += `[${body}]`;
1523
+ index = close;
1524
+ } else source += char.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
1525
+ }
1526
+ return new RegExp(`^${source}$`, 'iu');
1527
+ }
1528
+
1529
+ /** @param {Reading} reading @param {Scope} scope */
1530
+ function pushesProtected(reading, scope) {
1531
+ if (guardTexts(reading).some((text) => gitRefusal(text, scope))) return true;
1532
+ return reading.commands.some(unclearPush);
1533
+ }
1534
+
1535
+ /**
1536
+ * What gitGuard refuses. A push without a refspec makes gitGuard ask git for the
1537
+ * current branch; the reserve runs no process, so such a push is reserved here.
1538
+ * @param {string} text @param {Scope} scope
1539
+ */
1540
+ function gitRefusal(text, scope) {
1541
+ const parsed = splitShell(text);
1542
+ if (!parsed.ok) return false;
1543
+ for (const item of parsed.commands) {
1544
+ const words = effectiveWords(item.words);
1545
+ if (programName(words[0] ?? '') !== 'git') continue;
1546
+ let index = 1;
1547
+ while (index < words.length && (words[index] ?? '').startsWith('-'))
1548
+ index += GIT_OPTIONS_WITH_VALUE.has(words[index] ?? '') ? 2 : 1;
1549
+ if (words[index] !== 'push') continue;
1550
+ if (words.slice(index + 1).filter((word) => !word.startsWith('-')).length < 2) return true;
1551
+ }
1552
+ return gitGuard(bash(text), scope.guard) !== null;
1553
+ }
1554
+
1555
+ /**
1556
+ * A push whose destination the command line does not name: no refspec (the current
1557
+ * branch), `HEAD`, `@`, `:` (every matching branch), a pattern, a variable, `--repo`,
1558
+ * or refspecs that `xargs` or `find` supply.
1559
+ * @param {EffectiveCommand} command
1560
+ */
1561
+ function unclearPush(command) {
1562
+ const { words } = command;
1563
+ if (programKey(words[0] ?? '') !== 'git') return false;
1564
+ let index = 1;
1565
+ while (index < words.length && (words[index] ?? '').startsWith('-'))
1566
+ index += GIT_GLOBAL_VALUE_OPTIONS.has(words[index] ?? '') ? 2 : 1;
1567
+ if (words[index] !== 'push') return false;
1568
+ if (command.dynamicArgs) return true;
1569
+ const positional = pushPositionals(words.slice(index + 1));
1570
+ if (positional === null) return true;
1571
+ const refspecs = positional.slice(1);
1572
+ return (
1573
+ refspecs.length === 0 ||
1574
+ refspecs.some((refspec, at) => unclearRefspec(refspec, refspecs[at - 1]))
1575
+ );
1576
+ }
1577
+
1578
+ /** The positional words of `git push`, or null when `--repo` hides the remote. @param {string[]} args */
1579
+ function pushPositionals(args) {
1580
+ /** @type {string[]} */
1581
+ const positional = [];
1582
+ for (let index = 0; index < args.length; index += 1) {
1583
+ const word = args[index] ?? '';
1584
+ if (word === '--') return [...positional, ...args.slice(index + 1)];
1585
+ if (word === '--repo' || word.startsWith('--repo=')) return null;
1586
+ if (PUSH_VALUE_OPTIONS.has(word) || /^-[A-Za-z]*o$/u.test(word)) index += 1;
1587
+ else if (!word.startsWith('-')) positional.push(word);
1588
+ }
1589
+ return positional;
1590
+ }
1591
+
1592
+ /** @param {string} refspec @param {string | undefined} previous */
1593
+ function unclearRefspec(refspec, previous) {
1594
+ if (refspec === TAG_REFSPEC || previous === TAG_REFSPEC) return false;
1595
+ if (DYNAMIC_REFSPEC.test(refspec)) return true;
1596
+ const unforced = refspec.startsWith('+') ? refspec.slice(1) : refspec;
1597
+ const colon = unforced.lastIndexOf(':');
1598
+ const destination = (colon === -1 ? unforced : unforced.slice(colon + 1)).replace(
1599
+ /^refs\/heads\//u,
1600
+ '',
1601
+ );
1602
+ return UNCLEAR_DESTINATIONS.has(destination);
1603
+ }
1604
+
1605
+ /** @param {Reading} reading @param {Scope} scope */
1606
+ function destroys(reading, scope) {
1607
+ if (guardTexts(reading).some((text) => destructiveGuard(bash(text), scope.guard) !== null))
1608
+ return true;
1609
+ return reading.commands.some(
1610
+ (command) =>
1611
+ removesRootLike(command, reading, scope) ||
1612
+ findDeletesRootLike(command, reading, scope) ||
1613
+ damagesHost(command, reading, scope),
1614
+ );
1615
+ }
1616
+
1617
+ /**
1618
+ * Formatting or wiping a device, `dd of=` a device, and `chmod`/`chown`/`chgrp -R` on a
1619
+ * root-like target (the first operand is the mode or the owner).
1620
+ * @param {EffectiveCommand} command @param {Reading} reading @param {Scope} scope
1621
+ */
1622
+ function damagesHost(command, reading, scope) {
1623
+ const program = programKey(command.words[0] ?? '');
1624
+ const args = command.words.slice(1);
1625
+ if (DEVICE_WIPERS.has(program) || program.startsWith(MKFS_PREFIX)) return true;
1626
+ if (program === DD_PROGRAM)
1627
+ return args.some((arg) => {
1628
+ const output = arg.startsWith(DD_OUTPUT) ? arg.slice(DD_OUTPUT.length) : '';
1629
+ return output.startsWith(DEVICE_DIRECTORY) && !HARMLESS_DEVICES.has(output);
1630
+ });
1631
+ if (!OWNERSHIP_PROGRAMS.has(program)) return false;
1632
+ if (!args.some((arg) => arg === '--recursive' || OWNERSHIP_RECURSIVE.test(arg))) return false;
1633
+ if (command.dynamicArgs) return true;
1634
+ const operands = args.filter((arg) => !arg.startsWith('-')).slice(1);
1635
+ return operands.some((target) => rootLike(target, reading, scope));
1636
+ }
1637
+
1638
+ /**
1639
+ * `rm -r` (with or without `-f`) on the file system root, a top-level directory, the
1640
+ * home, the state root, a room root, a host directory or an ancestor of one; on a
1641
+ * target a variable, `xargs` or `find` supplies; or with `--no-preserve-root`.
1642
+ * @param {EffectiveCommand} command @param {Reading} reading @param {Scope} scope
1643
+ */
1644
+ function removesRootLike(command, reading, scope) {
1645
+ if (programKey(command.words[0] ?? '') !== REMOVAL_PROGRAM) return false;
1646
+ const args = command.words.slice(1);
1647
+ const separator = args.indexOf('--');
1648
+ const options =
1649
+ separator === -1 ? args.filter((arg) => arg.startsWith('-')) : args.slice(0, separator);
1650
+ if (options.includes(NO_PRESERVE_ROOT)) return true;
1651
+ const recursive = options.some(
1652
+ (option) => option === '--recursive' || /^-[A-Za-z]*[rR]/u.test(option),
1653
+ );
1654
+ if (!recursive) return false;
1655
+ if (command.dynamicArgs) return true;
1656
+ const targets =
1657
+ separator === -1
1658
+ ? args.filter((arg) => !arg.startsWith('-'))
1659
+ : [
1660
+ ...args.slice(0, separator).filter((arg) => !arg.startsWith('-')),
1661
+ ...args.slice(separator + 1),
1662
+ ];
1663
+ return targets.some((target) => rootLike(target, reading, scope));
1664
+ }
1665
+
1666
+ /** `find <root-like> -delete` without a name test. @param {EffectiveCommand} command @param {Reading} reading @param {Scope} scope */
1667
+ function findDeletesRootLike(command, reading, scope) {
1668
+ const { words } = command;
1669
+ if (programKey(words[0] ?? '') !== FIND_PROGRAM || !words.includes(FIND_DELETE)) return false;
1670
+ if (words.some((word) => FIND_NAME_TESTS.has(word))) return false;
1671
+ const firstTest = words.findIndex((word, index) => index > 0 && /^[-(!]/u.test(word));
1672
+ const starts = words.slice(1, firstTest === -1 ? words.length : firstTest);
1673
+ return (starts.length === 0 ? ['.'] : starts).some((start) => rootLike(start, reading, scope));
1674
+ }
1675
+
1676
+ /** @param {string} target @param {Reading} reading @param {Scope} scope */
1677
+ function rootLike(target, reading, scope) {
1678
+ if (/[$`]/u.test(target) || target.includes(FIND_PLACEHOLDER)) return true;
1679
+ const path = globParent(expandHome(target, scope.home));
1680
+ if (!isAbsolute(path) && reading.dirs.length === 0)
1681
+ return /^(?:\.|\.\.)(?:\/\.\.)*\/?$/u.test(path);
1682
+ return resolveAgainst(path, reading.dirs, scope.home).some((candidate) => {
1683
+ const lower = candidate.toLowerCase();
1684
+ return (
1685
+ candidate === sep ||
1686
+ candidate.split(sep).filter(Boolean).length <= ROOT_LIKE_DEPTH ||
1687
+ scope.criticalDirs.some((dir) => within(dir.toLowerCase(), lower))
1688
+ );
1689
+ });
1690
+ }
1691
+
1692
+ /** The directory a glob lists (`./*` is `.`, `/home/*` is `/home`). @param {string} path */
1693
+ function globParent(path) {
1694
+ const segments = path.split('/');
1695
+ const first = segments.findIndex((segment) => GLOB_CHARACTERS.test(segment));
1696
+ if (first === -1) return path;
1697
+ const parent = segments.slice(0, first).join('/');
1698
+ return parent.length === 0 ? (path.startsWith('/') ? '/' : '.') : parent;
1699
+ }
1700
+
1701
+ /** `~`, `$HOME` and `${HOME}` at the start of a word. @param {string} word @param {string} home */
1702
+ function expandHome(word, home) {
1703
+ return word.replace(/^~(?=\/|$)/u, home).replace(/^\$\{?HOME\}?(?=\/|$)/u, home);
1704
+ }
1705
+
1706
+ /** @param {string} path @param {string[]} dirs @param {string} home @returns {string[]} */
1707
+ function resolveAgainst(path, dirs, home) {
1708
+ const expanded = expandHome(path, home);
1709
+ return isAbsolute(expanded) ? [resolve(expanded)] : dirs.map((dir) => resolve(dir, expanded));
1710
+ }
1711
+
1712
+ /** FR13 `outward`: the named list, mutating `gh api`, a remote `rsync`, a remote database. @param {EffectiveCommand} command */
1713
+ function outward(command) {
1714
+ const program = programKey(command.words[0] ?? '');
1715
+ const rest = command.words.slice(1).map((word) => word.toLowerCase());
1716
+ if (OUTWARD_COMMANDS.some(([name, ...run]) => name === program && containsRun(rest, run)))
1717
+ return true;
1718
+ if (program === 'gh') return ghApiWrites(command.words.slice(1));
1719
+ if (program === 'rsync')
1720
+ return rest.some((word) => !word.startsWith('-') && RSYNC_REMOTE.test(word));
1721
+ return REMOTE_DATABASE_CLIENTS.has(program) && remoteDatabase(command.words.slice(1));
1722
+ }
1723
+
1724
+ /** @param {string[]} words @param {string[]} run */
1725
+ function containsRun(words, run) {
1726
+ if (run.length === 0) return true;
1727
+ for (let index = 0; index + run.length <= words.length; index += 1)
1728
+ if (run.every((word, at) => words[index + at] === word)) return true;
1729
+ return false;
1730
+ }
1731
+
1732
+ /**
1733
+ * `gh api` that writes: a method other than GET or HEAD, fields without a method (gh
1734
+ * then POSTs), an input file, or a GraphQL mutation or query read from a file.
1735
+ * @param {string[]} args
1736
+ */
1737
+ function ghApiWrites(args) {
1738
+ const start = args.indexOf(GH_API);
1739
+ if (start === -1) return false;
1740
+ const rest = args.slice(start + 1);
1741
+ /** @type {string | null} */
1742
+ let method = null;
1743
+ let fields = false;
1744
+ for (let index = 0; index < rest.length; index += 1) {
1745
+ const word = rest[index] ?? '';
1746
+ if (GH_METHOD_OPTIONS.has(word)) {
1747
+ method = (rest[index + 1] ?? '').toUpperCase();
1748
+ index += 1;
1749
+ } else if (word.startsWith('--method=')) method = word.slice('--method='.length).toUpperCase();
1750
+ else if (/^-X./u.test(word)) method = word.slice(2).toUpperCase();
1751
+ else if (GH_FIELD_OPTIONS.has(word) || /^(?:-[fF].|--(?:raw-)?field=|--input=)/u.test(word))
1752
+ fields = true;
1753
+ }
1754
+ if (rest.includes(GH_GRAPHQL))
1755
+ return rest.some(
1756
+ (word) => /mutation/iu.test(word) || word.includes('=@') || word.startsWith('--input'),
1757
+ );
1758
+ return method === null ? fields : !READ_METHODS.has(method);
1759
+ }
1760
+
1761
+ /** A database client pointed at a host that is not local, or at one a variable names. @param {string[]} args */
1762
+ function remoteDatabase(args) {
1763
+ for (let index = 0; index < args.length; index += 1) {
1764
+ const word = args[index] ?? '';
1765
+ if (word.includes('$')) return true;
1766
+ if (URI.test(word) && !localUri(word)) return true;
1767
+ const conninfo = CONNINFO_HOST.exec(word);
1768
+ if (conninfo !== null && !localHost(conninfo[1] ?? '')) return true;
1769
+ if (DATABASE_HOST_OPTIONS.has(word) && !localTarget(args[index + 1] ?? '')) return true;
1770
+ const attached = /^(?:-h|--host=|--server=|--url=|--uri=)(.+)$/u.exec(word);
1771
+ if (attached !== null && !localTarget(attached[1] ?? '')) return true;
1772
+ }
1773
+ return false;
1774
+ }
1775
+
1776
+ /** @param {string} value */
1777
+ function localTarget(value) {
1778
+ return URI.test(value) ? localUri(value) : localHost(value);
1779
+ }
1780
+
1781
+ /** @param {string} value */
1782
+ function localUri(value) {
1783
+ try {
1784
+ return localHost(new URL(value).hostname);
1785
+ } catch {
1786
+ return false;
1787
+ }
1788
+ }
1789
+
1790
+ /** @param {string} host */
1791
+ function localHost(host) {
1792
+ return LOCAL_HOSTS.has(host.toLowerCase()) || host.startsWith('/') || host.startsWith('127.');
1793
+ }
1794
+
1795
+ /** @param {Reading} reading @param {Scope} scope */
1796
+ function needsPrivilege(reading, scope) {
1797
+ if (reading.privileged) return true;
1798
+ const cwd = (scope.cwd ?? '').toLowerCase();
1799
+ if (cwd !== '' && scope.protectedDirs.some((dir) => within(cwd, dir.toLowerCase()))) return true;
1800
+ if (
1801
+ reading.texts.some((text) => PRIVILEGE_VARIABLES.test(text) || mentionsProtected(text, scope))
1802
+ )
1803
+ return true;
1804
+ if (
1805
+ [...reading.words.flat(), ...reading.targets].some((word) =>
1806
+ namesProtected(word, reading, scope),
1807
+ )
1808
+ )
1809
+ return true;
1810
+ return reading.commands.some((command) => delegatesApprovals(command.words));
1811
+ }
1812
+
1813
+ /** @param {string} text @param {Scope} scope */
1814
+ function mentionsProtected(text, scope) {
1815
+ const lower = text.toLowerCase();
1816
+ return scope.mentions.some((form) => lower.includes(form));
1817
+ }
1818
+
1819
+ /**
1820
+ * A word that names the state root, the bus or a host directory: spelled out, through
1821
+ * `~` or `$HOME`, relative to a working directory, by its dot name (`.codex`) inside a
1822
+ * repository root, or as a glob that can match that name.
1823
+ * @param {string} word @param {Reading} reading @param {Scope} scope
1824
+ */
1825
+ function namesProtected(word, reading, scope) {
1826
+ if (mentionsProtected(word, scope)) return true;
1827
+ if (/\s/u.test(word)) return false;
1828
+ if (globMatches(word, scope.protectedNames)) return true;
1829
+ const equals = word.lastIndexOf('=');
1830
+ const candidates = equals === -1 ? [word] : [word, word.slice(equals + 1)];
1831
+ return candidates.some((candidate) => {
1832
+ const expanded = expandHome(candidate, scope.home);
1833
+ const paths =
1834
+ isAbsolute(expanded) || reading.dirs.length > 0
1835
+ ? resolveAgainst(expanded, reading.dirs, scope.home)
1836
+ : [];
1837
+ if (paths.length === 0) return hasProtectedName(expanded, scope);
1838
+ return paths.some((path) => {
1839
+ const lower = path.toLowerCase();
1840
+ if (scope.protectedDirs.some((dir) => within(lower, dir.toLowerCase()))) return true;
1841
+ const root = deepestRoot(path, scope.roots);
1842
+ return hasProtectedName(root === null ? path : relative(root, path), scope);
1843
+ });
1844
+ });
1845
+ }
1846
+
1847
+ /** @param {string} path @param {Scope} scope */
1848
+ function hasProtectedName(path, scope) {
1849
+ return path
1850
+ .toLowerCase()
1851
+ .split(/[/\\]/u)
1852
+ .some((segment) => scope.protectedNames.includes(segment));
1853
+ }
1854
+
1855
+ /** `aisac workers delegate`: only the user grants a delegation, from a terminal (FR10). @param {string[]} words */
1856
+ function delegatesApprovals(words) {
1857
+ const first = words[0] ?? '';
1858
+ const program = programKey(first);
1859
+ const entry =
1860
+ AISAC_PROGRAMS.has(program) ||
1861
+ AISAC_PACKAGE.test(first) ||
1862
+ (program === 'node' && AISAC_CLI_ENTRY.test(words[1] ?? ''));
1863
+ const workers = words.indexOf('workers');
1864
+ return entry && workers !== -1 && words.slice(workers + 1).includes('delegate');
1865
+ }
1866
+
1867
+ // ---------------------------------------------------------------------------
1868
+ // Writes outside the roots (FR13 `files`, the command row)
1869
+
1870
+ /**
1871
+ * A path the line names, outright, as one it writes or removes (an output redirection,
1872
+ * or an operand of a known writing program) lies outside every root. Paths resolve
1873
+ * textually against every working directory the line may use (`cwd`, then `cd`).
1874
+ * @param {Reading} reading @param {Scope} scope
1875
+ */
1876
+ function writesOutsideRoots(reading, scope) {
1877
+ const bases = scope.cwd === null ? [scope.guard.projectDir, ...reading.dirs] : reading.dirs;
1878
+ const written = [
1879
+ ...reading.texts.flatMap(outputTargets),
1880
+ ...reading.commands.flatMap(writtenPaths),
1881
+ ];
1882
+ return written.some((path) => outsideRoots(path, bases, scope));
1883
+ }
1884
+
1885
+ /**
1886
+ * A dynamic path (`$OUT`, a `find`/`xargs` placeholder) is not reserved by this rule; a
1887
+ * glob is taken at the directory it lists; `~name` is another user's home.
1888
+ * @param {string} word @param {string[]} bases @param {Scope} scope
1889
+ */
1890
+ function outsideRoots(word, bases, scope) {
1891
+ if (word.length === 0 || word === STDIO_OPERAND || /[$`]/u.test(word)) return false;
1892
+ if (word.includes(FIND_PLACEHOLDER)) return false;
1893
+ const expanded = expandHome(word, scope.home);
1894
+ if (expanded.startsWith('~')) return true;
1895
+ return resolveAgainst(globParent(expanded), bases, scope.home).some(
1896
+ (path) =>
1897
+ !HARMLESS_DEVICES.has(path) &&
1898
+ !TEMPORARY_DIRECTORIES.some((dir) => within(path, dir)) &&
1899
+ !scope.roots.some((root) => within(path, root)),
1900
+ );
1901
+ }
1902
+
1903
+ /**
1904
+ * The files the output redirections of a text name (`>`, `>>`, `>|`, `&>`, `&>>`, `<>`,
1905
+ * `>&file`), read from the text in one pass: the splitter keeps `x>file` in one word and
1906
+ * does not say which of its targets are written.
1907
+ * @param {string} text @returns {string[]}
1908
+ */
1909
+ function outputTargets(text) {
1910
+ /** @type {string[]} */
1911
+ const targets = [];
1912
+ let index = 0;
1913
+ while (index < text.length) {
1914
+ const char = text[index];
1915
+ if (char === '\\') index += 2;
1916
+ else if (char === "'" || char === '"') index = quoteEnd(text, index);
1917
+ else if (char === '#' && (index === 0 || WORD_BREAK.test(text[index - 1] ?? ''))) {
1918
+ const newline = text.indexOf('\n', index);
1919
+ index = newline === -1 ? text.length : newline;
1920
+ } else if (char === '>' || ((char === '&' || char === '<') && text[index + 1] === '>')) {
1921
+ const redirection = outputRedirection(text, index);
1922
+ if (redirection.target.length > 0) targets.push(redirection.target);
1923
+ index = redirection.end;
1924
+ } else index += 1;
1925
+ }
1926
+ return targets;
1927
+ }
1928
+
1929
+ /**
1930
+ * The target of the output redirection at `index`, empty for a descriptor duplication
1931
+ * (`2>&1`, `>&-`).
1932
+ * @param {string} text @param {number} index @returns {{ target: string, end: number }}
1933
+ */
1934
+ function outputRedirection(text, index) {
1935
+ const char = text[index];
1936
+ let cursor = char === '>' ? index + 1 : index + 2;
1937
+ if (text[cursor] === '>' || (char === '>' && text[cursor] === '|')) cursor += 1;
1938
+ if (char === '>' && text[cursor] === '&') {
1939
+ if (DESCRIPTOR.test(text[cursor + 1] ?? '')) return { target: '', end: cursor + 2 };
1940
+ cursor += 1;
1941
+ }
1942
+ return readTargetWord(text, cursor);
1943
+ }
1944
+
1945
+ /** @param {string} text @param {number} start @returns {{ target: string, end: number }} */
1946
+ function readTargetWord(text, start) {
1947
+ let index = start;
1948
+ while (text[index] === ' ' || text[index] === '\t') index += 1;
1949
+ let target = '';
1950
+ while (index < text.length) {
1951
+ const char = text[index] ?? '';
1952
+ if (TARGET_END.test(char)) break;
1953
+ if (char === '\\') {
1954
+ target += text[index + 1] ?? '';
1955
+ index += 2;
1956
+ } else if (char === "'" || char === '"') {
1957
+ const end = quoteEnd(text, index);
1958
+ const inner = text.slice(index + 1, end - 1);
1959
+ target += char === '"' ? inner.replace(DOUBLE_QUOTE_ESCAPE, '$1') : inner;
1960
+ index = end;
1961
+ } else {
1962
+ target += char;
1963
+ index += 1;
1964
+ }
1965
+ }
1966
+ return { target, end: index };
1967
+ }
1968
+
1969
+ /** The index after the quoted string that starts at `index`. @param {string} text @param {number} index */
1970
+ function quoteEnd(text, index) {
1971
+ if (text[index] === "'") {
1972
+ const close = text.indexOf("'", index + 1);
1973
+ return close === -1 ? text.length : close + 1;
1974
+ }
1975
+ for (let cursor = index + 1; cursor < text.length; cursor += 1) {
1976
+ if (text[cursor] === '\\') cursor += 1;
1977
+ else if (text[cursor] === '"') return cursor + 1;
1978
+ }
1979
+ return text.length;
1980
+ }
1981
+
1982
+ /** The paths a command names as written or removed. @param {EffectiveCommand} command @returns {string[]} */
1983
+ function writtenPaths(command) {
1984
+ const program = programKey(command.words[0] ?? '');
1985
+ const args = command.words.slice(1);
1986
+ const spec = WRITERS.get(program);
1987
+ if (spec !== undefined) return writerPaths(args, spec);
1988
+ if (program === DD_PROGRAM)
1989
+ return args
1990
+ .filter((arg) => arg.startsWith(DD_OUTPUT))
1991
+ .map((arg) => arg.slice(DD_OUTPUT.length));
1992
+ if (program === UNZIP_PROGRAM) return parseOptions(args, NO_OPTIONS, UNZIP_TARGETS).targets;
1993
+ if (program === TAR_PROGRAM) return tarPaths(args);
1994
+ if (program === SED_PROGRAM) return sedPaths(args);
1995
+ if (program === PERL_PROGRAM) return perlPaths(args);
1996
+ if (program === GIT_PROGRAM) return gitPaths(args);
1997
+ return [];
1998
+ }
1999
+
2000
+ /** @param {string[]} args @param {WriterSpec} spec */
2001
+ function writerPaths(args, spec) {
2002
+ const parsed = parseOptions(args, spec.values ?? NO_OPTIONS, spec.targets ?? NO_OPTIONS);
2003
+ const allWhen = spec.allWhen ?? NO_OPTIONS;
2004
+ const every =
2005
+ spec.operands === 'all' ||
2006
+ parsed.flags.some((flag) =>
2007
+ [...allWhen].some((option) =>
2008
+ option.startsWith('--')
2009
+ ? flag === option
2010
+ : !flag.startsWith('--') && flag.includes(option.slice(1)),
2011
+ ),
2012
+ );
2013
+ if (every) return [...parsed.operands, ...parsed.targets];
2014
+ if (parsed.targets.length > 0) return parsed.targets;
2015
+ return parsed.operands.length >= 2 ? [parsed.operands.at(-1) ?? ''] : [];
2016
+ }
2017
+
2018
+ /**
2019
+ * Operands and option values as getopt reads them: `--` ends the options; in a cluster
2020
+ * (`-at DIR`) a letter that takes a value takes the rest of the word or the next one;
2021
+ * `--name=value` carries its value.
2022
+ * @param {string[]} args @param {ReadonlySet<string>} values @param {ReadonlySet<string>} targets
2023
+ * @returns {{ operands: string[], flags: string[], targets: string[], seen: Set<string> }}
2024
+ */
2025
+ function parseOptions(args, values, targets) {
2026
+ /** @type {{ operands: string[], flags: string[], targets: string[], seen: Set<string> }} */
2027
+ const parsed = { operands: [], flags: [], targets: [], seen: new Set() };
2028
+ for (let index = 0; index < args.length; index += 1) {
2029
+ const arg = args[index] ?? '';
2030
+ if (arg === OPTION_END) {
2031
+ parsed.operands.push(...args.slice(index + 1));
2032
+ break;
2033
+ }
2034
+ if (!arg.startsWith('-') || arg === STDIO_OPERAND) {
2035
+ parsed.operands.push(arg);
2036
+ continue;
2037
+ }
2038
+ parsed.flags.push(arg);
2039
+ const taken = optionValue(arg, args[index + 1], values, targets);
2040
+ if (taken === null) continue;
2041
+ parsed.seen.add(taken.option);
2042
+ if (targets.has(taken.option)) parsed.targets.push(taken.value);
2043
+ if (taken.next) index += 1;
2044
+ }
2045
+ return parsed;
2046
+ }
2047
+
2048
+ /**
2049
+ * The option of a word that takes a value, its value, and whether that is the next word.
2050
+ * @param {string} arg @param {string | undefined} next
2051
+ * @param {ReadonlySet<string>} values @param {ReadonlySet<string>} targets
2052
+ * @returns {{ option: string, value: string, next: boolean } | null}
2053
+ */
2054
+ function optionValue(arg, next, values, targets) {
2055
+ const takes = (/** @type {string} */ option) => values.has(option) || targets.has(option);
2056
+ if (arg.startsWith('--')) {
2057
+ const equals = arg.indexOf('=');
2058
+ const option = equals === -1 ? arg : arg.slice(0, equals);
2059
+ if (!takes(option)) return null;
2060
+ return equals === -1
2061
+ ? { option, value: next ?? '', next: true }
2062
+ : { option, value: arg.slice(equals + 1), next: false };
2063
+ }
2064
+ for (let at = 1; at < arg.length; at += 1) {
2065
+ const option = `-${arg[at]}`;
2066
+ if (!takes(option)) continue;
2067
+ const rest = arg.slice(at + 1);
2068
+ return rest.length > 0
2069
+ ? { option, value: rest, next: false }
2070
+ : { option, value: next ?? '', next: true };
2071
+ }
2072
+ return null;
2073
+ }
2074
+
2075
+ /** `tar -C DIR` is where tar extracts; creating or appending, it is where tar reads. @param {string[]} args */
2076
+ function tarPaths(args) {
2077
+ const letters = (TAR_OPERATION.exec(args[0] ?? '')?.[1] ?? '').split(TAR_VALUE_LETTER)[0] ?? '';
2078
+ if (TAR_READING_LETTERS.test(letters) || args.some((arg) => TAR_READING_MODES.has(arg)))
2079
+ return [];
2080
+ return parseOptions(args, TAR_VALUE_OPTIONS, TAR_TARGETS).targets;
2081
+ }
2082
+
2083
+ /** `sed -i`: the file operands (after the script, unless `-e`/`-f` gave it). @param {string[]} args */
2084
+ function sedPaths(args) {
2085
+ const parsed = parseOptions(args, SED_VALUE_OPTIONS, NO_OPTIONS);
2086
+ const inPlace = parsed.flags.some((flag) =>
2087
+ flag.startsWith('--')
2088
+ ? flag === SED_IN_PLACE || flag.startsWith(`${SED_IN_PLACE}=`)
2089
+ : ((SED_CLUSTER.exec(flag)?.[1] ?? '').split(SED_VALUE_LETTER)[0] ?? '').includes('i'),
2090
+ );
2091
+ if (!inPlace) return [];
2092
+ const scripted = [...SED_SCRIPT_OPTIONS].some((option) => parsed.seen.has(option));
2093
+ return scripted ? parsed.operands : parsed.operands.slice(1);
2094
+ }
2095
+
2096
+ /** `perl -i`: the file operands (after the script, unless `-e`/`-E` gave the code). @param {string[]} args */
2097
+ function perlPaths(args) {
2098
+ let inPlace = false;
2099
+ let code = false;
2100
+ let index = 0;
2101
+ for (; index < args.length; index += 1) {
2102
+ const arg = args[index] ?? '';
2103
+ if (arg === OPTION_END) {
2104
+ index += 1;
2105
+ break;
2106
+ }
2107
+ if (!arg.startsWith('-') || arg === STDIO_OPERAND) break;
2108
+ const switches = perlSwitches(arg);
2109
+ inPlace ||= switches.inPlace;
2110
+ code ||= switches.code;
2111
+ if (switches.takesNext) index += 1;
2112
+ }
2113
+ if (!inPlace) return [];
2114
+ const operands = args.slice(index);
2115
+ return code ? operands : operands.slice(1);
2116
+ }
2117
+
2118
+ /** @param {string} arg @returns {{ inPlace: boolean, code: boolean, takesNext: boolean }} */
2119
+ function perlSwitches(arg) {
2120
+ for (let at = 1; at < arg.length; at += 1) {
2121
+ const letter = arg[at] ?? '';
2122
+ const last = at === arg.length - 1;
2123
+ if (letter === PERL_IN_PLACE) return { inPlace: true, code: false, takesNext: false };
2124
+ if (PERL_CODE_SWITCHES.has(letter)) return { inPlace: false, code: true, takesNext: last };
2125
+ if (PERL_ARGUMENT_SWITCHES.has(letter))
2126
+ return { inPlace: false, code: false, takesNext: last && letter === PERL_SEPARATE_VALUE };
2127
+ if (PERL_DIGIT_SWITCHES.has(letter)) while (/\d/u.test(arg[at + 1] ?? '')) at += 1;
2128
+ }
2129
+ return { inPlace: false, code: false, takesNext: false };
2130
+ }
2131
+
2132
+ /** `git clone`/`git init`/`git worktree add` destinations, under `git -C DIR`. @param {string[]} args */
2133
+ function gitPaths(args) {
2134
+ let base = '';
2135
+ let index = 0;
2136
+ while (index < args.length && (args[index] ?? '').startsWith('-')) {
2137
+ const option = args[index] ?? '';
2138
+ if (option === GIT_DIRECTORY_OPTION) base = underBase(base, args[index + 1] ?? '');
2139
+ index += GIT_GLOBAL_VALUE_OPTIONS.has(option) ? 2 : 1;
2140
+ }
2141
+ const rest = args.slice(index + 1);
2142
+ const at = (/** @type {string} */ path) => underBase(base, path);
2143
+ const here = base === '' ? [] : [base];
2144
+ const subcommand = args[index];
2145
+ if (subcommand === 'clone') {
2146
+ const parsed = parseOptions(rest, GIT_CLONE_VALUE_OPTIONS, GIT_SEPARATE_DIR);
2147
+ const { operands } = parsed;
2148
+ const into = operands.length >= 2 ? [operands[1] ?? '', operands.at(-1) ?? ''].map(at) : here;
2149
+ return [...into, ...parsed.targets.map(at)];
2150
+ }
2151
+ if (subcommand === 'init') {
2152
+ const parsed = parseOptions(rest, GIT_INIT_VALUE_OPTIONS, GIT_SEPARATE_DIR);
2153
+ const into = parsed.operands.length > 0 ? parsed.operands.map(at) : here;
2154
+ return [...into, ...parsed.targets.map(at)];
2155
+ }
2156
+ if (subcommand === 'worktree' && rest[0] === 'add')
2157
+ return parseOptions(rest.slice(1), GIT_WORKTREE_VALUE_OPTIONS, NO_OPTIONS).operands.map(at);
2158
+ return [];
2159
+ }
2160
+
2161
+ /** A path relative to `git -C`'s directory. @param {string} base @param {string} path */
2162
+ function underBase(base, path) {
2163
+ if (base === '' || path.startsWith('/') || path.startsWith('~') || /[$`]/u.test(path))
2164
+ return path;
2165
+ return join(base, path);
2166
+ }