@agent-corpus/policy-manager 0.5.0 → 0.6.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 { 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,407 @@ 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
+ if (program === "gh") {
298
+ for (const [index, word] of args.entries()) {
299
+ if (GH_TEXT.has(word))
300
+ text.add(index + 1);
301
+ else if (/^--(?:body|title|jq|template|notes)=/.test(word))
302
+ text.add(index);
303
+ }
304
+ return { text, paths: [], files };
305
+ }
306
+ const values = SHORT_VALUES[program];
307
+ if (values === undefined)
308
+ return { text, paths: [], files };
309
+ // Fallback when an option cannot be understood: every operand is checked.
310
+ const everyWord = {
311
+ text: new Set(),
312
+ paths: [],
313
+ files: args.filter((arg) => arg !== "" && !arg.startsWith("-")),
314
+ };
315
+ // grep, rg and GNU sed accept options after operands, so collect everything before deciding
316
+ // which operand, if any, is the pattern or script.
317
+ const scripts = [];
318
+ const operands = [];
319
+ let explicit = false;
320
+ let ended = false;
321
+ for (let index = 0; index < args.length; index++) {
322
+ const word = args[index] ?? "";
323
+ if (!ended && word === "--") {
324
+ ended = true;
325
+ continue;
326
+ }
327
+ if (!ended && word.startsWith("--")) {
328
+ const eq = word.indexOf("=");
329
+ const name = longOption(program, eq < 0 ? word : word.slice(0, eq));
330
+ if (name === undefined)
331
+ return everyWord;
332
+ if (name === "--context" && eq < 0 && DUAL_LONG.has(program))
333
+ return everyWord;
334
+ if (name === "--expression" || name === "--regexp") {
335
+ explicit = true;
336
+ if (eq >= 0)
337
+ scripts.push([index, word.slice(eq + 1)]);
338
+ else {
339
+ index++;
340
+ scripts.push([index, args[index] ?? ""]);
341
+ }
342
+ }
343
+ else {
344
+ // A pattern or script file means there is no pattern operand: every operand is a file.
345
+ if (name === "--file")
346
+ explicit = true;
347
+ // A value-taking long option consumes the next word, which stays a checked operand.
348
+ if (eq < 0 && LONG_VALUES[program]?.has(name))
349
+ index++;
350
+ }
351
+ continue;
352
+ }
353
+ if (!ended && /^-[A-Za-z]/.test(word)) {
354
+ for (let at = 1; at < word.length; at++) {
355
+ const flag = word[at] ?? "";
356
+ if (program === "sed" && flag === "i")
357
+ break; // the rest is a backup suffix
358
+ if (DUAL_SHORT[program]?.includes(flag))
359
+ return everyWord;
360
+ if (flag === "e") {
361
+ explicit = true;
362
+ if (at + 1 < word.length)
363
+ scripts.push([index, word.slice(at + 1)]);
364
+ else {
365
+ index++;
366
+ scripts.push([index, args[index] ?? ""]);
367
+ }
368
+ break;
369
+ }
370
+ if (values.includes(flag)) {
371
+ if (flag === "f")
372
+ explicit = true;
373
+ if (at + 1 === word.length)
374
+ index++;
375
+ break;
376
+ }
377
+ }
378
+ continue;
379
+ }
380
+ if (!ended && word.startsWith("-"))
381
+ continue;
382
+ // BSD `sed -i ''` leaves an empty suffix operand, which is skipped.
383
+ if (word !== "")
384
+ operands.push(index);
385
+ }
386
+ // The first operand is the script or pattern only when no -e, -f, --regexp, --expression or
387
+ // --file named one, wherever that option appears.
388
+ const first = explicit ? undefined : operands.shift();
389
+ if (first !== undefined)
390
+ scripts.push([first, args[first] ?? ""]);
391
+ for (const [index] of scripts)
392
+ text.add(index);
393
+ files.push(...operands.map((index) => args[index] ?? ""));
394
+ const paths = program === "sed" ? scripts.flatMap(([, script]) => sedScriptPaths(script)) : [];
395
+ return { text, paths, files };
396
+ }
397
+ /** Pattern and script options per program, besides the value lists. */
398
+ const PATTERN_OPTIONS = {
399
+ sed: ["--expression", "--file"],
400
+ grep: ["--regexp", "--file"],
401
+ egrep: ["--regexp", "--file"],
402
+ fgrep: ["--regexp", "--file"],
403
+ rg: ["--regexp", "--file"],
404
+ };
405
+ /**
406
+ * A long option name resolved as GNU getopt does: an exact match, or the one known option it
407
+ * abbreviates. Unknown or ambiguous names are undefined.
408
+ */
409
+ function longOption(program, name) {
410
+ const known = new Set([
411
+ ...(PATTERN_OPTIONS[program] ?? []),
412
+ ...(LONG_VALUES[program] ?? []),
413
+ ...(LONG_FLAGS[program] ?? []),
414
+ ]);
415
+ if (known.has(name))
416
+ return name;
417
+ // rg takes no abbreviations: `rg --files` is not `--files-with-matches`.
418
+ if (program === "rg")
419
+ return undefined;
420
+ const matches = [...known].filter((option) => option.startsWith(name));
421
+ return matches.length === 1 ? matches[0] : undefined;
422
+ }
423
+ const FIND_ACTIONS = new Set([
424
+ "-exec",
425
+ "-execdir",
426
+ "-ok",
427
+ "-okdir",
428
+ "-fprint",
429
+ "-fprint0",
430
+ "-fprintf",
431
+ "-fls",
432
+ ]);
433
+ /** find primaries that take one argument. */
434
+ const FIND_VALUE_PRIMARIES = new Set([
435
+ "amin",
436
+ "anewer",
437
+ "atime",
438
+ "cmin",
439
+ "cnewer",
440
+ "ctime",
441
+ "group",
442
+ "iname",
443
+ "inum",
444
+ "ipath",
445
+ "iregex",
446
+ "iwholename",
447
+ "links",
448
+ "maxdepth",
449
+ "mindepth",
450
+ "mmin",
451
+ "mtime",
452
+ "name",
453
+ "newer",
454
+ "path",
455
+ "perm",
456
+ "regex",
457
+ "size",
458
+ "type",
459
+ "user",
460
+ "wholename",
461
+ ].map((name) => `-${name}`));
462
+ /** find primaries and operators that take no argument. */
463
+ const FIND_FLAG_PRIMARIES = new Set([
464
+ ...[
465
+ "a",
466
+ "and",
467
+ "delete",
468
+ "depth",
469
+ "empty",
470
+ "false",
471
+ "mount",
472
+ "nogroup",
473
+ "not",
474
+ "nouser",
475
+ "o",
476
+ "or",
477
+ "print",
478
+ "print0",
479
+ "prune",
480
+ "true",
481
+ "xdev",
482
+ ].map((name) => `-${name}`),
483
+ "!",
484
+ "(",
485
+ ")",
486
+ ]);
487
+ /**
488
+ * Whether every word of a find expression is a known primary, operator or primary argument. bfs
489
+ * (behind Claude Code's `find`) also takes start paths, `-f` and `--` inside the expression, so an
490
+ * unknown word could be one.
491
+ */
492
+ function knownFindExpression(words) {
493
+ for (let index = 0; index < words.length; index++) {
494
+ const word = words[index] ?? "";
495
+ if (FIND_VALUE_PRIMARIES.has(word))
496
+ index++;
497
+ else if (!FIND_FLAG_PRIMARIES.has(word))
498
+ return false;
499
+ }
500
+ return true;
501
+ }
502
+ /**
503
+ * `rm`, `rmdir`, `unlink` or `find ... -delete` whose every target is disposable: strictly inside
504
+ * a scratch root or the system temp directory (see `disposable`).
505
+ */
506
+ function scratchDeletion(program, args, cwd, profile, fill) {
507
+ const roots = [...profile.scratchRoots, ...tempRoots()];
508
+ let targets;
509
+ if (program === "rm" || program === "rmdir" || program === "unlink") {
510
+ const end = args.indexOf("--");
511
+ const options = end < 0 ? args : args.slice(0, end);
512
+ targets = [
513
+ ...options.filter((arg) => !arg.startsWith("-")),
514
+ ...(end < 0 ? [] : args.slice(end + 1)),
515
+ ];
516
+ // `rmdir -p` also removes empty ancestors, up to and past a root.
517
+ // GNU accepts abbreviations (`--parent`, `--p`).
518
+ if (program === "rmdir" && options.some((arg) => /^--p/.test(arg) || /^-[^-]*p/.test(arg)))
519
+ return false;
520
+ }
521
+ else if (program === "find") {
522
+ if (!args.includes("-delete") ||
523
+ args.some((arg) => FIND_ACTIONS.has(arg) || ["-follow", "-files0-from"].includes(arg)))
524
+ return false;
525
+ // Leading options come before the start paths: GNU -P -D -O, BSD -E -s -x -X -d. -H, -L follow
526
+ // symlinks and BSD -f names a start path, so those stay with a person.
527
+ let index = 0;
528
+ for (; index < args.length; index++) {
529
+ const arg = args[index] ?? "";
530
+ if (arg === "--") {
531
+ index++;
532
+ break;
533
+ }
534
+ // BSD find accepts clusters such as -xP.
535
+ if (/^-[PEsxXd]+$/.test(arg) || /^-O[0-9]*$/.test(arg))
536
+ continue;
537
+ if (arg === "-D") {
538
+ index++;
539
+ continue;
540
+ }
541
+ // Expression primaries are words (-name, -type); a single letter is an unknown option.
542
+ if (/^-[HLf]$/.test(arg) || /^-.$/.test(arg))
543
+ return false;
544
+ break;
545
+ }
546
+ targets = [];
547
+ for (; index < args.length && !/^[-(!)]/.test(args[index] ?? ""); index++)
548
+ targets.push(args[index]);
549
+ if (!knownFindExpression(args.slice(index)))
550
+ return false;
551
+ if (targets.length === 0)
552
+ targets = ["."];
553
+ }
554
+ else
555
+ return false;
556
+ return targets.length > 0 && targets.every((target) => disposable(cwd, target, roots, fill));
557
+ }
158
558
  export function permissiveRead(cwd, input) {
159
559
  try {
160
- const lexical = resolve(cwd, input);
560
+ const lexical = resolveWord(cwd, input);
161
561
  const path = canonical(lexical);
162
562
  if (sensitive(path) || sensitive(lexical))
163
563
  return {
@@ -179,10 +579,31 @@ export function permissiveRead(cwd, input) {
179
579
  };
180
580
  }
181
581
  }
182
- export function permissiveWrite(cwd, input, profile) {
582
+ const DISPOSABLE_WRITES = new Set([
583
+ "Write within a scratch directory",
584
+ "Write within the system temp directory",
585
+ ]);
586
+ /** Temp and scratch writes are trusted only before anything could plant a symlink (see `Fill`). */
587
+ export function permissiveWrite(cwd, input, profile, fill) {
588
+ const check = writeEvidence(cwd, input, profile);
589
+ if (!check.allowed || !fill || !DISPOSABLE_WRITES.has(check.reason))
590
+ return check;
591
+ if (fill.script.tainted)
592
+ return {
593
+ allowed: false,
594
+ category: "temp-write",
595
+ reason: "Temp write after a command that can create symlinks requires review",
596
+ };
597
+ if (fill.reorder)
598
+ fill.script.approved = true;
599
+ return check;
600
+ }
601
+ function writeEvidence(cwd, input, profile) {
602
+ let lexical;
603
+ let path;
183
604
  try {
184
- const lexical = resolve(cwd, input);
185
- const path = canonical(lexical);
605
+ lexical = resolveWord(cwd, input);
606
+ path = canonical(lexical);
186
607
  if (sensitive(path) || sensitive(lexical) || isProtectedPath(path) || isProtectedPath(lexical))
187
608
  return {
188
609
  allowed: false,
@@ -190,8 +611,10 @@ export function permissiveWrite(cwd, input, profile) {
190
611
  reason: "Protected path requires human approval",
191
612
  };
192
613
  // 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)))
614
+ const target = path;
615
+ if (!policyState(target) &&
616
+ !policyState(lexical) &&
617
+ profile.scratchRoots.some((root) => inside(root, target)))
195
618
  return {
196
619
  allowed: true,
197
620
  category: "worktree-write",
@@ -201,7 +624,19 @@ export function permissiveWrite(cwd, input, profile) {
201
624
  catch {
202
625
  /* fall through to the repository check, which fails closed */
203
626
  }
204
- return pathEvidence(cwd, input, true);
627
+ const evidence = pathEvidence(cwd, input, true);
628
+ // Repository rules win; the temp directory only covers writes outside any repository.
629
+ if (!evidence.allowed &&
630
+ evidence.reason === OUTSIDE_REPOSITORY &&
631
+ lexical &&
632
+ path &&
633
+ tempWrite(lexical, path))
634
+ return {
635
+ allowed: true,
636
+ category: "temp-write",
637
+ reason: "Write within the system temp directory",
638
+ };
639
+ return evidence;
205
640
  }
206
641
  export function unwrap(argv) {
207
642
  let current = argv;
@@ -246,7 +681,41 @@ function safeConfigWrite(rest) {
246
681
  const words = rest.filter((word) => !word.startsWith("-"));
247
682
  return words.length >= 1 && words.length <= 2 && SAFE_CONFIG_KEYS.test(words[0] ?? "");
248
683
  }
249
- function gitDecision(request, argv, cwdForGit) {
684
+ const RECOVERABLE = "Removes only tracked content Git can restore, in a linked feature worktree";
685
+ const SESSION_CREATED = "Removes files this session created, unchanged since, in a feature worktree";
686
+ /** The one destructive reason the session classifier may decide; every other stays a person's. */
687
+ export const WORKTREE_DELETION = "Deleting files inside a linked feature worktree";
688
+ /** Splits `args` at the first `--`: options and words before it, and the words after it. */
689
+ function splitDashes(args) {
690
+ const at = args.indexOf("--");
691
+ return at < 0
692
+ ? { before: args, after: undefined }
693
+ : { before: args.slice(0, at), after: args.slice(at + 1) };
694
+ }
695
+ /** Paths of `git checkout -- <paths>` or `git checkout .`, with at most -q; else undefined. */
696
+ function checkoutPaths(rest) {
697
+ const { before, after } = splitDashes(rest);
698
+ if (before.some((word) => !["-q", "--quiet"].includes(word) && word.startsWith("-")))
699
+ return undefined;
700
+ const positional = before.filter((word) => !word.startsWith("-"));
701
+ if (after)
702
+ return positional.length ? undefined : after;
703
+ return positional.length === 1 && positional[0] === "." ? positional : undefined;
704
+ }
705
+ /** Paths and source of `git restore [-W] [-S] [-q] [--] <paths>`; else undefined. */
706
+ function restorePaths(rest) {
707
+ const { before, after } = splitDashes(rest);
708
+ const flags = before.filter((word) => word.startsWith("-"));
709
+ const known = ["--worktree", "--staged", "--quiet"];
710
+ if (flags.some((flag) => !/^-[SWq]+$/.test(flag) && !known.includes(flag)))
711
+ return undefined;
712
+ const staged = flags.some((flag) => flag === "--staged" || /^-[SWq]*S/.test(flag));
713
+ return {
714
+ paths: [...before.filter((word) => !word.startsWith("-")), ...(after ?? [])],
715
+ fromHead: staged,
716
+ };
717
+ }
718
+ function gitDecision(request, argv, cwdForGit, sole) {
250
719
  const args = argv.slice(1);
251
720
  let index = 0;
252
721
  let cwd = cwdForGit;
@@ -281,18 +750,36 @@ function gitDecision(request, argv, cwdForGit) {
281
750
  }
282
751
  if (sub === "branch" && (has("-f", "--force") || cluster("f") || has("-M")))
283
752
  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");
753
+ if (sub === "rm" && (has("-f", "--force") || cluster("f")))
754
+ return sole() && gitRmRecoverable(cwd, rest)
755
+ ? ok(RECOVERABLE)
756
+ : human(request, "destructive", "git rm --force can discard uncommitted changes");
757
+ if (sub === "reset" && has("--hard")) {
758
+ const plain = !rest.includes("--") &&
759
+ positional.length <= 1 &&
760
+ flags.every((flag) => abbreviates(flag, "--hard") || ["-q", "--quiet"].includes(flag));
761
+ return plain && sole() && resetRecoverable(cwd, positional[0])
762
+ ? ok("Reset loses no uncommitted work, and dropped commits are on a remote ref")
763
+ : human(request, "destructive", "git reset --hard discards work");
764
+ }
286
765
  if (sub === "clean" && !has("-n", "--dry-run") && !cluster("n"))
287
766
  return human(request, "destructive", "git clean deletes untracked files");
288
767
  if (sub === "checkout" &&
289
768
  (has("-f", "--force", "-B") ||
290
769
  rest.includes("--") ||
291
770
  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");
771
+ positional.includes(":/"))) {
772
+ const paths = checkoutPaths(rest);
773
+ return paths && sole() && restoreRecoverable(cwd, paths, false)
774
+ ? ok("Checkout overwrites no working-tree change")
775
+ : human(request, "destructive", "git checkout would discard working-tree changes");
776
+ }
777
+ if (sub === "restore" && (!has("--staged", "-S") || has("--worktree", "-W") || cluster("W"))) {
778
+ const parsed = restorePaths(rest);
779
+ return parsed && sole() && restoreRecoverable(cwd, parsed.paths, parsed.fromHead)
780
+ ? ok("Restore overwrites no working-tree change")
781
+ : human(request, "destructive", "git restore would discard working-tree changes");
782
+ }
296
783
  if (sub === "switch" && has("-f", "--force", "--discard-changes"))
297
784
  return human(request, "destructive", "git switch would discard working-tree changes");
298
785
  if (sub === "stash" && ["drop", "clear"].includes(positional[0] ?? ""))
@@ -302,6 +789,8 @@ function gitDecision(request, argv, cwdForGit) {
302
789
  if (["gc", "prune", "filter-branch", "filter-repo", "replace"].includes(sub) ||
303
790
  (sub === "update-ref" && has("-d")))
304
791
  return human(request, "destructive", "Repository history or object pruning requires human approval");
792
+ if (sub === "worktree" && positional[0] === "add")
793
+ return worktreeAdd(request, cwd, rest.slice(rest.indexOf("add") + 1)) ?? ok();
305
794
  if (sub === "worktree" &&
306
795
  ["remove", "prune"].includes(positional[0] ?? "") &&
307
796
  (has("-f", "--force") || positional[0] === "prune"))
@@ -315,6 +804,57 @@ function gitDecision(request, argv, cwdForGit) {
315
804
  return human(request, "impactful-write", "Changing remotes requires human approval");
316
805
  return ok();
317
806
  }
807
+ /**
808
+ * `git worktree add` from any clone is approved, except that the main checkout's working tree
809
+ * stays protected: a new worktree inside it must go under `.worktrees/` or `.claude/worktrees/`.
810
+ * `-B` resets an existing branch, so it needs a human.
811
+ */
812
+ function worktreeAdd(request, cwd, args) {
813
+ const positional = [];
814
+ for (let i = 0; i < args.length; i++) {
815
+ const word = args[i];
816
+ if (word === "--") {
817
+ positional.push(...args.slice(i + 1));
818
+ break;
819
+ }
820
+ if (word.startsWith("--")) {
821
+ // Only --reason takes a value (the next word unless given inline as `--reason=x`). Every
822
+ // other long option of `worktree add` is a switch: --orphan, --lock, --track, --force, ...
823
+ if (!word.includes("=") && abbreviates(word, "--reason"))
824
+ i++;
825
+ }
826
+ else if (word.startsWith("-") && word.length > 1) {
827
+ // A cluster of short flags (`-qb`, `-fB`): the first `b` or `B` takes the rest of the word
828
+ // as its value (`-bname`), or the next word when it ends the cluster.
829
+ const letters = word.slice(1);
830
+ const at = letters.search(/[bB]/);
831
+ if (letters[at] === "B")
832
+ return human(request, "destructive", "git worktree add -B resets an existing branch");
833
+ if (at === letters.length - 1)
834
+ i++;
835
+ }
836
+ else
837
+ positional.push(word);
838
+ }
839
+ const path = positional[0];
840
+ if (!path)
841
+ return undefined;
842
+ try {
843
+ const common = canonical(resolve(cwd, git(cwd, ["rev-parse", "--git-common-dir"])));
844
+ if (basename(common) !== ".git")
845
+ return undefined; // a bare repository has no working tree
846
+ const main = dirname(common);
847
+ const target = canonical(resolve(cwd, path));
848
+ if (!inside(main, target))
849
+ return undefined;
850
+ if ([resolve(main, ".worktrees"), resolve(main, ".claude", "worktrees")].some((parent) => inside(parent, target) && target !== parent))
851
+ return undefined;
852
+ }
853
+ catch {
854
+ return undefined; // not a repository: git refuses the command itself
855
+ }
856
+ 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/");
857
+ }
318
858
  function gitPush(request, cwd, rest) {
319
859
  const flags = rest.filter((word) => word.startsWith("-"));
320
860
  const positional = rest.filter((word) => !word.startsWith("-"));
@@ -443,7 +983,7 @@ function cloudDecision(request, argv, profile) {
443
983
  return strict;
444
984
  }
445
985
  /** Judges one redirection's target in `cwd`; undefined means it is acceptable. */
446
- export function redirectDecision(request, redirect, profile, cwd) {
986
+ export function redirectDecision(request, redirect, profile, cwd, fill) {
447
987
  if (redirect.target.includes(SUBSTITUTION))
448
988
  return human(request, "unknown", "Command substitution in a redirection requires human review");
449
989
  // `>& word` duplicates a descriptor only when word is a number or `-`; otherwise it names a file.
@@ -452,7 +992,7 @@ export function redirectDecision(request, redirect, profile, cwd) {
452
992
  return undefined;
453
993
  const check = redirect.op === "<"
454
994
  ? permissiveRead(cwd, redirect.target)
455
- : permissiveWrite(cwd, redirect.target, profile);
995
+ : permissiveWrite(cwd, redirect.target, profile, fill);
456
996
  return check.allowed ? undefined : human(request, check.category, check.reason);
457
997
  }
458
998
  /** printf formats with only %s, %b, %q and %%: no argument is evaluated as arithmetic. */
@@ -507,12 +1047,50 @@ function interpreterCodeRefusal(code) {
507
1047
  return "Interpreter code that names a protected or credential path requires human review";
508
1048
  return undefined;
509
1049
  }
510
- export function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
1050
+ /**
1051
+ * zsh builtins and reserved words. AUTO_CD is a zsh option, so a bash-only builtin (`help`,
1052
+ * `mapfile`) is not a command there and a directory of that name is entered.
1053
+ */
1054
+ const SHELL_WORDS = new Set((". : [ [[ ]] { } ! alias autoload bg bindkey break builtin case cd chdir command continue " +
1055
+ "coproc declare dirs disown do done echo elif else emulate enable esac eval exec exit export " +
1056
+ "false fc fg float for function functions getopts hash history if in integer jobs kill let " +
1057
+ "local logout noglob nocorrect popd print printf pushd pwd read readonly repeat return select " +
1058
+ "set setopt shift source suspend test then time times trap true type typeset ulimit umask " +
1059
+ "unalias unset unsetopt until wait whence where which while zle zmodload zstyle").split(" "));
1060
+ /** Commands that change the shell's directory. */
1061
+ const DIRECTORY_CHANGERS = new Set(["cd", "chdir", "pushd", "popd"]);
1062
+ /**
1063
+ * Whether zsh AUTO_CD could run `word` as `cd word`: it names an existing directory and no
1064
+ * executable of that name is on PATH.
1065
+ */
1066
+ function autoCd(cwd, word) {
1067
+ // A builtin or keyword is a command, so AUTO_CD never applies; `.` is `source`.
1068
+ if (SHELL_WORDS.has(word))
1069
+ return false;
1070
+ try {
1071
+ if (!statSync(resolveWord(cwd, word)).isDirectory())
1072
+ return false;
1073
+ }
1074
+ catch {
1075
+ return false;
1076
+ }
1077
+ if (/[\\/]/.test(word) || word === "..")
1078
+ return true;
1079
+ return !(process.env.PATH ?? "").split(delimiter).some((dir) => {
1080
+ try {
1081
+ return dir !== "" && statSync(join(dir, word)).isFile();
1082
+ }
1083
+ catch {
1084
+ return false;
1085
+ }
1086
+ });
1087
+ }
1088
+ export function simpleDecision(request, command, profile, depth, stageIndex, cwd, fill) {
511
1089
  for (const [name] of command.env)
512
1090
  if (BANNED_ENV.test(name))
513
1091
  return human(request, "unknown", "Environment override requires human review");
514
1092
  for (const redirect of command.redirects) {
515
- const refusal = redirectDecision(request, redirect, profile, cwd);
1093
+ const refusal = redirectDecision(request, redirect, profile, cwd, fill);
516
1094
  if (refusal)
517
1095
  return refusal;
518
1096
  }
@@ -525,6 +1103,13 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
525
1103
  const looseAfterWrappers = command.loose?.slice(command.argv.length - unwrapped.argv.length);
526
1104
  const argv = withOpaqueValues(unwrapped.argv, looseAfterWrappers);
527
1105
  const program = basename(argv[0] ?? "");
1106
+ // Every directory change must move the tracked cwd, which the flow evaluator does for `cd` and
1107
+ // `chdir`. Behind a wrapper (`command cd`, `time cd`) or as a bare directory name (zsh AUTO_CD)
1108
+ // the shell still changes directory, but nothing tracks it.
1109
+ if (DIRECTORY_CHANGERS.has(program) && argv.length !== command.argv.length)
1110
+ return human(request, "unknown", "A directory change behind a wrapper requires human review");
1111
+ if (argv[0] !== undefined && autoCd(cwd, argv[0]))
1112
+ return human(request, "unknown", "A directory name used as a command (zsh AUTO_CD) requires human review");
528
1113
  // Words a wrapper consumed (env assignments, options, durations) are gone from `argv`, but an
529
1114
  // unquoted substitution in them can still split into extra words and pick a different program.
530
1115
  if (command.argv.slice(0, command.argv.length - argv.length).some((w) => w.includes(SUBSTITUTION)))
@@ -563,14 +1148,35 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
563
1148
  const joined = argv.join(" ");
564
1149
  if (profile.humanPatterns.some((pattern) => pattern.test(joined)))
565
1150
  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)) {
1151
+ // Anything that looks like a credential or protected-config path stays with a human. Words in
1152
+ // known text positions (sed scripts, grep patterns, gh message text) are not paths, but the
1153
+ // files a sed script reads or writes are.
1154
+ const operands = textOperands(program, args);
1155
+ for (const [index, word] of args.entries()) {
1156
+ if (operands.text.has(index))
1157
+ continue;
568
1158
  const candidate = word.includes("=") ? word.slice(word.indexOf("=") + 1) : word;
569
1159
  if (candidate.includes("/") || candidate.startsWith(".")) {
570
1160
  if (sensitive(candidate))
571
1161
  return human(request, "sensitive", "Protected path requires human approval");
572
1162
  }
573
1163
  }
1164
+ if (operands.paths.some((path) => sensitive(path)))
1165
+ return human(request, "sensitive", "Protected path requires human approval");
1166
+ if (["rm", "rmdir", "unlink", "shred", "srm"].includes(program) && deletesProtected(cwd, args))
1167
+ return human(request, "sensitive", "Deleting a protected or credential path requires a human");
1168
+ if (scratchDeletion(program, args, cwd, profile, fill))
1169
+ return result(request, "temp-write", "Delete within a scratch directory", true);
1170
+ if (argv[0] === "rm" && command.argv[0] === "rm") {
1171
+ const kind = depth === 0 && soleEffect(request) ? rmRecoverable(cwd, args) : undefined;
1172
+ if (kind)
1173
+ return result(request, "worktree-write", kind === "tracked" ? RECOVERABLE : SESSION_CREATED, true);
1174
+ // Classified only when this `rm` is the script's whole effect, in its one known directory;
1175
+ // otherwise this first refusal would hide every later command from the classifier's verdict.
1176
+ const only = depth === 0 ? deletionScriptCwd(request) : undefined;
1177
+ if (only !== undefined && resolve(only) === resolve(cwd) && worktreeDeletion(cwd, args))
1178
+ return human(request, "destructive", WORKTREE_DELETION);
1179
+ }
574
1180
  if (DESTRUCTIVE.has(program) || program.startsWith("mkfs"))
575
1181
  return human(request, "destructive", "Destructive operation requires human approval");
576
1182
  if (REMOTE_EXECUTORS.has(program))
@@ -599,7 +1205,7 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
599
1205
  : undefined;
600
1206
  if (script === undefined || depth >= 2)
601
1207
  return human(request, "unknown", "Shell invocation requires human review");
602
- return commandDecision(request, script, profile, depth + 1, [cwd]);
1208
+ return commandDecision(request, script, profile, depth + 1, [cwd], fill);
603
1209
  }
604
1210
  // Inline code and a heredoc body are both literal text, so both can be read. Code piped in
605
1211
  // from elsewhere cannot.
@@ -627,15 +1233,29 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
627
1233
  if ((program === "sed" &&
628
1234
  args.some((arg) => /^-[a-zA-Z]*i/.test(arg) || arg.startsWith("--in-place"))) ||
629
1235
  (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);
1236
+ const files = program === "sed"
1237
+ ? textOperands(program, args).files
1238
+ : args.filter((arg) => !arg.startsWith("-")).slice(1);
1239
+ for (const file of files) {
1240
+ const check = permissiveWrite(cwd, file, profile, fill);
632
1241
  if (!check.allowed)
633
1242
  return human(request, check.category, check.reason);
634
1243
  }
635
1244
  }
636
1245
  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);
1246
+ // Option values can name a target too: `--target-directory=/etc`, `-t/etc`.
1247
+ const optionValues = args.flatMap((arg) => {
1248
+ const value = /^--[^=]+=(.+)$/.exec(arg)?.[1] ??
1249
+ (["cp", "mv", "ln", "install"].includes(program)
1250
+ ? /^-[a-zA-Z]*t(.+)$/.exec(arg)?.[1]
1251
+ : undefined);
1252
+ return value === undefined ? [] : [value];
1253
+ });
1254
+ for (const file of [
1255
+ ...args.filter((arg) => !arg.startsWith("-") && !/^[0-9]+$/.test(arg)),
1256
+ ...optionValues,
1257
+ ]) {
1258
+ const check = permissiveWrite(cwd, file, profile, fill);
639
1259
  if (!check.allowed)
640
1260
  return human(request, check.category, check.reason);
641
1261
  }
@@ -661,7 +1281,7 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
661
1281
  /(?:-X|--request)[=\s]?(?:DELETE|PUT)\b/i.test(joined))
662
1282
  return human(request, "destructive", "Destructive HTTP verbs require human approval");
663
1283
  if (program === "git")
664
- return gitDecision(request, argv, cwd);
1284
+ return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request));
665
1285
  if (program === "gh") {
666
1286
  const gh = ghDecision(request, argv);
667
1287
  if (gh)