@agent-corpus/policy-manager 0.5.0 → 0.7.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.
@@ -1,8 +1,10 @@
1
- import { basename, resolve } from "node:path";
2
- import { branchEvidence, canonical, inside, isProtectedPath, pathEvidence, protectedPath, sensitive, } from "./evidence.js";
1
+ import { lstatSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
3
+ import { branchEvidence, canonical, disposable, git, inside, isProtectedPath, OUTSIDE_REPOSITORY, pathEvidence, policyState, protectedPath, resolveWord, sensitive, tempRoots, tempWrite, } from "./evidence.js";
3
4
  import { commandDecision } from "./flow.js";
4
5
  import { mergedEvidence, remoteTipMatches } from "./merged.js";
5
6
  import { evaluateArgv, result } from "./policy.js";
7
+ import { deletesProtected, deletionScriptCwd, gitRmRecoverable, resetRecoverable, restoreRecoverable, rmRecoverable, soleEffect, worktreeDeletion, } from "./recoverable.js";
6
8
  import { SUBSTITUTION } from "./shell.js";
7
9
  /**
8
10
  * Permissive profile: approve everything except effects that are destructive, irreversible,
@@ -155,9 +157,420 @@ const FORCE_PUSH = ["--force", "--force-with-lease", "--force-if-includes", "--m
155
157
  export function human(request, category, reason) {
156
158
  return result(request, category, reason);
157
159
  }
160
+ const GH_TEXT = new Set(["--body", "-b", "--title", "-t", "--jq", "-q", "--template", "--notes"]);
161
+ /** Short options that take a value, per program; the value is never the pattern or script. */
162
+ const SHORT_VALUES = {
163
+ sed: "f",
164
+ grep: "ABDdfm",
165
+ egrep: "ABDdfm",
166
+ fgrep: "ABDdfm",
167
+ rg: "ABCEfgjMmrTt",
168
+ };
169
+ /**
170
+ * Options that take a separate value in GNU but none in BSD (`sed -l`, BSD `grep -C[num]` and
171
+ * `--context[=num]`). Which word is the value is unknowable, so every operand is checked.
172
+ */
173
+ const DUAL_SHORT = { sed: "l", grep: "C", egrep: "C", fgrep: "C" };
174
+ const DUAL_LONG = new Set(["grep", "egrep", "fgrep"]); // `--context`
175
+ const GREP_LONG_VALUES = [
176
+ "--after-context",
177
+ "--before-context",
178
+ "--binary-files",
179
+ "--context",
180
+ "--devices",
181
+ "--directories",
182
+ "--exclude",
183
+ "--exclude-dir",
184
+ "--exclude-from",
185
+ "--file",
186
+ "--include",
187
+ "--label",
188
+ "--max-count",
189
+ ];
190
+ const GREP_LONG_FLAGS = [
191
+ "--count",
192
+ "--extended-regexp",
193
+ "--files-with-matches",
194
+ "--files-without-match",
195
+ "--fixed-strings",
196
+ "--ignore-case",
197
+ "--invert-match",
198
+ "--line-number",
199
+ "--line-regexp",
200
+ "--no-filename",
201
+ "--no-messages",
202
+ "--null",
203
+ "--only-matching",
204
+ "--perl-regexp",
205
+ "--quiet",
206
+ "--recursive",
207
+ "--dereference-recursive",
208
+ "--silent",
209
+ "--with-filename",
210
+ "--word-regexp",
211
+ ];
212
+ /** Long options that take a separate value; the value is never the pattern or script. */
213
+ const LONG_VALUES = {
214
+ sed: new Set(["--file", "--line-length"]),
215
+ grep: new Set(GREP_LONG_VALUES),
216
+ egrep: new Set(GREP_LONG_VALUES),
217
+ fgrep: new Set(GREP_LONG_VALUES),
218
+ rg: new Set([
219
+ "--after-context",
220
+ "--before-context",
221
+ "--context",
222
+ "--encoding",
223
+ "--file",
224
+ "--glob",
225
+ "--iglob",
226
+ "--ignore-file",
227
+ "--max-count",
228
+ "--max-depth",
229
+ "--max-filesize",
230
+ "--pre",
231
+ "--pre-glob",
232
+ "--replace",
233
+ "--sort",
234
+ "--sortr",
235
+ "--threads",
236
+ "--type",
237
+ "--type-add",
238
+ "--type-not",
239
+ ]),
240
+ };
241
+ /** Long options known to take no value. */
242
+ const LONG_FLAGS = {
243
+ sed: new Set([
244
+ "--debug",
245
+ "--null-data",
246
+ "--posix",
247
+ "--quiet",
248
+ "--regexp-extended",
249
+ "--sandbox",
250
+ "--separate",
251
+ "--silent",
252
+ "--unbuffered",
253
+ "--in-place",
254
+ ]),
255
+ grep: new Set(GREP_LONG_FLAGS),
256
+ egrep: new Set(GREP_LONG_FLAGS),
257
+ fgrep: new Set(GREP_LONG_FLAGS),
258
+ rg: new Set([
259
+ "--count",
260
+ "--files-with-matches",
261
+ "--fixed-strings",
262
+ "--follow",
263
+ "--hidden",
264
+ "--ignore-case",
265
+ "--invert-match",
266
+ "--json",
267
+ "--line-number",
268
+ "--multiline",
269
+ "--no-filename",
270
+ "--no-heading",
271
+ "--no-ignore",
272
+ "--only-matching",
273
+ "--pcre2",
274
+ "--smart-case",
275
+ "--vimgrep",
276
+ "--with-filename",
277
+ "--word-regexp",
278
+ ]),
279
+ };
280
+ /**
281
+ * File names a sed script reads, writes or runs (`r`, `R`, `w`, `W`, the `s///w` flag, GNU `e`).
282
+ * Over-matching only sends more to a human.
283
+ */
284
+ function sedScriptPaths(script) {
285
+ const paths = [];
286
+ for (const match of script.matchAll(/(?:^|[^A-Za-z\\])[eErRwW]\s*([^\n]*)/g))
287
+ paths.push(...(match[1] ?? "").split(/[\s;]+/).filter(Boolean));
288
+ return paths;
289
+ }
290
+ /**
291
+ * Indices of `args` that are text rather than paths, paths named inside that text, and the file
292
+ * operands (for sed, the files `-i` rewrites).
293
+ */
294
+ function textOperands(program, args) {
295
+ const text = new Set();
296
+ const files = [];
297
+ // Values of file-name pattern options (`--include`, rg `-g`), found by this same parse.
298
+ const patterns = new Set();
299
+ if (program === "gh") {
300
+ for (const [index, word] of args.entries()) {
301
+ if (GH_TEXT.has(word))
302
+ text.add(index + 1);
303
+ else if (/^--(?:body|title|jq|template|notes)=/.test(word))
304
+ text.add(index);
305
+ }
306
+ return { text, paths: [], files, patterns };
307
+ }
308
+ if (program === "find")
309
+ return { text, paths: [], files, patterns: findPatterns(args) };
310
+ const values = SHORT_VALUES[program];
311
+ if (values === undefined)
312
+ return { text, paths: [], files, patterns };
313
+ // Fallback when an option cannot be understood: every operand is checked.
314
+ const everyWord = {
315
+ text: new Set(),
316
+ paths: [],
317
+ files: args.filter((arg) => arg !== "" && !arg.startsWith("-")),
318
+ patterns: new Set(),
319
+ };
320
+ // grep, rg and GNU sed accept options after operands, so collect everything before deciding
321
+ // which operand, if any, is the pattern or script.
322
+ const scripts = [];
323
+ const operands = [];
324
+ let explicit = false;
325
+ let ended = false;
326
+ for (let index = 0; index < args.length; index++) {
327
+ const word = args[index] ?? "";
328
+ if (!ended && word === "--") {
329
+ ended = true;
330
+ continue;
331
+ }
332
+ if (!ended && word.startsWith("--")) {
333
+ const eq = word.indexOf("=");
334
+ const name = longOption(program, eq < 0 ? word : word.slice(0, eq));
335
+ if (name === undefined)
336
+ return everyWord;
337
+ if (name === "--context" && eq < 0 && DUAL_LONG.has(program))
338
+ return everyWord;
339
+ if (name === "--expression" || name === "--regexp") {
340
+ explicit = true;
341
+ if (eq >= 0)
342
+ scripts.push([index, word.slice(eq + 1)]);
343
+ else {
344
+ index++;
345
+ scripts.push([index, args[index] ?? ""]);
346
+ }
347
+ }
348
+ else {
349
+ // A pattern or script file means there is no pattern operand: every operand is a file.
350
+ if (name === "--file")
351
+ explicit = true;
352
+ const pattern = NAME_PATTERN_OPTIONS[program]?.includes(name);
353
+ if (pattern && eq >= 0)
354
+ patterns.add(index);
355
+ // A value-taking long option consumes the next word, which stays a checked operand.
356
+ if (eq < 0 && LONG_VALUES[program]?.has(name)) {
357
+ index++;
358
+ if (pattern)
359
+ patterns.add(index);
360
+ }
361
+ }
362
+ continue;
363
+ }
364
+ if (!ended && /^-[A-Za-z]/.test(word)) {
365
+ for (let at = 1; at < word.length; at++) {
366
+ const flag = word[at] ?? "";
367
+ if (program === "sed" && flag === "i")
368
+ break; // the rest is a backup suffix
369
+ if (DUAL_SHORT[program]?.includes(flag))
370
+ return everyWord;
371
+ if (flag === "e") {
372
+ explicit = true;
373
+ if (at + 1 < word.length)
374
+ scripts.push([index, word.slice(at + 1)]);
375
+ else {
376
+ index++;
377
+ scripts.push([index, args[index] ?? ""]);
378
+ }
379
+ break;
380
+ }
381
+ if (values.includes(flag)) {
382
+ if (flag === "f")
383
+ explicit = true;
384
+ if (at + 1 === word.length)
385
+ index++;
386
+ if (program === "rg" && flag === "g")
387
+ patterns.add(index);
388
+ break;
389
+ }
390
+ }
391
+ continue;
392
+ }
393
+ if (!ended && word.startsWith("-"))
394
+ continue;
395
+ // BSD `sed -i ''` leaves an empty suffix operand, which is skipped.
396
+ if (word !== "")
397
+ operands.push(index);
398
+ }
399
+ // The first operand is the script or pattern only when no -e, -f, --regexp, --expression or
400
+ // --file named one, wherever that option appears.
401
+ const first = explicit ? undefined : operands.shift();
402
+ if (first !== undefined)
403
+ scripts.push([first, args[first] ?? ""]);
404
+ for (const [index] of scripts)
405
+ text.add(index);
406
+ files.push(...operands.map((index) => args[index] ?? ""));
407
+ const paths = program === "sed" ? scripts.flatMap(([, script]) => sedScriptPaths(script)) : [];
408
+ return { text, paths, files, patterns };
409
+ }
410
+ /** Pattern and script options per program, besides the value lists. */
411
+ const PATTERN_OPTIONS = {
412
+ sed: ["--expression", "--file"],
413
+ grep: ["--regexp", "--file"],
414
+ egrep: ["--regexp", "--file"],
415
+ fgrep: ["--regexp", "--file"],
416
+ rg: ["--regexp", "--file"],
417
+ };
418
+ /**
419
+ * A long option name resolved as GNU getopt does: an exact match, or the one known option it
420
+ * abbreviates. Unknown or ambiguous names are undefined.
421
+ */
422
+ function longOption(program, name) {
423
+ const known = new Set([
424
+ ...(PATTERN_OPTIONS[program] ?? []),
425
+ ...(LONG_VALUES[program] ?? []),
426
+ ...(LONG_FLAGS[program] ?? []),
427
+ ]);
428
+ if (known.has(name))
429
+ return name;
430
+ // rg takes no abbreviations: `rg --files` is not `--files-with-matches`.
431
+ if (program === "rg")
432
+ return undefined;
433
+ const matches = [...known].filter((option) => option.startsWith(name));
434
+ return matches.length === 1 ? matches[0] : undefined;
435
+ }
436
+ const FIND_ACTIONS = new Set([
437
+ "-exec",
438
+ "-execdir",
439
+ "-ok",
440
+ "-okdir",
441
+ "-fprint",
442
+ "-fprint0",
443
+ "-fprintf",
444
+ "-fls",
445
+ ]);
446
+ /** find primaries that take one argument. */
447
+ const FIND_VALUE_PRIMARIES = new Set([
448
+ "amin",
449
+ "anewer",
450
+ "atime",
451
+ "cmin",
452
+ "cnewer",
453
+ "ctime",
454
+ "group",
455
+ "iname",
456
+ "inum",
457
+ "ipath",
458
+ "iregex",
459
+ "iwholename",
460
+ "links",
461
+ "maxdepth",
462
+ "mindepth",
463
+ "mmin",
464
+ "mtime",
465
+ "name",
466
+ "newer",
467
+ "path",
468
+ "perm",
469
+ "regex",
470
+ "size",
471
+ "type",
472
+ "user",
473
+ "wholename",
474
+ ].map((name) => `-${name}`));
475
+ /** find primaries and operators that take no argument. */
476
+ const FIND_FLAG_PRIMARIES = new Set([
477
+ ...[
478
+ "a",
479
+ "and",
480
+ "delete",
481
+ "depth",
482
+ "empty",
483
+ "false",
484
+ "mount",
485
+ "nogroup",
486
+ "not",
487
+ "nouser",
488
+ "o",
489
+ "or",
490
+ "print",
491
+ "print0",
492
+ "prune",
493
+ "true",
494
+ "xdev",
495
+ ].map((name) => `-${name}`),
496
+ "!",
497
+ "(",
498
+ ")",
499
+ ]);
500
+ /**
501
+ * Whether every word of a find expression is a known primary, operator or primary argument. bfs
502
+ * (behind Claude Code's `find`) also takes start paths, `-f` and `--` inside the expression, so an
503
+ * unknown word could be one.
504
+ */
505
+ function knownFindExpression(words) {
506
+ for (let index = 0; index < words.length; index++) {
507
+ const word = words[index] ?? "";
508
+ if (FIND_VALUE_PRIMARIES.has(word))
509
+ index++;
510
+ else if (!FIND_FLAG_PRIMARIES.has(word))
511
+ return false;
512
+ }
513
+ return true;
514
+ }
515
+ /**
516
+ * `rm`, `rmdir`, `unlink` or `find ... -delete` whose every target is disposable: strictly inside
517
+ * a scratch root or the system temp directory (see `disposable`).
518
+ */
519
+ function scratchDeletion(program, args, cwd, profile, fill) {
520
+ const roots = [...profile.scratchRoots, ...tempRoots()];
521
+ let targets;
522
+ if (program === "rm" || program === "rmdir" || program === "unlink") {
523
+ const end = args.indexOf("--");
524
+ const options = end < 0 ? args : args.slice(0, end);
525
+ targets = [
526
+ ...options.filter((arg) => !arg.startsWith("-")),
527
+ ...(end < 0 ? [] : args.slice(end + 1)),
528
+ ];
529
+ // `rmdir -p` also removes empty ancestors, up to and past a root.
530
+ // GNU accepts abbreviations (`--parent`, `--p`).
531
+ if (program === "rmdir" && options.some((arg) => /^--p/.test(arg) || /^-[^-]*p/.test(arg)))
532
+ return false;
533
+ }
534
+ else if (program === "find") {
535
+ if (!args.includes("-delete") ||
536
+ args.some((arg) => FIND_ACTIONS.has(arg) || ["-follow", "-files0-from"].includes(arg)))
537
+ return false;
538
+ // Leading options come before the start paths: GNU -P -D -O, BSD -E -s -x -X -d. -H, -L follow
539
+ // symlinks and BSD -f names a start path, so those stay with a person.
540
+ let index = 0;
541
+ for (; index < args.length; index++) {
542
+ const arg = args[index] ?? "";
543
+ if (arg === "--") {
544
+ index++;
545
+ break;
546
+ }
547
+ // BSD find accepts clusters such as -xP.
548
+ if (/^-[PEsxXd]+$/.test(arg) || /^-O[0-9]*$/.test(arg))
549
+ continue;
550
+ if (arg === "-D") {
551
+ index++;
552
+ continue;
553
+ }
554
+ // Expression primaries are words (-name, -type); a single letter is an unknown option.
555
+ if (/^-[HLf]$/.test(arg) || /^-.$/.test(arg))
556
+ return false;
557
+ break;
558
+ }
559
+ targets = [];
560
+ for (; index < args.length && !/^[-(!)]/.test(args[index] ?? ""); index++)
561
+ targets.push(args[index]);
562
+ if (!knownFindExpression(args.slice(index)))
563
+ return false;
564
+ if (targets.length === 0)
565
+ targets = ["."];
566
+ }
567
+ else
568
+ return false;
569
+ return targets.length > 0 && targets.every((target) => disposable(cwd, target, roots, fill));
570
+ }
158
571
  export function permissiveRead(cwd, input) {
159
572
  try {
160
- const lexical = resolve(cwd, input);
573
+ const lexical = resolveWord(cwd, input);
161
574
  const path = canonical(lexical);
162
575
  if (sensitive(path) || sensitive(lexical))
163
576
  return {
@@ -179,10 +592,41 @@ export function permissiveRead(cwd, input) {
179
592
  };
180
593
  }
181
594
  }
182
- export function permissiveWrite(cwd, input, profile) {
595
+ const DISPOSABLE_WRITES = new Set([
596
+ "Write within a scratch directory",
597
+ "Write within the system temp directory",
598
+ ]);
599
+ /** Temp and scratch writes are trusted only before anything could plant a symlink (see `Fill`). */
600
+ export function permissiveWrite(cwd, input, profile, fill) {
601
+ const check = writeEvidence(cwd, input, profile);
602
+ if (!check.allowed || !fill || !DISPOSABLE_WRITES.has(check.reason))
603
+ return check;
604
+ if (fill.script.tainted)
605
+ return {
606
+ allowed: false,
607
+ category: "temp-write",
608
+ reason: "Temp write after a command that can create symlinks requires review",
609
+ };
610
+ if (fill.reorder)
611
+ fill.script.approved = true;
612
+ return check;
613
+ }
614
+ /** A file with another hard link may alias a file outside the scratch root; unknown counts as yes. */
615
+ function hardLinked(path) {
183
616
  try {
184
- const lexical = resolve(cwd, input);
185
- const path = canonical(lexical);
617
+ const stat = lstatSync(path);
618
+ return !stat.isDirectory() && stat.nlink > 1;
619
+ }
620
+ catch (error) {
621
+ return error.code !== "ENOENT";
622
+ }
623
+ }
624
+ function writeEvidence(cwd, input, profile) {
625
+ let lexical;
626
+ let path;
627
+ try {
628
+ lexical = resolveWord(cwd, input);
629
+ path = canonical(lexical);
186
630
  if (sensitive(path) || sensitive(lexical) || isProtectedPath(path) || isProtectedPath(lexical))
187
631
  return {
188
632
  allowed: false,
@@ -190,8 +634,11 @@ export function permissiveWrite(cwd, input, profile) {
190
634
  reason: "Protected path requires human approval",
191
635
  };
192
636
  // Never let a scratch root reach the policy service's own session directories.
193
- if (!path.split(/[\\/]/).some((part) => part.startsWith("acp-")) &&
194
- profile.scratchRoots.some((root) => inside(root, path)))
637
+ const target = path;
638
+ if (!policyState(target) &&
639
+ !policyState(lexical) &&
640
+ !hardLinked(target) &&
641
+ profile.scratchRoots.some((root) => inside(root, target)))
195
642
  return {
196
643
  allowed: true,
197
644
  category: "worktree-write",
@@ -201,7 +648,19 @@ export function permissiveWrite(cwd, input, profile) {
201
648
  catch {
202
649
  /* fall through to the repository check, which fails closed */
203
650
  }
204
- return pathEvidence(cwd, input, true);
651
+ const evidence = pathEvidence(cwd, input, true);
652
+ // Repository rules win; the temp directory only covers writes outside any repository.
653
+ if (!evidence.allowed &&
654
+ evidence.reason === OUTSIDE_REPOSITORY &&
655
+ lexical &&
656
+ path &&
657
+ tempWrite(lexical, path))
658
+ return {
659
+ allowed: true,
660
+ category: "temp-write",
661
+ reason: "Write within the system temp directory",
662
+ };
663
+ return evidence;
205
664
  }
206
665
  export function unwrap(argv) {
207
666
  let current = argv;
@@ -246,7 +705,87 @@ function safeConfigWrite(rest) {
246
705
  const words = rest.filter((word) => !word.startsWith("-"));
247
706
  return words.length >= 1 && words.length <= 2 && SAFE_CONFIG_KEYS.test(words[0] ?? "");
248
707
  }
249
- function gitDecision(request, argv, cwdForGit) {
708
+ const RECOVERABLE = "Removes only tracked content Git can restore, in a linked feature worktree";
709
+ const SESSION_CREATED = "Removes files this session created, unchanged since, in a feature worktree";
710
+ /** The one destructive reason the session classifier may decide; every other stays a person's. */
711
+ export const WORKTREE_DELETION = "Deleting files inside a linked feature worktree";
712
+ /** Splits `args` at the first `--`: options and words before it, and the words after it. */
713
+ function splitDashes(args) {
714
+ const at = args.indexOf("--");
715
+ return at < 0
716
+ ? { before: args, after: undefined }
717
+ : { before: args.slice(0, at), after: args.slice(at + 1) };
718
+ }
719
+ /** Paths of `git checkout -- <paths>` or `git checkout .`, with at most -q; else undefined. */
720
+ function checkoutPaths(rest) {
721
+ const { before, after } = splitDashes(rest);
722
+ if (before.some((word) => !["-q", "--quiet"].includes(word) && word.startsWith("-")))
723
+ return undefined;
724
+ const positional = before.filter((word) => !word.startsWith("-"));
725
+ if (after)
726
+ return positional.length ? undefined : after;
727
+ return positional.length === 1 && positional[0] === "." ? positional : undefined;
728
+ }
729
+ /** Paths and source of `git restore [-W] [-S] [-q] [--] <paths>`; else undefined. */
730
+ function restorePaths(rest) {
731
+ const { before, after } = splitDashes(rest);
732
+ const flags = before.filter((word) => word.startsWith("-"));
733
+ const known = ["--worktree", "--staged", "--quiet"];
734
+ if (flags.some((flag) => !/^-[SWq]+$/.test(flag) && !known.includes(flag)))
735
+ return undefined;
736
+ const staged = flags.some((flag) => flag === "--staged" || /^-[SWq]*S/.test(flag));
737
+ return {
738
+ paths: [...before.filter((word) => !word.startsWith("-")), ...(after ?? [])],
739
+ fromHead: staged,
740
+ };
741
+ }
742
+ /**
743
+ * `git worktree remove --force <path>` where `path` is a linked worktree of this repository (never
744
+ * the main one) strictly inside a temp or scratch root and outside the main checkout.
745
+ */
746
+ function disposableWorktree(cwd, args, roots, fill) {
747
+ if (fill?.script.tainted)
748
+ return false;
749
+ const paths = [];
750
+ let ended = false;
751
+ let forces = 0;
752
+ for (const arg of args) {
753
+ if (!ended && arg === "--")
754
+ ended = true;
755
+ else if (!ended && arg.startsWith("-")) {
756
+ if (arg !== "-f" && !abbreviates(arg, "--force"))
757
+ return false;
758
+ forces++;
759
+ }
760
+ else
761
+ paths.push(arg);
762
+ }
763
+ // A second force also removes a locked worktree, and a lock is an explicit keep marker.
764
+ if (paths.length !== 1 || forces !== 1)
765
+ return false;
766
+ try {
767
+ const target = canonical(resolveWord(cwd, paths[0]));
768
+ if (policyState(target) || !roots.some((root) => root !== target && inside(root, target)))
769
+ return false;
770
+ const listed = git(cwd, ["worktree", "list", "--porcelain"])
771
+ .split("\n")
772
+ .filter((line) => line.startsWith("worktree "))
773
+ .map((line) => canonical(line.slice("worktree ".length)));
774
+ const [main, ...linked] = listed;
775
+ if (main === undefined || inside(main, target) || !linked.includes(target))
776
+ return false;
777
+ // Removal deletes the whole directory, so no other checkout may live inside it.
778
+ if (listed.some((path) => path !== target && inside(target, path)))
779
+ return false;
780
+ if (fill?.reorder)
781
+ fill.script.approved = true;
782
+ return true;
783
+ }
784
+ catch {
785
+ return false;
786
+ }
787
+ }
788
+ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
250
789
  const args = argv.slice(1);
251
790
  let index = 0;
252
791
  let cwd = cwdForGit;
@@ -281,18 +820,36 @@ function gitDecision(request, argv, cwdForGit) {
281
820
  }
282
821
  if (sub === "branch" && (has("-f", "--force") || cluster("f") || has("-M")))
283
822
  return human(request, "destructive", "Forced branch move requires human approval");
284
- if (sub === "reset" && has("--hard"))
285
- return human(request, "destructive", "git reset --hard discards work");
823
+ if (sub === "rm" && (has("-f", "--force") || cluster("f")))
824
+ return sole() && gitRmRecoverable(cwd, rest)
825
+ ? ok(RECOVERABLE)
826
+ : human(request, "destructive", "git rm --force can discard uncommitted changes");
827
+ if (sub === "reset" && has("--hard")) {
828
+ const plain = !rest.includes("--") &&
829
+ positional.length <= 1 &&
830
+ flags.every((flag) => abbreviates(flag, "--hard") || ["-q", "--quiet"].includes(flag));
831
+ return plain && sole() && resetRecoverable(cwd, positional[0])
832
+ ? ok("Reset loses no uncommitted work, and dropped commits are on a remote ref")
833
+ : human(request, "destructive", "git reset --hard discards work");
834
+ }
286
835
  if (sub === "clean" && !has("-n", "--dry-run") && !cluster("n"))
287
836
  return human(request, "destructive", "git clean deletes untracked files");
288
837
  if (sub === "checkout" &&
289
838
  (has("-f", "--force", "-B") ||
290
839
  rest.includes("--") ||
291
840
  positional.includes(".") ||
292
- positional.includes(":/")))
293
- return human(request, "destructive", "git checkout would discard working-tree changes");
294
- if (sub === "restore" && (!has("--staged", "-S") || has("--worktree", "-W") || cluster("W")))
295
- return human(request, "destructive", "git restore would discard working-tree changes");
841
+ positional.includes(":/"))) {
842
+ const paths = checkoutPaths(rest);
843
+ return paths && sole() && restoreRecoverable(cwd, paths, false)
844
+ ? ok("Checkout overwrites no working-tree change")
845
+ : human(request, "destructive", "git checkout would discard working-tree changes");
846
+ }
847
+ if (sub === "restore" && (!has("--staged", "-S") || has("--worktree", "-W") || cluster("W"))) {
848
+ const parsed = restorePaths(rest);
849
+ return parsed && sole() && restoreRecoverable(cwd, parsed.paths, parsed.fromHead)
850
+ ? ok("Restore overwrites no working-tree change")
851
+ : human(request, "destructive", "git restore would discard working-tree changes");
852
+ }
296
853
  if (sub === "switch" && has("-f", "--force", "--discard-changes"))
297
854
  return human(request, "destructive", "git switch would discard working-tree changes");
298
855
  if (sub === "stash" && ["drop", "clear"].includes(positional[0] ?? ""))
@@ -302,10 +859,17 @@ function gitDecision(request, argv, cwdForGit) {
302
859
  if (["gc", "prune", "filter-branch", "filter-repo", "replace"].includes(sub) ||
303
860
  (sub === "update-ref" && has("-d")))
304
861
  return human(request, "destructive", "Repository history or object pruning requires human approval");
862
+ if (sub === "worktree" && positional[0] === "add")
863
+ return worktreeAdd(request, cwd, rest.slice(rest.indexOf("add") + 1)) ?? ok();
305
864
  if (sub === "worktree" &&
306
865
  ["remove", "prune"].includes(positional[0] ?? "") &&
307
- (has("-f", "--force") || positional[0] === "prune"))
308
- return human(request, "destructive", "Forced worktree removal requires human approval");
866
+ (has("-f", "--force") || cluster("f") || positional[0] === "prune"))
867
+ return positional[0] === "remove" && disposableWorktree(cwd, rest.slice(1), roots, fill)
868
+ ? ok("Removes a linked worktree inside a temp or scratch directory")
869
+ : positional[0] === "prune" &&
870
+ rest.slice(1).every((arg) => ["-n", "-v", "--dry-run", "--verbose"].includes(arg))
871
+ ? ok("Prunes only records of worktrees whose directories are gone")
872
+ : human(request, "destructive", "Forced worktree removal requires human approval");
309
873
  if (sub === "config" &&
310
874
  !has("--get", "--get-all", "--get-regexp", "--list", "-l", "--show-origin") &&
311
875
  !safeConfigWrite(rest))
@@ -315,6 +879,57 @@ function gitDecision(request, argv, cwdForGit) {
315
879
  return human(request, "impactful-write", "Changing remotes requires human approval");
316
880
  return ok();
317
881
  }
882
+ /**
883
+ * `git worktree add` from any clone is approved, except that the main checkout's working tree
884
+ * stays protected: a new worktree inside it must go under `.worktrees/` or `.claude/worktrees/`.
885
+ * `-B` resets an existing branch, so it needs a human.
886
+ */
887
+ function worktreeAdd(request, cwd, args) {
888
+ const positional = [];
889
+ for (let i = 0; i < args.length; i++) {
890
+ const word = args[i];
891
+ if (word === "--") {
892
+ positional.push(...args.slice(i + 1));
893
+ break;
894
+ }
895
+ if (word.startsWith("--")) {
896
+ // Only --reason takes a value (the next word unless given inline as `--reason=x`). Every
897
+ // other long option of `worktree add` is a switch: --orphan, --lock, --track, --force, ...
898
+ if (!word.includes("=") && abbreviates(word, "--reason"))
899
+ i++;
900
+ }
901
+ else if (word.startsWith("-") && word.length > 1) {
902
+ // A cluster of short flags (`-qb`, `-fB`): the first `b` or `B` takes the rest of the word
903
+ // as its value (`-bname`), or the next word when it ends the cluster.
904
+ const letters = word.slice(1);
905
+ const at = letters.search(/[bB]/);
906
+ if (letters[at] === "B")
907
+ return human(request, "destructive", "git worktree add -B resets an existing branch");
908
+ if (at === letters.length - 1)
909
+ i++;
910
+ }
911
+ else
912
+ positional.push(word);
913
+ }
914
+ const path = positional[0];
915
+ if (!path)
916
+ return undefined;
917
+ try {
918
+ const common = canonical(resolve(cwd, git(cwd, ["rev-parse", "--git-common-dir"])));
919
+ if (basename(common) !== ".git")
920
+ return undefined; // a bare repository has no working tree
921
+ const main = dirname(common);
922
+ const target = canonical(resolve(cwd, path));
923
+ if (!inside(main, target))
924
+ return undefined;
925
+ if ([resolve(main, ".worktrees"), resolve(main, ".claude", "worktrees")].some((parent) => inside(parent, target) && target !== parent))
926
+ return undefined;
927
+ }
928
+ catch {
929
+ return undefined; // not a repository: git refuses the command itself
930
+ }
931
+ return human(request, "worktree-write", "Write requires a linked worktree on a feature branch: a new worktree inside the main checkout goes under .worktrees/ or .claude/worktrees/");
932
+ }
318
933
  function gitPush(request, cwd, rest) {
319
934
  const flags = rest.filter((word) => word.startsWith("-"));
320
935
  const positional = rest.filter((word) => !word.startsWith("-"));
@@ -401,6 +1016,8 @@ const AWS_METADATA_GETTERS = new Set([
401
1016
  "get-metric-statistics",
402
1017
  "get-log-events",
403
1018
  ]);
1019
+ /** az operations that only read but whose verb is not list or show. */
1020
+ const AZ_READ_OPERATIONS = new Set(["boards query"]);
404
1021
  function readVerb(argv) {
405
1022
  const [tool] = argv;
406
1023
  const firstOption = argv.findIndex((arg) => arg.startsWith("-"));
@@ -415,7 +1032,8 @@ function readVerb(argv) {
415
1032
  if (/token|secret|password|credential|key/i.test(verb))
416
1033
  return false;
417
1034
  if (tool === "az")
418
- return /^(?:list|show|exists|list-[a-z-]+|show-[a-z-]+)$/.test(verb);
1035
+ return (/^(?:list|show|exists|list-[a-z-]+|show-[a-z-]+)$/.test(verb) ||
1036
+ AZ_READ_OPERATIONS.has(operation.join(" ")));
419
1037
  if (tool === "aws") {
420
1038
  // `get-*` is not safe as a family: it includes secret, password, token and access-detail
421
1039
  // retrieval. Only `describe-`/`list-` and an explicit set of metadata getters are automatic.
@@ -443,7 +1061,7 @@ function cloudDecision(request, argv, profile) {
443
1061
  return strict;
444
1062
  }
445
1063
  /** Judges one redirection's target in `cwd`; undefined means it is acceptable. */
446
- export function redirectDecision(request, redirect, profile, cwd) {
1064
+ export function redirectDecision(request, redirect, profile, cwd, fill) {
447
1065
  if (redirect.target.includes(SUBSTITUTION))
448
1066
  return human(request, "unknown", "Command substitution in a redirection requires human review");
449
1067
  // `>& word` duplicates a descriptor only when word is a number or `-`; otherwise it names a file.
@@ -452,7 +1070,7 @@ export function redirectDecision(request, redirect, profile, cwd) {
452
1070
  return undefined;
453
1071
  const check = redirect.op === "<"
454
1072
  ? permissiveRead(cwd, redirect.target)
455
- : permissiveWrite(cwd, redirect.target, profile);
1073
+ : permissiveWrite(cwd, redirect.target, profile, fill);
456
1074
  return check.allowed ? undefined : human(request, check.category, check.reason);
457
1075
  }
458
1076
  /** printf formats with only %s, %b, %q and %%: no argument is evaluated as arithmetic. */
@@ -507,12 +1125,349 @@ function interpreterCodeRefusal(code) {
507
1125
  return "Interpreter code that names a protected or credential path requires human review";
508
1126
  return undefined;
509
1127
  }
510
- export function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
1128
+ /**
1129
+ * zsh builtins and reserved words. AUTO_CD is a zsh option, so a bash-only builtin (`help`,
1130
+ * `mapfile`) is not a command there and a directory of that name is entered.
1131
+ */
1132
+ const SHELL_WORDS = new Set((". : [ [[ ]] { } ! alias autoload bg bindkey break builtin case cd chdir command continue " +
1133
+ "coproc declare dirs disown do done echo elif else emulate enable esac eval exec exit export " +
1134
+ "false fc fg float for function functions getopts hash history if in integer jobs kill let " +
1135
+ "local logout noglob nocorrect popd print printf pushd pwd read readonly repeat return select " +
1136
+ "set setopt shift source suspend test then time times trap true type typeset ulimit umask " +
1137
+ "unalias unset unsetopt until wait whence where which while zle zmodload zstyle").split(" "));
1138
+ /** Commands that change the shell's directory. */
1139
+ const DIRECTORY_CHANGERS = new Set(["cd", "chdir", "pushd", "popd"]);
1140
+ /**
1141
+ * Whether zsh AUTO_CD could run `word` as `cd word`: it names an existing directory and no
1142
+ * executable of that name is on PATH.
1143
+ */
1144
+ function autoCd(cwd, word) {
1145
+ // A builtin or keyword is a command, so AUTO_CD never applies; `.` is `source`.
1146
+ if (SHELL_WORDS.has(word))
1147
+ return false;
1148
+ try {
1149
+ if (!statSync(resolveWord(cwd, word)).isDirectory())
1150
+ return false;
1151
+ }
1152
+ catch {
1153
+ return false;
1154
+ }
1155
+ if (/[\\/]/.test(word) || word === "..")
1156
+ return true;
1157
+ return !(process.env.PATH ?? "").split(delimiter).some((dir) => {
1158
+ try {
1159
+ return dir !== "" && statSync(join(dir, word)).isFile();
1160
+ }
1161
+ catch {
1162
+ return false;
1163
+ }
1164
+ });
1165
+ }
1166
+ const PRINTERS = new Set(["echo", "printf"]);
1167
+ const GLOB = /[*?[]/;
1168
+ /** At most this many directory entries are matched against a glob operand. */
1169
+ const GLOB_ENTRIES = 5000;
1170
+ /**
1171
+ * Whether a word that may be a file operand names a credential: by name, as resolved against the
1172
+ * working directory (a symlink to a key, or a cwd inside `~/.ssh`), or, for a glob in its last
1173
+ * component, by any entry it would match.
1174
+ */
1175
+ function sensitiveOperand(cwd, word) {
1176
+ if (word === "")
1177
+ return false;
1178
+ if (sensitive(word))
1179
+ return true;
1180
+ if (GLOB.test(word))
1181
+ return sensitiveGlob(cwd, word);
1182
+ try {
1183
+ const lexical = resolveWord(cwd, word);
1184
+ if (!lstatExists(lexical))
1185
+ return false;
1186
+ return sensitive(lexical) || sensitive(canonical(lexical));
1187
+ }
1188
+ catch {
1189
+ return false;
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Expands a glob one component at a time, as the shell would, and reports whether any directory
1194
+ * it passes or entry it matches is a credential path. Fails closed: an unreadable directory, an
1195
+ * unresolvable entry or more than GLOB_ENTRIES entries in total count as sensitive.
1196
+ */
1197
+ function sensitiveGlob(cwd, word) {
1198
+ try {
1199
+ const parts = word.split(/[\\/]/);
1200
+ // zsh `**/` matches any depth (and `***/` follows symlinks): too wide to expand here.
1201
+ if (parts.some((part) => part.includes("**")))
1202
+ return true;
1203
+ const first = parts.findIndex((part) => GLOB.test(part));
1204
+ const prefix = parts.slice(0, first).join("/");
1205
+ const start = resolveWord(cwd, first === 0 ? "." : prefix || "/");
1206
+ if (sensitive(start) || sensitive(canonical(start)))
1207
+ return true;
1208
+ let current = [start];
1209
+ let budget = GLOB_ENTRIES;
1210
+ for (const part of parts.slice(first)) {
1211
+ if (part === "" || part === ".")
1212
+ continue;
1213
+ const next = [];
1214
+ for (const dir of current) {
1215
+ if (!GLOB.test(part)) {
1216
+ const path = join(dir, part);
1217
+ if (sensitive(path) || (lstatExists(path) && sensitive(canonical(path))))
1218
+ return true;
1219
+ next.push(path);
1220
+ continue;
1221
+ }
1222
+ let entries;
1223
+ try {
1224
+ if (!statSync(dir).isDirectory())
1225
+ continue;
1226
+ entries = readdirSync(dir);
1227
+ }
1228
+ catch (error) {
1229
+ if (error.code === "ENOENT")
1230
+ continue;
1231
+ return true;
1232
+ }
1233
+ budget -= entries.length;
1234
+ if (budget < 0)
1235
+ return true;
1236
+ const pattern = globPattern(part);
1237
+ // `*` skips dot files unless the pattern itself starts with a dot.
1238
+ for (const name of entries) {
1239
+ if ((name.startsWith(".") && !part.startsWith(".")) || !pattern.test(name))
1240
+ continue;
1241
+ const path = join(dir, name);
1242
+ if (sensitive(name) || sensitive(canonical(path)))
1243
+ return true;
1244
+ next.push(path);
1245
+ }
1246
+ }
1247
+ current = next;
1248
+ }
1249
+ return false;
1250
+ }
1251
+ catch {
1252
+ return true;
1253
+ }
1254
+ }
1255
+ function lstatExists(path) {
1256
+ try {
1257
+ lstatSync(path);
1258
+ return true;
1259
+ }
1260
+ catch {
1261
+ return false;
1262
+ }
1263
+ }
1264
+ /** A shell glob for one path component: `*`, `?` and bracket classes. */
1265
+ function globPattern(glob) {
1266
+ let source = "";
1267
+ for (let index = 0; index < glob.length; index++) {
1268
+ const char = glob[index];
1269
+ if (char === "*")
1270
+ source += ".*";
1271
+ else if (char === "?")
1272
+ source += ".";
1273
+ else if (char === "[") {
1274
+ const close = glob.indexOf("]", index + 2);
1275
+ if (close < 0)
1276
+ source += "\\[";
1277
+ else {
1278
+ const body = glob
1279
+ .slice(index + 1, close)
1280
+ .replace(/^[!^]/, "^")
1281
+ .replace(/\\/g, "\\\\");
1282
+ source += `[${body}]`;
1283
+ index = close;
1284
+ }
1285
+ }
1286
+ else
1287
+ source += char.replace(/[.+^${}()|[\]\\/-]/g, "\\$&");
1288
+ }
1289
+ try {
1290
+ return new RegExp(`^${source}$`, "s");
1291
+ }
1292
+ catch {
1293
+ return /^/; // an unparsable class matches everything, which only sends more to a person
1294
+ }
1295
+ }
1296
+ const NAME_PATTERN_OPTIONS = {
1297
+ grep: ["--include", "--exclude", "--exclude-dir"],
1298
+ egrep: ["--include", "--exclude", "--exclude-dir"],
1299
+ fgrep: ["--include", "--exclude", "--exclude-dir"],
1300
+ rg: ["--glob", "--iglob", "-g"],
1301
+ find: ["-name", "-iname", "-path", "-ipath", "-wholename", "-iwholename"],
1302
+ };
1303
+ /**
1304
+ * Indices of find's `-name`/`-path` values. Every value-taking primary consumes its value; an
1305
+ * unknown primary (`-printf`, `-newerXY`) makes the parse uncertain, so nothing is a pattern.
1306
+ */
1307
+ function findPatterns(args) {
1308
+ const found = new Set();
1309
+ const names = NAME_PATTERN_OPTIONS.find ?? [];
1310
+ for (let index = 0; index < args.length; index++) {
1311
+ const word = args[index] ?? "";
1312
+ if (FIND_VALUE_PRIMARIES.has(word)) {
1313
+ if (names.includes(word))
1314
+ found.add(index + 1);
1315
+ index++;
1316
+ }
1317
+ else if (/^[-(!)]/.test(word) && !FIND_FLAG_PRIMARIES.has(word))
1318
+ return new Set();
1319
+ }
1320
+ return found;
1321
+ }
1322
+ /** Index of chmod's mode or chown's owner (`+x`, `u+w`, `user:group`), which names no file. */
1323
+ function modeIndex(program, args) {
1324
+ if (!["chmod", "chown"].includes(program) || args.some((arg) => arg.startsWith("--reference")))
1325
+ return undefined;
1326
+ // BSD chmod's ACL options (-N, -E, -C, -i, -I) take no mode: every operand is a file.
1327
+ if (program === "chmod" && args.some((arg) => /^-[A-Za-z]*[NECiI]/.test(arg)))
1328
+ return undefined;
1329
+ for (let index = 0; index < args.length; index++) {
1330
+ const arg = args[index] ?? "";
1331
+ if (arg === "--")
1332
+ return index + 1 < args.length ? index + 1 : undefined;
1333
+ // `chmod -w file`: a mode may start with `-`.
1334
+ if (arg.startsWith("-") && !(program === "chmod" && /^-[rwxXst]+$/.test(arg)))
1335
+ continue;
1336
+ return index;
1337
+ }
1338
+ return undefined;
1339
+ }
1340
+ /**
1341
+ * GNU long options of cp and ln. Of those that take a separate value, only --target-directory
1342
+ * matters: a consumed `--sparse`/`--no-preserve` value only adds a read-checked source.
1343
+ */
1344
+ const COPY_LONG = {
1345
+ cp: [
1346
+ "--archive",
1347
+ "--attributes-only",
1348
+ "--backup",
1349
+ "--copy-contents",
1350
+ "--debug",
1351
+ "--dereference",
1352
+ "--force",
1353
+ "--interactive",
1354
+ "--keep-directory-symlink",
1355
+ "--link",
1356
+ "--no-clobber",
1357
+ "--no-dereference",
1358
+ "--no-preserve",
1359
+ "--no-target-directory",
1360
+ "--one-file-system",
1361
+ "--parents",
1362
+ "--preserve",
1363
+ "--recursive",
1364
+ "--reflink",
1365
+ "--remove-destination",
1366
+ "--sparse",
1367
+ "--strip-trailing-slashes",
1368
+ "--suffix",
1369
+ "--symbolic-link",
1370
+ "--target-directory",
1371
+ "--update",
1372
+ "--verbose",
1373
+ ],
1374
+ ln: [
1375
+ "--backup",
1376
+ "--directory",
1377
+ "--force",
1378
+ "--interactive",
1379
+ "--logical",
1380
+ "--no-dereference",
1381
+ "--no-target-directory",
1382
+ "--physical",
1383
+ "--relative",
1384
+ "--suffix",
1385
+ "--symbolic",
1386
+ "--target-directory",
1387
+ "--verbose",
1388
+ ],
1389
+ };
1390
+ /**
1391
+ * Sources and written targets of `cp` and `ln`: sources are only read (a symlink's target is not
1392
+ * touched), so they take the read check. Undefined when the split is uncertain (backup suffixes,
1393
+ * hard links, unknown options), and every operand is then checked as a write.
1394
+ */
1395
+ function copySources(program, args, cwd) {
1396
+ if (program !== "cp" && program !== "ln")
1397
+ return undefined;
1398
+ const operands = [];
1399
+ let target;
1400
+ let ended = false;
1401
+ let symbolic = false;
1402
+ for (let index = 0; index < args.length; index++) {
1403
+ const arg = args[index] ?? "";
1404
+ if (ended || !arg.startsWith("-") || arg === "-") {
1405
+ operands.push(arg);
1406
+ continue;
1407
+ }
1408
+ if (arg === "--") {
1409
+ ended = true;
1410
+ continue;
1411
+ }
1412
+ if (arg.startsWith("--")) {
1413
+ // Resolved as GNU getopt does (exact or unique prefix); unknown or ambiguous fails closed.
1414
+ const given = arg.split("=")[0] ?? "";
1415
+ const known = COPY_LONG[program] ?? [];
1416
+ const matches = known.includes(given) ? [given] : known.filter((o) => o.startsWith(given));
1417
+ const name = matches.length === 1 ? matches[0] : undefined;
1418
+ if (name === undefined || ["--backup", "--suffix", "--link"].includes(name))
1419
+ return undefined;
1420
+ if (name === "--symbolic")
1421
+ symbolic = true;
1422
+ if (name === "--target-directory") {
1423
+ if (target !== undefined)
1424
+ return undefined;
1425
+ target = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++index];
1426
+ if (target === undefined)
1427
+ return undefined;
1428
+ }
1429
+ continue;
1430
+ }
1431
+ const letters = arg.slice(1);
1432
+ const at = letters.indexOf("t");
1433
+ const flags = at < 0 ? letters : letters.slice(0, at);
1434
+ if (/[bS]/.test(flags))
1435
+ return undefined;
1436
+ if (program === "cp" && flags.includes("l"))
1437
+ return undefined;
1438
+ if (program === "ln" && flags.includes("s"))
1439
+ symbolic = true;
1440
+ if (at >= 0) {
1441
+ if (target !== undefined)
1442
+ return undefined;
1443
+ target = at + 1 < letters.length ? letters.slice(at + 1) : args[++index];
1444
+ if (target === undefined)
1445
+ return undefined;
1446
+ }
1447
+ }
1448
+ // A hard link shares its source's inode, so a later write through it changes the source.
1449
+ if (program === "ln" && !symbolic)
1450
+ return undefined;
1451
+ if (target !== undefined)
1452
+ return { sources: operands, targets: [target] };
1453
+ if (operands.length >= 2)
1454
+ return { sources: operands.slice(0, -1), targets: operands.slice(-1) };
1455
+ // `ln -s path` links `basename(path)` in the working directory.
1456
+ if (program === "ln" && operands.length === 1) {
1457
+ const only = operands[0] ?? "";
1458
+ const name = basename(only.replace(/[\\/]+$/, ""));
1459
+ if (!name || name === "." || name === "..")
1460
+ return undefined;
1461
+ return { sources: operands, targets: [resolve(cwd, name)] };
1462
+ }
1463
+ return undefined;
1464
+ }
1465
+ export function simpleDecision(request, command, profile, depth, stageIndex, cwd, fill) {
511
1466
  for (const [name] of command.env)
512
1467
  if (BANNED_ENV.test(name))
513
1468
  return human(request, "unknown", "Environment override requires human review");
514
1469
  for (const redirect of command.redirects) {
515
- const refusal = redirectDecision(request, redirect, profile, cwd);
1470
+ const refusal = redirectDecision(request, redirect, profile, cwd, fill);
516
1471
  if (refusal)
517
1472
  return refusal;
518
1473
  }
@@ -525,6 +1480,13 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
525
1480
  const looseAfterWrappers = command.loose?.slice(command.argv.length - unwrapped.argv.length);
526
1481
  const argv = withOpaqueValues(unwrapped.argv, looseAfterWrappers);
527
1482
  const program = basename(argv[0] ?? "");
1483
+ // Every directory change must move the tracked cwd, which the flow evaluator does for `cd` and
1484
+ // `chdir`. Behind a wrapper (`command cd`, `time cd`) or as a bare directory name (zsh AUTO_CD)
1485
+ // the shell still changes directory, but nothing tracks it.
1486
+ if (DIRECTORY_CHANGERS.has(program) && argv.length !== command.argv.length)
1487
+ return human(request, "unknown", "A directory change behind a wrapper requires human review");
1488
+ if (argv[0] !== undefined && autoCd(cwd, argv[0]))
1489
+ return human(request, "unknown", "A directory name used as a command (zsh AUTO_CD) requires human review");
528
1490
  // Words a wrapper consumed (env assignments, options, durations) are gone from `argv`, but an
529
1491
  // unquoted substitution in them can still split into extra words and pick a different program.
530
1492
  if (command.argv.slice(0, command.argv.length - argv.length).some((w) => w.includes(SUBSTITUTION)))
@@ -563,13 +1525,40 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
563
1525
  const joined = argv.join(" ");
564
1526
  if (profile.humanPatterns.some((pattern) => pattern.test(joined)))
565
1527
  return human(request, "destructive", "Matches an organization human-approval pattern");
566
- // Anything that looks like a credential or protected-config path stays with a human.
567
- for (const word of argv.slice(1)) {
1528
+ // Anything that looks like a credential or protected-config path stays with a human. Words in
1529
+ // known text positions (sed scripts, grep patterns, gh message text) are not paths, but the
1530
+ // files a sed script reads or writes are.
1531
+ const operands = textOperands(program, args);
1532
+ const namePatterns = operands.patterns;
1533
+ for (const [index, word] of args.entries()) {
1534
+ if (operands.text.has(index))
1535
+ continue;
568
1536
  const candidate = word.includes("=") ? word.slice(word.indexOf("=") + 1) : word;
569
- if (candidate.includes("/") || candidate.startsWith(".")) {
570
- if (sensitive(candidate))
571
- return human(request, "sensitive", "Protected path requires human approval");
572
- }
1537
+ // echo and printf read no file, so only a path-like word is judged, by name.
1538
+ const pathLike = candidate.includes("/") || candidate.startsWith(".");
1539
+ // A file-name pattern (`--include=*.md`, `find -name '*.ts'`) is matched below the searched
1540
+ // paths, not against the working directory, so it is judged by name only.
1541
+ const namePattern = namePatterns.has(index);
1542
+ if (PRINTERS.has(program) || namePattern
1543
+ ? (pathLike || namePattern) && sensitive(candidate)
1544
+ : sensitiveOperand(cwd, candidate) || (candidate !== word && sensitiveOperand(cwd, word)))
1545
+ return human(request, "sensitive", "Protected path requires human approval");
1546
+ }
1547
+ if (operands.paths.some((path) => sensitive(path)))
1548
+ return human(request, "sensitive", "Protected path requires human approval");
1549
+ if (["rm", "rmdir", "unlink", "shred", "srm"].includes(program) && deletesProtected(cwd, args))
1550
+ return human(request, "sensitive", "Deleting a protected or credential path requires a human");
1551
+ if (scratchDeletion(program, args, cwd, profile, fill))
1552
+ return result(request, "temp-write", "Delete within a scratch directory", true);
1553
+ if (argv[0] === "rm" && command.argv[0] === "rm") {
1554
+ const kind = depth === 0 && soleEffect(request) ? rmRecoverable(cwd, args) : undefined;
1555
+ if (kind)
1556
+ return result(request, "worktree-write", kind === "tracked" ? RECOVERABLE : SESSION_CREATED, true);
1557
+ // Classified only when this `rm` is the script's whole effect, in its one known directory;
1558
+ // otherwise this first refusal would hide every later command from the classifier's verdict.
1559
+ const only = depth === 0 ? deletionScriptCwd(request) : undefined;
1560
+ if (only !== undefined && resolve(only) === resolve(cwd) && worktreeDeletion(cwd, args))
1561
+ return human(request, "destructive", WORKTREE_DELETION);
573
1562
  }
574
1563
  if (DESTRUCTIVE.has(program) || program.startsWith("mkfs"))
575
1564
  return human(request, "destructive", "Destructive operation requires human approval");
@@ -599,7 +1588,7 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
599
1588
  : undefined;
600
1589
  if (script === undefined || depth >= 2)
601
1590
  return human(request, "unknown", "Shell invocation requires human review");
602
- return commandDecision(request, script, profile, depth + 1, [cwd]);
1591
+ return commandDecision(request, script, profile, depth + 1, [cwd], fill);
603
1592
  }
604
1593
  // Inline code and a heredoc body are both literal text, so both can be read. Code piped in
605
1594
  // from elsewhere cannot.
@@ -627,15 +1616,34 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
627
1616
  if ((program === "sed" &&
628
1617
  args.some((arg) => /^-[a-zA-Z]*i/.test(arg) || arg.startsWith("--in-place"))) ||
629
1618
  (program === "perl" && args.some((arg) => /^-[a-zA-Z]*i/.test(arg)))) {
630
- for (const file of args.filter((arg) => !arg.startsWith("-")).slice(1)) {
631
- const check = permissiveWrite(cwd, file, profile);
1619
+ const files = program === "sed"
1620
+ ? textOperands(program, args).files
1621
+ : args.filter((arg) => !arg.startsWith("-")).slice(1);
1622
+ for (const file of files) {
1623
+ const check = permissiveWrite(cwd, file, profile, fill);
632
1624
  if (!check.allowed)
633
1625
  return human(request, check.category, check.reason);
634
1626
  }
635
1627
  }
636
1628
  else if (WRITERS.has(program)) {
637
- for (const file of args.filter((arg) => !arg.startsWith("-") && !/^[0-9]+$/.test(arg))) {
638
- const check = permissiveWrite(cwd, file, profile);
1629
+ // Option values can name a target too: `--target-directory=/etc`, `-t/etc`.
1630
+ const optionValues = args.flatMap((arg) => {
1631
+ const value = /^--[^=]+=(.+)$/.exec(arg)?.[1] ??
1632
+ (["cp", "mv", "ln", "install"].includes(program)
1633
+ ? /^-[a-zA-Z]*t(.+)$/.exec(arg)?.[1]
1634
+ : undefined);
1635
+ return value === undefined ? [] : [value];
1636
+ });
1637
+ const split = copySources(program, args, cwd);
1638
+ const mode = modeIndex(program, args);
1639
+ const operands = args.filter((arg, index) => index !== mode && !arg.startsWith("-") && !/^[0-9]+$/.test(arg));
1640
+ for (const file of split?.sources ?? []) {
1641
+ const check = permissiveRead(cwd, file);
1642
+ if (!check.allowed)
1643
+ return human(request, check.category, check.reason);
1644
+ }
1645
+ for (const file of [...(split?.targets ?? operands), ...optionValues]) {
1646
+ const check = permissiveWrite(cwd, file, profile, fill);
639
1647
  if (!check.allowed)
640
1648
  return human(request, check.category, check.reason);
641
1649
  }
@@ -661,7 +1669,7 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
661
1669
  /(?:-X|--request)[=\s]?(?:DELETE|PUT)\b/i.test(joined))
662
1670
  return human(request, "destructive", "Destructive HTTP verbs require human approval");
663
1671
  if (program === "git")
664
- return gitDecision(request, argv, cwd);
1672
+ return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request), [...profile.scratchRoots, ...tempRoots()], fill);
665
1673
  if (program === "gh") {
666
1674
  const gh = ghDecision(request, argv);
667
1675
  if (gh)