@cratis/pi 7.184.0 → 7.185.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.
@@ -380,12 +380,49 @@ only these standalone install/repair operations (Node must be available):
380
380
  so `ln` cannot follow it and write into its target. File Write/Edit calls, including writes
381
381
  through repaired links, remain protected as before.
382
382
 
383
- All other commands retain the existing policy. The shell-write guard scans the **whole command text**
383
+ Before the reference fallback, destructive and bulk operations are checked by their effective
384
+ scope against the shared write policy. This includes removal/movement, find-delete, Git clean,
385
+ recursive copy destinations, local rsync destinations, archive extraction (including an implicit
386
+ current directory), explicit Git path rewrites and whole-worktree content effects. Literal `cd`
387
+ and Git `-C` contexts are tracked. Tar aliases, ditto, pax, cpio, 7-Zip extraction and Git
388
+ read-tree/checkout-index content effects use the same destination policy. Classified families
389
+ require exact recognized options, including their argument arities, before any dry-run, listing
390
+ or index-only allowance; option abbreviation and unknown options are refused. Git pathspec magic
391
+ is conservatively scoped to the enclosing worktree. Unknown destinations and uncertain execution
392
+ contexts refuse rather than assume a clean scope. Ordinary single-file copies are not treated
393
+ as recursive extraction.
394
+
395
+ Archive extraction is refused regardless of destination or current directory; exactly recognised
396
+ list/test/stdout modes remain admitted. Creation/append is an ordinary write of the archive output
397
+ path (or stdout) only with exactly recognised non-executing, non-deleting options; unknown options,
398
+ source deletion and program execution are refused. Option environments (`UNZIP`, `UNZIPOPT`,
399
+ `TAR_OPTIONS`, `ZIPOPT`) and argfile arguments are refused; assigning/exporting those variables is
400
+ also blocked. Extraction-to-stdout forms do not accept `--`. Extract outside the agent shell (or ask
401
+ the user), then copy the specific files needed. Git checkout-index still requires a directory
402
+ prefix ending in `/`, checked against all protected-path policy.
403
+
404
+ In destructive scope only, an existing directory also receives a metadata-only inventory for
405
+ environment-named descendants using the write guard's environment patterns. Matching entry names
406
+ include files, directories and symlinks, case-insensitively. Nested symlinks are not followed;
407
+ addressed directory aliases still receive the ordinary physical-path checks. Inventories are
408
+ bounded to 250,000 entries and five seconds per hook call, deduplicated within that call, never
409
+ cached across calls. Environment patterns cover control characters in entry names. Undecodable
410
+ names, inspection errors, changes observed during inspection, missing Node and exhausted limits refuse. Clean ordinary directories (including dependency/build trees) and
411
+ missing operands remain usable. Normal references and Write/Edit do not inventory descendants.
412
+
413
+ Git restore is index-only only when a narrowly parsed `--staged` form has no worktree flag.
414
+ Narrowly parsed default/soft/mixed reset also remains an index-only operation.
415
+ Checkout path forms and restore paths use their explicit scope; reset hard/merge/keep, stash
416
+ content operations and forced/discard/merge branch changes use whole-worktree scope even from
417
+ subdirectories. Ordinary non-forced branch checkout/switch/creation remains allowed intentionally;
418
+ this is not protection from every Git branch transition, alias, hook or configuration effect.
419
+ Unresolved Git worktree selection is refused for content effects.
420
+
421
+ All commands retain the later reference policy. The shell-write guard scans the **whole command text**
384
422
  for protected references, including nested strings, heredoc bodies and option values. It
385
423
  removes simple quoting/escapes, checks case-insensitive spellings, and asks the write guard's
386
424
  `--references` batch mode to classify candidate paths relative to the hook cwd. Original
387
- spellings are retained too so existing generated headers can be checked on case-sensitive
388
- filesystems. The lowercase alias of a path is dropped only where the original path exists and its
425
+ spellings are retained too for physical-path checks on case-sensitive filesystems. The lowercase alias of a path is dropped only where the original path exists and its
389
426
  lowercase spelling provably does not (a case-sensitive lookup); any doubt keeps it. Glob/bracket patterns are checked against that same policy; brace patterns
390
427
  are conservative. A directory containing owned controls/managed paths also counts, such as
391
428
  `.claude`, `.pi/extensions` or installed `.cratis/ai`; no second tree list lives in the shell
@@ -419,6 +456,8 @@ arguments are operands. A lone `-` is a stdin operand. Value-free short flags ma
419
456
  | `git log` | `--oneline --stat --name-only -n N -nN -<N> -p --no-color --format=<fmt> --pretty=<fmt> --follow` |
420
457
  | `git show` | `--stat --name-only -p --no-color --format=<fmt>` |
421
458
  | `git add` | `-A -u -p -v --all`; literal named paths, including corpus files, and path globs for installed prompts. No `-f` or `-N`/`--intent-to-add` |
459
+ | `git restore` (index only) | `--staged`/`-S` required, optional literal `--source`/`-s`; no worktree, patch or file-input option; literal repeated `-C` is supported |
460
+ | `git reset` (index only) | Default, `--soft` or `--mixed`; `--no-refresh -q --quiet`; no content-mode, patch or file-input option |
422
461
  | `git commit` | `-m MSG`, `--message MSG`, `-mMSG`, `-a`, `-q`; `-F FILE` only for a literal non-protected file; no `--no-verify` |
423
462
  | `git blame`, `ls-files`, `rev-parse`, `check-ignore`, `grep` | None |
424
463
  | `git branch` | Exactly `--show-current`, or `--list` followed only by literal patterns |
@@ -466,7 +505,7 @@ The tag tail takes exactly one pattern not starting with `-` (for example, `'*7.
466
505
  Those metadata tails accept no extra words. Literal `git -C <dir> add` and `commit` also qualify,
467
506
  with the ordinary per-verb option checks above. Attached `-Cdir`/`-C=dir`, repeated `-C`, other verbs and
468
507
  all other global options (`-c`, `--git-dir`, `--work-tree`, `--no-pager`, `--exec-path`, etc.)
469
- remain denied. `-C` gives **no protection** from a hostile repository's configuration:
508
+ remain denied in this reference allowlist, apart from the narrow index-only restore entry above. `-C` gives **no protection** from a hostile repository's configuration:
470
509
  fsmonitor, hooks, pager and diff/textconv helpers can still run. This is a syntax filter,
471
510
  not a repository sandbox.
472
511
 
@@ -496,7 +535,8 @@ evaluators, shells or writer verbs. `pushd` and `popd` are **not** allowlisted w
496
535
  protected reference exists. The restricted literal `cd` read-chain exemption still refuses
497
536
  `cd .claude && echo x > settings.json` without inferring write destinations. Shells refuse regardless of stdin descriptor, lone `-`, or
498
537
  `-c` option spelling. Unparsed complex syntax, including substitutions and heredocs, refuses
499
- once a protected reference exists; no shell bodies are interpreted.
538
+ once a protected reference exists. Separately, bounded static analysis of nested shell commands
539
+ tracks destructive scopes; it never executes those bodies or inspects archive contents.
500
540
 
501
541
  Even an allowlisted command may not redirect output to a protected or non-literal target
502
542
  (`$`, backticks or pathname patterns). Literal ordinary output is permitted, for example
@@ -513,14 +553,18 @@ matches and a bounded glob-intersection state space). Pattern and tree reference
513
553
  this deliberately over-conservative.
514
554
 
515
555
  This is **best-effort, not a sandbox**. Runtime names assembled from variables without a
516
- protected name appearing literally are out of scope, as are aliases/functions, external
517
- scripts, tool configuration/hooks and symlinks created during execution.
556
+ protected name appearing literally remain outside the reference fallback; known scoped mutators
557
+ refuse unresolved destinations. Aliases/functions, external scripts, tool configuration/hooks and
558
+ symlinks created during execution are not generally modeled. Inventory is a point-in-time check,
559
+ not a TOCTOU guarantee. Archive members and arbitrary copy payloads are not inspected; modeled
560
+ destinations and existing protected descendants do not establish payload safety.
518
561
  OS permissions/sandboxing remain the primary boundary. Do not use another
519
562
  route to work around a refusal.
520
563
 
521
564
  Generated-file headers do not trigger a block in either write guard. Regenerating proxies with
522
- `dotnet build`, staging, restoring, committing and other Git index/worktree operations, and direct
523
- writes (including copies, moves and redirections) are allowed for generated files. For durable
565
+ `dotnet build`, staging, restoring, committing and direct writes (including copies, moves and
566
+ redirections) are allowed for generated files only when no other protected category or destructive
567
+ scope applies. Generated status does not exempt whole-worktree rewrites. For durable
524
568
  proxy changes, change the C# source and rebuild rather than hand-editing generated output.
525
569
  Other protected classes still apply regardless of a generated header.
526
570
 
@@ -555,7 +599,7 @@ and Pi:
555
599
  `false` re-enables the manifest block in a Cratis repository; `true` allows manifest writes
556
600
  in any repository, for targets that do not themselves block (see above). Merge this property into the existing configuration. An absent
557
601
  or non-boolean setting uses the origin-based default (an unparsable file protects the whole repository; see below). This setting never permits `.env` writes.
558
- The protected basename list is unchanged; `package.json` is not part of this guard's manifest category.
602
+ The protected basename list includes `package.json`; it follows the same session/target manifest policy.
559
603
 
560
604
  This allowance is not authorization for unrelated upgrades: keep changes task-focused and
561
605
  call out version bumps in the PR description. Other repositories retain the rule requiring
@@ -17,6 +17,9 @@ parser_failed() {
17
17
  printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: parser failed; cannot check this tool call.' >&2
18
18
  exit 2
19
19
  }
20
+ archive_guidance() {
21
+ printf '%s\n' 'Extract outside the agent shell (or ask the user), then copy the specific files needed.' >&2
22
+ }
20
23
  cwd="" command_text="" parser_status=""
21
24
  {
22
25
  IFS= read -r -d '' cwd
@@ -624,6 +627,11 @@ function copy_targets(verb, i, w, j, ch, tail, value, targets, dirs, no_targe
624
627
  else destinations[++targets] = value
625
628
  break
626
629
  }
630
+ if (verb == "rsync" && ch == "f") {
631
+ value = substr(w, j + 1); if (value == "") { if (++i > argc) return 0; value = W[i] }
632
+ if (value == "" || globbed[i]) return 0
633
+ break
634
+ }
627
635
  if (verb == "install" && ch == "d") { dirs = 1; continue }
628
636
  if (index(flags, ch) == 0) return 0
629
637
  if (ch == "T") no_target = 1
@@ -643,6 +651,31 @@ function copy_targets(verb, i, w, j, ch, tail, value, targets, dirs, no_targe
643
651
  }
644
652
  return copy_effective_targets(verb, targets, operands, dirs, no_target, explicit_dirs)
645
653
  }
654
+ # Index-only restore is admitted narrowly, never a neighboring worktree/patch/file-input form.
655
+ function index_reset( i, skip, w) {
656
+ if (W[2] != "reset") return 0
657
+ for (i = 3; i <= argc; i++) {
658
+ w = W[i]
659
+ if (!skip && w == "--") { skip = 1; continue }
660
+ if (!skip && w ~ /^-/ && w !~ /^(--soft|--mixed|--no-refresh|-q|--quiet)$/) return 0
661
+ }
662
+ return 1
663
+ }
664
+ function index_restore( i, staged, paths, skip, w) {
665
+ i = 2
666
+ while (W[i] == "-C" && i + 2 <= argc && W[i + 1] != "" && !globbed[i + 1]) i += 2
667
+ if (W[i++] != "restore") return 0
668
+ for (; i <= argc; i++) {
669
+ w = W[i]
670
+ if (!skip && w == "--") { skip = 1; continue }
671
+ if (!skip && (w == "--staged" || w ~ /^-S+$/)) { staged = 1; continue }
672
+ if (!skip && (w == "-s" || w == "--source")) { if (++i > argc || globbed[i]) return 0; continue }
673
+ if (!skip && (w ~ /^--source=./ || w ~ /^-s./)) continue
674
+ if (!skip && w ~ /^-/) return 0
675
+ paths++
676
+ }
677
+ return staged && paths
678
+ }
646
679
  function allow_command( verb, first, i) {
647
680
  if (!argc) return
648
681
  if (++commands > 64) { fail(); return }
@@ -659,6 +692,7 @@ function allow_command( verb, first, i) {
659
692
  if (verb == "sed") { if (!print_only_sed()) cmd_failed = 1; return }
660
693
  if (verb == "find") { if (!find_allowed()) cmd_failed = 1; return }
661
694
  if (verb == "gh") { if (!gh_allowed()) cmd_failed = 1; return }
695
+ if (verb == "git" && (index_restore() || index_reset())) { changed_index = 1; return }
662
696
  if (verb == "git" && W[2] == "-C") {
663
697
  if (argc >= 4 && W[3] != "" && W[3] !~ /^-/ && !globbed[3] && W[4] ~ /^(add|commit)$/) {
664
698
  verb = verb " " W[4]; first = 5
@@ -819,8 +853,8 @@ BEGIN {
819
853
  exit (readonly(reduced) && !heredoc_writes) ? 0 : 1
820
854
  }
821
855
  AWK
822
- # This stage is independent of the readonly/reference grammar above. Prefix syntax is
823
- # never a reason to refuse a reader: only a discovered destructive operation has operands.
856
+ # This stage is independent of the readonly/reference grammar above. Scoped filesystem
857
+ # effects retain prefix uncertainty; archive tools require explicit uncontaminated read modes.
824
858
  IFS= read -r -d '' destructive_program <<'AWK' || true
825
859
  function base(word) { sub(/^.*\//, "", word); return word }
826
860
  function member(list, word) { return index(" " list " ", " " word " ") > 0 }
@@ -829,7 +863,7 @@ function shell(word) { return member("sh bash dash zsh ksh ash", base(word)) }
829
863
  # Command-head recognition is shared by dispatch and directory tracking. time retains
830
864
  # its option-aware wrapper handling below; grouping delimiters also split segments.
831
865
  function command_prefix(word) {
832
- return word ~ /^[A-Za-z_][A-Za-z0-9_]*=/ || member("then do else elif ! if while until { ( coproc", word)
866
+ return word ~ /^[A-Za-z_][A-Za-z0-9_]*[+]?=/ || word ~ /^(UNZIP|UNZIPOPT|TAR_OPTIONS|ZIPOPT)\[[^]]+\][+]?=/ || member("then do else elif ! if while until { ( coproc", word)
833
867
  }
834
868
  # Only these established execution prefixes expose another command position.
835
869
  function wrapper(word) {
@@ -842,7 +876,10 @@ function unclassified(text) {
842
876
  gsub(/["\047\\]/, "", text)
843
877
  if (text ~ /(^|[[:space:];|&()`\/])(rm|rmdir|unlink|shred|mv)([[:space:];|&()`]|$)/ ||
844
878
  (text ~ /(^|[[:space:];|&()`\/])git[[:space:]]/ && text ~ /(^|[[:space:]])clean([[:space:]]|$)/) ||
845
- (text ~ /(^|[[:space:];|&()`\/])find[[:space:]]/ && text ~ /(^|[[:space:]])-delete([[:space:]]|$)/)) emit("!")
879
+ (text ~ /(^|[[:space:];|&()`\/])find[[:space:]]/ && text ~ /(^|[[:space:]])-delete([[:space:]]|$)/) ||
880
+ (text ~ /(^|[[:space:];|&()`\/])git[[:space:]]/ && text ~ /(^|[[:space:]])(restore|checkout|switch|stash|reset|read-tree|checkout-index)([[:space:]]|$)/) ||
881
+ text ~ /(^|[[:space:];|&()`\/])(rsync|cp)([[:space:]]|$)/) emit("!")
882
+ if (text ~ /(^|[[:space:];|&()`\/])(unzip|bsdunzip|tar|bsdtar|gtar|ditto|pax|cpio|bsdcpio|7z|7za|7zz|7zr|jar|ar|unar|zip)([[:space:]]|$)/) emit("!archive")
846
883
  }
847
884
  function remaining(d, start, end, i, j, text) {
848
885
  for (i = start; i <= end; i++) {
@@ -885,7 +922,7 @@ function arithmetic_prefix(text, i, quoted) {
885
922
  # Quoted parentheses and parameter braces remain word data in the lexer.
886
923
  function simple_command(text, d, n, i, head) {
887
924
  head = base(W[d, 1])
888
- if (!destructive(head) && head != "git" && head != "find") return 0
925
+ if (!destructive(head) && !member("git find", head) && bulk_family(head) == "") return 0
889
926
  if (text ~ /`|\$\(/) return 0
890
927
  for (i = 1; i <= n; i++) {
891
928
  if (BC[d, i] || (K[d, i] != "word" && K[d, i] !~ /^(>|>>|>&|&>|&>>|<|<&)$/)) return 0
@@ -1199,7 +1236,11 @@ function env_words(text, slot, i, c, nextc, quote, word, active, n) {
1199
1236
  function executable(d, start, end, i, j, program, option, split_at, text, slot, count, first, expansions) {
1200
1237
  prefix_uncertain = 0; prefix_fed = 0; dispatch_end = end; i = start
1201
1238
  while (i <= end) {
1202
- if (command_prefix(W[d, i])) { i++; continue }
1239
+ if (command_prefix(W[d, i])) {
1240
+ if (archive_environment_name(W[d, i])) { archive_environment = 1; emit("!archive") }
1241
+ if (program == "env" && W[d, i] ~ /[$`*?\[{}]/ && (!Q[d, i] || DQ[d, i])) prefix_uncertain = 1
1242
+ i++; continue
1243
+ }
1203
1244
  program = base(W[d, i])
1204
1245
  if (!wrapper(program)) return redirection(d, i) ? 0 : i
1205
1246
  if (member("chroot nsenter", program)) prefix_uncertain = 1
@@ -1255,8 +1296,414 @@ function removal(d, verb, end, cwd, uncertain, findpaths, i, w, count, option
1255
1296
  sources++
1256
1297
  }
1257
1298
  }
1258
- function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j, w, subcommand, dry, paths, skip, alias, name, call, script, option) {
1299
+ # A shared exact grammar runs before effect parsing, including nonmutating/dry-run exits.
1300
+ # Unknown options are never interpreted as abbreviations, negations or harmless data.
1301
+ function option_schema(family, flags, values, long_flags, long_values, i, n, words) {
1302
+ for (i = 1; i <= length(flags); i++) OPT[family, "-" substr(flags, i, 1)] = "flag"
1303
+ for (i = 1; i <= length(values); i++) OPT[family, "-" substr(values, i, 1)] = "value"
1304
+ n = split(long_flags, words, " "); for (i = 1; i <= n; i++) OPT[family, "--" words[i]] = "flag"
1305
+ n = split(long_values, words, " "); for (i = 1; i <= n; i++) OPT[family, "--" words[i]] = "value"
1306
+ }
1307
+ function bulk_family(word) {
1308
+ if (member("tar bsdtar gtar", word)) return "tar"
1309
+ if (member("7z 7za 7zz 7zr", word)) return "7z"
1310
+ if (member("unzip bsdunzip", word)) return "unzip"
1311
+ if (member("cpio bsdcpio", word)) return "cpio"
1312
+ if (member("rsync cp ditto pax jar ar unar zip", word)) return word
1313
+ return ""
1314
+ }
1315
+ function option_grammars() {
1316
+ option_schema("tar", "xctruAdOzjJavpkhmPS", "fC", "extract get to-stdout create list append update concatenate diff compare verbose gzip gunzip bzip2 xz zstd overwrite keep-old-files no-same-owner same-owner no-same-permissions same-permissions", "file directory strip-components")
1317
+ option_schema("unzip", "lptZvoqnujCXLKafDUV", "dP", "", "")
1318
+ option_schema("cp", "rRaTpfvniuLPHdl", "t", "archive recursive no-target-directory force verbose no-clobber update", "target-directory")
1319
+ option_schema("rsync", "rapvniuLPHdzctgoDlq", "f", "archive recursive force verbose update compress times perms ignore-existing existing dry-run delete delete-before delete-during delete-delay delete-after delete-excluded", "")
1320
+ option_schema("ditto", "xkczvV", "", "rsrc norsrc extattr noextattr acl noacl qtn noqtn keepParent sequesterRsrc", "")
1321
+ option_schema("pax", "rwv", "f", "", "")
1322
+ option_schema("cpio", "idmvtop", "FDH", "extract create list pass-through make-directories preserve-modification-time no-absolute-filenames verbose", "file directory format")
1323
+ option_schema("7z", "y", "opt", "", "")
1324
+ OPT["7z", "-so"] = OPT["7z", "-bd"] = "flag"
1325
+ option_schema("zip", "rqjv0123456789", "x", "quiet recurse-paths junk-paths verbose", "exclude out")
1326
+ option_schema("jar", "xctuv", "fC", "extract create list update verbose", "file dir")
1327
+ option_schema("ar", "xtrqdmpsvfP", "", "", "output")
1328
+ option_schema("unar", "qfdD", "o", "quiet force-overwrite force-directory no-directory", "output-directory")
1329
+ # Creation has a separate, deliberately small non-executing/non-deleting grammar.
1330
+ option_schema("creation:tar", "cruAvzjJ", "fCT", "create append update concatenate gzip bzip2 xz zstd verbose", "file directory exclude files-from format")
1331
+ option_schema("creation:zip", "rqjv0123456789", "x", "quiet recurse-paths junk-paths verbose", "exclude out")
1332
+ option_schema("creation:7z", "", "t", "", "")
1333
+ option_schema("creation:jar", "cuvM", "fC", "create update verbose no-manifest", "file")
1334
+ option_schema("creation:ar", "rqcsdmvu", "", "", "")
1335
+ option_schema("creation:cpio", "ov", "FH", "create verbose", "file format")
1336
+ option_schema("creation:pax", "wv", "fx", "", "")
1337
+ option_schema("restore", "SWq", "s", "staged worktree ours theirs ignore-unmerged ignore-skip-worktree-bits overlay no-overlay quiet", "source")
1338
+ option_schema("checkout", "fmqd", "bB", "force merge quiet detach track no-track guess no-guess recurse-submodules ours theirs", "orphan")
1339
+ option_schema("switch", "fmqd", "cC", "force discard-changes merge quiet detach track no-track guess no-guess recurse-submodules", "create force-create")
1340
+ option_schema("stash", "kuapq", "m", "keep-index no-keep-index include-untracked all quiet patch stat index", "message")
1341
+ option_schema("reset", "q", "", "soft mixed hard merge keep no-refresh quiet pathspec-file-nul", "pathspec-from-file")
1342
+ option_schema("clean", "fdxXqn", "e", "force quiet dry-run", "exclude")
1343
+ option_schema("read-tree", "uminv", "", "reset merge dry-run verbose no-sparse-checkout", "prefix index-output")
1344
+ option_schema("checkout-index", "afqunz", "", "all force quiet index no-create stdin temp", "prefix")
1345
+ }
1346
+ function option_value(d, i, end) {
1347
+ return i <= end && K[d, i] == "word" && W[d, i] != "" && (Q[d, i] || W[d, i] !~ /[$`*?\[{}]/)
1348
+ }
1349
+ # Return the last consumed word, or zero. Option values are data, never another option.
1350
+ function option_end(d, i, end, family, old, schema, w, key, kind, j, last) {
1351
+ if (schema == "") schema = family
1352
+ w = W[d, i]; last = i
1353
+ if (w ~ /^--/) {
1354
+ key = w; sub(/=.*/, "", key); kind = OPT[schema, key]
1355
+ if (kind == "flag") return w == key ? i : 0
1356
+ if (kind != "value") return 0
1357
+ if (w != key) return length(w) > length(key) + 1 ? i : 0
1358
+ return option_value(d, i + 1, end) ? i + 1 : 0
1359
+ }
1360
+ if (family == "7z") {
1361
+ if (schema == "creation:7z" && w ~ /^-mx=?[0-9]$/) return i
1362
+ if (OPT[schema, w] == "flag") return i
1363
+ key = substr(w, 1, 2)
1364
+ if (OPT[schema, key] != "value") return 0
1365
+ if (length(w) > 2) return i
1366
+ return option_value(d, i + 1, end) ? i + 1 : 0
1367
+ }
1368
+ for (j = old ? 1 : 2; j <= length(w); j++) {
1369
+ kind = OPT[schema, "-" substr(w, j, 1)]
1370
+ if (kind == "") return 0
1371
+ if (kind != "value") continue
1372
+ if (!old && j < length(w)) return i
1373
+ if (!option_value(d, ++last, end)) return 0
1374
+ if (!old) break
1375
+ }
1376
+ return last
1377
+ }
1378
+ function known_options(d, start, end, family, cwd, uncertain, creation, i, w, old, last, schema) {
1379
+ schema = creation ? "creation:" family : family
1380
+ for (i = start; i <= end; i++) {
1381
+ w = W[d, i]
1382
+ if (redirection(d, i)) break
1383
+ if (w == "--") return !member("unzip jar ar", family)
1384
+ old = member("tar jar ar", family) && i == start && w ~ /^[a-zA-Z]+$/
1385
+ if (w !~ /^-/ && !old) {
1386
+ if (w ~ /[$`]/ && (!Q[d, i] || DQ[d, i]) && (!DQ[d, i] || resolved(w, Q[d, i], cwd, uncertain, DQ[d, i]) == "!")) return 0
1387
+ continue
1388
+ }
1389
+ if (!Q[d, i] && w ~ /[$`*?\[{}]/) return 0
1390
+ last = option_end(d, i, end, family, old, schema)
1391
+ if (!last) return 0
1392
+ i = last
1393
+ }
1394
+ return 1
1395
+ }
1396
+ # Archive payloads and option environments are opaque. Read modes and safe creation are explicit.
1397
+ function archive_environment_name(word) { return word ~ /^(UNZIP|UNZIPOPT|TAR_OPTIONS|ZIPOPT)($|[+]?=|\[)/ }
1398
+ function archive_exports(d, head, end, i, w) {
1399
+ for (i = head + 1; i <= end; i++) {
1400
+ w = W[d, i]
1401
+ if (redirection(d, i)) break
1402
+ if (archive_environment_name(w)) { archive_environment = 1; emit("!archive") }
1403
+ else if (w !~ /^[-+]/ && w !~ /^[A-Za-z_][A-Za-z0-9_]*([+]?=|$)/) {
1404
+ archive_environment = 1
1405
+ if (archive_seen) emit("!archive")
1406
+ }
1407
+ }
1408
+ }
1409
+ function archive_mode_flag(family, flag) {
1410
+ if (family == "tar") {
1411
+ if (member("-t --list", flag)) return "list"
1412
+ if (member("-x --extract --get", flag)) return "extract"
1413
+ if (member("-O --to-stdout", flag)) return "stdout"
1414
+ if (member("-c -r -u -A --create --append --update --concatenate", flag)) return "create"
1415
+ if (member("-d --diff --compare", flag)) return "other"
1416
+ } else if (family == "unzip") {
1417
+ if (member("-l -t -v -Z", flag)) return "list"
1418
+ if (flag == "-p") return "stdout"
1419
+ return "other"
1420
+ } else if (family == "jar") {
1421
+ if (member("-t --list", flag)) return "list"
1422
+ if (member("-c -u --create --update", flag)) return "create"
1423
+ if (member("-x --extract", flag)) return "extract"
1424
+ } else if (family == "ar") {
1425
+ if (flag == "-t") return "list"
1426
+ if (member("-r -q -d -m -s", flag)) return "create"
1427
+ if (flag == "-x") return "extract"
1428
+ if (member("-p -M", flag)) return "other"
1429
+ } else if (family == "cpio") {
1430
+ if (member("-t --list", flag)) return "list"
1431
+ if (member("-o --create", flag)) return "create"
1432
+ if (member("-i -p --extract --pass-through", flag)) return "extract"
1433
+ } else if (family == "pax") {
1434
+ if (flag == "-w") return "create"
1435
+ if (flag == "-r") return "extract"
1436
+ }
1437
+ return ""
1438
+ }
1439
+ # 0 = refused/unknown, 1 = explicit read, 2 = archive creation/update.
1440
+ function archive_mode(d, start, end, family, i, j, w, flag, kind, old, last, mode, options, terminator, state, schema) {
1441
+ if (family == "zip") return 2
1442
+ if (!member("tar unzip jar ar cpio pax 7z", family)) return 0
1443
+ options = 1
1444
+ for (i = start; i <= end; i++) {
1445
+ w = W[d, i]
1446
+ if (redirection(d, i)) break
1447
+ if (w == "--") { options = 0; terminator = 1; continue }
1448
+ old = member("tar jar ar", family) && i == start && w ~ /^[a-zA-Z]+$/
1449
+ if (!options || (w !~ /^-/ && !old)) {
1450
+ if (family == "7z" && mode == "") mode = w
1451
+ continue
1452
+ }
1453
+ schema = family; last = option_end(d, i, end, family, old)
1454
+ if (!last) { schema = "creation:" family; last = option_end(d, i, end, family, old, schema) }
1455
+ if (!last) last = i
1456
+ if (w ~ /^--/) {
1457
+ flag = w; sub(/=.*/, "", flag)
1458
+ kind = archive_mode_flag(family, flag); if (kind != "") state[kind] = 1
1459
+ } else if (family != "7z") {
1460
+ for (j = old ? 1 : 2; j <= length(w); j++) {
1461
+ flag = "-" substr(w, j, 1)
1462
+ kind = archive_mode_flag(family, flag); if (kind != "") state[kind] = 1
1463
+ if (!old && OPT[schema, flag] == "value") break
1464
+ }
1465
+ }
1466
+ i = last
1467
+ }
1468
+ if (family == "7z") {
1469
+ if (member("a u d", mode) && mode != "") return 2
1470
+ return member("l t", mode) && mode != ""
1471
+ }
1472
+ if (state["create"] && !state["extract"] && !state["list"] && !state["stdout"] && !state["other"]) return 2
1473
+ if (state["create"] || state["other"]) return family == "unzip" && state["stdout"]
1474
+ if (family == "unzip") return state["stdout"] || state["list"]
1475
+ if (family == "tar") return (state["list"] && !state["extract"]) || (state["extract"] && state["stdout"] && !state["list"] && !terminator)
1476
+ return state["list"] && !state["extract"]
1477
+ }
1478
+ function archive_command(d, verb, end, cwd, uncertain, fed, family, i, mode) {
1479
+ archive_seen = 1
1480
+ if (uncertain || fed || archive_environment || ("UNZIP" in ENVIRON) || ("UNZIPOPT" in ENVIRON) || ("TAR_OPTIONS" in ENVIRON) || ("ZIPOPT" in ENVIRON)) { emit("!archive"); return }
1481
+ for (i = verb + 1; i <= end; i++) {
1482
+ if (redirection(d, i)) break
1483
+ if (W[d, i] ~ /^@/) { emit("!archive"); return }
1484
+ }
1485
+ mode = archive_mode(d, verb + 1, end, family)
1486
+ if (mode == 2) {
1487
+ if (!known_options(d, verb + 1, end, family, cwd, uncertain, 1)) emit("!archive")
1488
+ else archive_creation(d, verb, end, cwd, uncertain, family)
1489
+ } else if (mode != 1 || !known_options(d, verb + 1, end, family, cwd, uncertain)) emit("!archive")
1490
+ }
1491
+ function creation_output_option(family, flag) {
1492
+ return (member("tar jar pax", family) && member("-f --file", flag)) ||
1493
+ (family == "cpio" && member("-F --file", flag)) ||
1494
+ (family == "zip" && flag == "--out")
1495
+ }
1496
+ function archive_creation(d, verb, end, cwd, uncertain, family, i, j, w, flag, value, next_word, old, options, output, output_q, output_dq, output_explicit, positional, schema) {
1497
+ options = 1; schema = "creation:" family
1498
+ for (i = verb + 1; i <= end; i++) {
1499
+ w = W[d, i]
1500
+ if (redirection(d, i)) break
1501
+ if (w == "--" && options) { options = 0; continue }
1502
+ if (w ~ /[$`]/ && (!Q[d, i] || DQ[d, i])) { emit("!"); return }
1503
+ old = member("tar jar ar", family) && i == verb + 1 && w ~ /^[a-zA-Z]+$/
1504
+ if (options && ((w ~ /^-/ && w != "-") || old)) {
1505
+ if (family == "7z") {
1506
+ next_word = option_end(d, i, end, family, 0, schema); if (next_word) i = next_word
1507
+ continue
1508
+ }
1509
+ if (w ~ /^--/) {
1510
+ flag = w; sub(/=.*/, "", flag)
1511
+ if (OPT[schema, flag] == "value") {
1512
+ value = substr(w, length(flag) + 2)
1513
+ if (w == flag) value = W[d, ++i]
1514
+ if (value == "") { emit("!"); return }
1515
+ if (creation_output_option(family, flag)) { output = value; output_q = Q[d, i]; output_dq = DQ[d, i]; output_explicit = 1 }
1516
+ }
1517
+ continue
1518
+ }
1519
+ next_word = i
1520
+ for (j = old ? 1 : 2; j <= length(w); j++) {
1521
+ flag = "-" substr(w, j, 1)
1522
+ if (OPT[schema, flag] != "value") continue
1523
+ value = old ? "" : substr(w, j + 1)
1524
+ if (value == "") value = W[d, ++next_word]
1525
+ if (value == "") { emit("!"); return }
1526
+ if (creation_output_option(family, flag)) { output = value; output_q = Q[d, next_word]; output_dq = DQ[d, next_word]; output_explicit = 1 }
1527
+ if (!old) break
1528
+ }
1529
+ i = next_word; continue
1530
+ }
1531
+ if (family == "7z" && !positional) { positional = 1; continue }
1532
+ if (member("zip ar 7z", family) && positional < 2) {
1533
+ positional = 2
1534
+ if (!output_explicit) { output = w; output_q = Q[d, i]; output_dq = DQ[d, i] }
1535
+ }
1536
+ }
1537
+ if (output == "-") return
1538
+ if (output != "") operand(output, output_q, cwd, uncertain, output_dq)
1539
+ else if (member("ar 7z", family)) emit("!")
1540
+ }
1541
+ # cp writes source basenames to an existing/explicit directory, but source/. writes its contents.
1542
+ function copy_effect(d, verb, end, cwd, uncertain, i, j, w, ch, value, count, target, no_target, recursive, dry, bad, options, source, suffix, kind, explicit_target, sync_delete, remote_target) {
1543
+ options = 1
1544
+ for (i = verb + 1; i <= end; i++) {
1545
+ w = W[d, i]
1546
+ if (redirection(d, i)) break
1547
+ if (options && w == "--") { options = 0; continue }
1548
+ if (options && w ~ /^--/) {
1549
+ if (w ~ /^--target-directory(=|$)/ && base(W[d, verb]) == "cp") {
1550
+ value = substr(w, 20); if (w == "--target-directory") value = W[d, ++i]
1551
+ target = resolved(value, Q[d, i], cwd, uncertain, DQ[d, i]); explicit_target = 1
1552
+ } else if (w == "--no-target-directory") no_target = 1
1553
+ else if (w == "--dry-run") dry = 1
1554
+ else if (member("--archive --recursive", w)) recursive = 1
1555
+ else if (w ~ /^--delete(-before|-during|-delay|-after|-excluded)?$/) sync_delete = 1
1556
+ else if (!member("--force --verbose --no-clobber --update --compress --times --perms --ignore-existing --existing", w)) bad = 1
1557
+ continue
1558
+ }
1559
+ if (options && w ~ /^-/) {
1560
+ for (j = 2; j <= length(w); j++) {
1561
+ ch = substr(w, j, 1)
1562
+ if (base(W[d, verb]) == "rsync" && ch == "f") {
1563
+ value = substr(w, j + 1); if (value == "") value = W[d, ++i]
1564
+ if (value == "") bad = 1
1565
+ break
1566
+ }
1567
+ if (base(W[d, verb]) == "cp" && ch == "t") {
1568
+ value = substr(w, j + 1); if (value == "") value = W[d, ++i]
1569
+ target = resolved(value, Q[d, i], cwd, uncertain, DQ[d, i]); explicit_target = 1; break
1570
+ }
1571
+ if (ch ~ /^[rRa]$/) recursive = 1
1572
+ else if (ch == "T") no_target = 1
1573
+ else if (ch == "n" && base(W[d, verb]) == "rsync") dry = 1
1574
+ else if (ch !~ /^[pfvniuLPHdzctgoDlq]$/) bad = 1
1575
+ }
1576
+ continue
1577
+ }
1578
+ CP[d, ++count] = i
1579
+ }
1580
+ if (dry && base(W[d, verb]) == "rsync") return
1581
+ if (bad || uncertain || !count || target == "!") { emit("!"); return }
1582
+ if (!explicit_target) {
1583
+ i = CP[d, count--]; target = resolved(W[d, i], Q[d, i], cwd, uncertain, DQ[d, i])
1584
+ remote_target = W[d, i] ~ /^([^\/:]+:|rsync:\/\/)/
1585
+ }
1586
+ if (target == "!" || !count || (no_target && (explicit_target || count > 1))) { emit("!"); return }
1587
+ # Remote destinations are not local scopes; the existing reference fallback still applies.
1588
+ if (base(W[d, verb]) == "rsync" && remote_target) return
1589
+ if (base(W[d, verb]) == "rsync" && sync_delete) {
1590
+ emit(target); return
1591
+ }
1592
+ if (!recursive && base(W[d, verb]) == "cp") return
1593
+ kind = directory_kind(target)
1594
+ if (kind == "!") { emit("!"); return }
1595
+ for (j = 1; j <= count; j++) {
1596
+ i = CP[d, j]; source = W[d, i]; sub(/\/+$/, "", source)
1597
+ suffix = base(source)
1598
+ if (suffix == "." || suffix == ".." || suffix == "" || source ~ /[$`*?\[{}]/ || (base(W[d, verb]) == "rsync" && W[d, i] ~ /[\/:]$/)) emit(target)
1599
+ else if (!no_target && (explicit_target || kind == "directory" || count > 1)) emit(target "/" suffix)
1600
+ else emit(target)
1601
+ }
1602
+ }
1603
+ function directory_kind(path, cmd, result) {
1604
+ cmd = "bash -c " quote_path("if [ -d \"$1\" ]; then echo directory; elif [ -e \"$1\" ] || [ ! -L \"$1\" ]; then echo other; else exit 2; fi") " guard-directory " quote_path(path)
1605
+ if ((cmd | getline result) != 1) result = "!"
1606
+ if (close(cmd) != 0) result = "!"
1607
+ return result
1608
+ }
1609
+ function git_bulk(d, command, start, end, cwd, uncertain, fed, i, j, w, prefix, write, dry, root) {
1610
+ for (i = start; i <= end; i++) {
1611
+ w = W[d, i]
1612
+ if (redirection(d, i)) break
1613
+ if (w == "--") { if (command == "checkout-index" && i < end) write = 1; break }
1614
+ if (w == "--prefix") prefix = W[d, ++i]
1615
+ else if (w ~ /^--prefix=/) prefix = substr(w, 10)
1616
+ else if (w == "--index-output") i++
1617
+ else if (w == "--stdin" || w == "--temp") { emit("!"); return }
1618
+ else if (w == "--dry-run" && command == "read-tree") dry = 1
1619
+ else if (member("--all --force", w) && command == "checkout-index") write = 1
1620
+ else if (w ~ /^-[^-]/) {
1621
+ for (j = 2; j <= length(w); j++) {
1622
+ if (command == "read-tree" && substr(w, j, 1) == "u") write = 1
1623
+ else if (command == "read-tree" && substr(w, j, 1) == "n") dry = 1
1624
+ else if (command == "checkout-index" && substr(w, j, 1) ~ /[af]/) write = 1
1625
+ }
1626
+ } else if (command == "checkout-index" && w !~ /^-/) write = 1
1627
+ }
1628
+ if (!write || dry) return
1629
+ if (uncertain || fed) { emit("!"); return }
1630
+ if (command == "checkout-index" && (prefix == "" || substr(prefix, length(prefix), 1) != "/")) { emit("!"); return }
1631
+ root = command == "read-tree" ? git_root(cwd) : cwd
1632
+ emit(prefix == "" ? root : resolved(prefix, 1, root, root == "!"))
1633
+ }
1634
+ # Locate the selected worktree with metadata only. Overrides are refused for content effects.
1635
+ function git_root(cwd, cmd, root) {
1636
+ cmd = "bash -c " quote_path("cd -P -- \"$1\" || exit 2; while [ ! -e \"$PWD/.git\" ]; do [ \"$PWD\" != / ] || exit 2; cd .. || exit 2; done; pwd -P") " guard-git-root " quote_path(cwd) " 2>/dev/null"
1637
+ if ((cmd | getline root) != 1) root = "!"
1638
+ if (close(cmd) != 0) root = "!"
1639
+ return root
1640
+ }
1641
+ function git_path(d, i, cwd, uncertain, findpaths, w) {
1642
+ w = W[d, i]
1643
+ if (w ~ /^:/) emit(git_root(cwd))
1644
+ else if (w == "{}" && findpaths != "") emit(findpaths)
1645
+ else operand(w, Q[d, i], cwd, uncertain, DQ[d, i])
1646
+ }
1647
+ function git_rewrite(d, command, start, end, cwd, uncertain, findpaths, fed, i, j, w, ch, staged, worktree, whole, paths, skip, bad, create, position, action) {
1648
+ if (command == "stash") {
1649
+ action = W[d, start]
1650
+ if (member("list show drop clear", action)) return
1651
+ if (action == "" || member("apply pop branch save", action)) whole = 1
1652
+ else if (action != "push" && action !~ /^-/) { emit("!"); return }
1653
+ if (action == "push") start++
1654
+ }
1655
+ if (command == "reset") {
1656
+ for (i = start; i <= end; i++) {
1657
+ if (redirection(d, i)) break
1658
+ if (member("--hard --merge --keep", W[d, i])) whole = 1
1659
+ else if (W[d, i] ~ /^--(pathspec-from-file|pathspec-file-nul)/ || W[d, i] ~ /[$`]/) bad = 1
1660
+ }
1661
+ if (!whole && !bad) return
1662
+ } else for (i = start; i <= end; i++) {
1663
+ w = W[d, i]
1664
+ if (redirection(d, i)) break
1665
+ if (!skip && w == "--") { skip = 1; continue }
1666
+ if (!skip && w ~ /^-/) {
1667
+ if (command == "restore") {
1668
+ if (w == "--staged") { staged = 1; continue }
1669
+ if (w == "--worktree") { worktree = 1; continue }
1670
+ if (w == "--source" || w == "-s") { if (++i > end || W[d, i] ~ /[$`]/) bad = 1; continue }
1671
+ if (w ~ /^--source=./ || w ~ /^-s./) continue
1672
+ if (w ~ /^-[SW]+$/) {
1673
+ for (j = 2; j <= length(w); j++) { ch = substr(w, j, 1); if (ch == "S") staged = 1; else worktree = 1 }
1674
+ continue
1675
+ }
1676
+ if (member("--ours --theirs --ignore-unmerged --ignore-skip-worktree-bits --overlay --no-overlay -q --quiet", w)) continue
1677
+ } else if (command == "checkout" || command == "switch") {
1678
+ if (member("-f --force --discard-changes -m --merge", w)) { whole = 1; continue }
1679
+ if (member("-b -B --orphan -c -C --create --force-create", w)) { create = 1; if (++i > end) bad = 1; continue }
1680
+ if (member("-q --quiet --detach -d --track --no-track --guess --no-guess --recurse-submodules --ours --theirs", w)) continue
1681
+ } else if (command == "stash") {
1682
+ if (w == "-m" || w == "--message") { if (++i > end) bad = 1; continue }
1683
+ if (w ~ /^--message=/ || w ~ /^-m./ || member("-k --keep-index --no-keep-index -u --include-untracked -a --all -q --quiet", w)) continue
1684
+ }
1685
+ bad = 1; continue
1686
+ }
1687
+ if (w ~ /[$`]/) bad = 1
1688
+ if (w ~ /^:/) { emit(git_root(cwd)); return }
1689
+ RP[++paths] = i
1690
+ # checkout REV -- paths: revision is not a path, and branch data is never a subcommand.
1691
+ if (!skip) position++
1692
+ }
1693
+ if (command == "restore" && staged && !worktree && !bad) return
1694
+ if (command == "switch" && !whole && !bad) return
1695
+ if (command == "checkout" && create && !whole && !bad) return
1696
+ if (command == "stash" && !paths) whole = 1
1697
+ if (bad || uncertain || fed) { emit("!"); return }
1698
+ if (whole) { emit(git_root(cwd)); return }
1699
+ if (command == "checkout" && skip && paths > 1 && position > 0) {
1700
+ for (i = 2; i <= paths; i++) git_path(d, RP[i], cwd, uncertain, findpaths)
1701
+ } else for (i = 1; i <= paths; i++) git_path(d, RP[i], cwd, uncertain, findpaths)
1702
+ if (!paths) emit("!")
1703
+ }
1704
+ function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j, w, subcommand, dry, paths, skip, alias, name, call, script, option, rewrite_context) {
1259
1705
  subcommand = 0; call = ++git_call
1706
+ uncertain = uncertain || git_context_unknown || ("GIT_WORK_TREE" in ENVIRON) || ("GIT_DIR" in ENVIRON) || ("GIT_COMMON_DIR" in ENVIRON)
1260
1707
  for (i = verb + 1; i <= end; i++) {
1261
1708
  w = W[d, i]
1262
1709
  if (w == "-C") {
@@ -1267,11 +1714,16 @@ function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j,
1267
1714
  if (alias ~ /^alias\.[^=]+=/) {
1268
1715
  name = alias; sub(/^alias\./, "", name); sub(/=.*/, "", name)
1269
1716
  sub(/^[^=]*=/, "", alias); A[call, name] = alias
1270
- }
1717
+ } else if (tolower(alias) ~ /^(core\.worktree|core\.bare|include\.|includeif\.)/) uncertain = 1
1271
1718
  } else if (w ~ /[$`]/) { emit("!"); return }
1272
1719
  # Git 2.50.1 git.c handle_options(), plus legacy --super-prefix.
1273
- else if (member("--git-dir --work-tree --namespace --config-env --attr-source --super-prefix --shallow-file", w)) i++
1274
- else if (w ~ /^--(git-dir|work-tree|namespace|config-env|attr-source|super-prefix|exec-path)=/) continue
1720
+ else if (w == "--work-tree") { if (W[d, ++i] != ".") uncertain = 1 }
1721
+ else if (w == "--work-tree=.") continue
1722
+ else if (w == "--git-dir") { rewrite_context = 1; if (W[d, ++i] != ".git") uncertain = 1 }
1723
+ else if (w == "--git-dir=.git") { rewrite_context = 1; continue }
1724
+ else if (w ~ /^--(git-dir|work-tree)=/ || w == "--bare") { uncertain = 1; continue }
1725
+ else if (member("--namespace --config-env --attr-source --super-prefix --shallow-file", w)) { rewrite_context = 1; i++ }
1726
+ else if (w ~ /^--(namespace|config-env|attr-source|super-prefix|exec-path)=/) { rewrite_context = 1; continue }
1275
1727
  else if (member("-h --help -v --version --html-path --man-path --info-path --exec-path", w) || w ~ /^--list-cmds=/) return
1276
1728
  else if (member("-p --paginate -P --no-pager --no-replace-objects --no-lazy-fetch --no-optional-locks --no-advice --bare --literal-pathspecs --no-literal-pathspecs --glob-pathspecs --noglob-pathspecs --icase-pathspecs", w)) continue
1277
1729
  else if (w ~ /^-/) { unclassified("git " remaining(d, i, end)); return }
@@ -1283,10 +1735,19 @@ function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j,
1283
1735
  if (substr(script, 1, 1) == "!") script = substr(script, 2)
1284
1736
  else script = "git " script
1285
1737
  for (i = subcommand + 1; i <= end; i++) script = script " " quote_path(W[d, i])
1286
- parse(script, cwd, uncertain, depth + 1, fed)
1738
+ parse(script, cwd, uncertain || rewrite_context, depth + 1, fed)
1287
1739
  return
1288
1740
  }
1289
1741
  # Once a subcommand is established, later words are its data, never another subcommand.
1742
+ if (member("restore checkout switch stash reset clean read-tree checkout-index", W[d, subcommand]) && !known_options(d, subcommand + 1, end, W[d, subcommand], cwd, uncertain)) { emit("!"); return }
1743
+ if (member("read-tree checkout-index", W[d, subcommand])) {
1744
+ git_bulk(d, W[d, subcommand], subcommand + 1, end, cwd, uncertain || rewrite_context, fed)
1745
+ return
1746
+ }
1747
+ if (member("restore checkout switch stash reset", W[d, subcommand])) {
1748
+ git_rewrite(d, W[d, subcommand], subcommand + 1, end, cwd, uncertain || rewrite_context, findpaths, fed)
1749
+ return
1750
+ }
1290
1751
  if (W[d, subcommand] != "clean") return
1291
1752
  dry = 0; paths = 0; skip = 0
1292
1753
  for (i = subcommand + 1; i <= end; i++) {
@@ -1314,10 +1775,7 @@ function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j,
1314
1775
  if (fed) { emit("!"); return }
1315
1776
  for (j = 1; j <= paths; j++) {
1316
1777
  i = GP[call, j]; w = W[d, i]
1317
- if (w ~ /^:\// || w ~ /^:\(top/) emit(ENVIRON["GSW_ROOT"])
1318
- else if (w ~ /^:\(/) emit("!")
1319
- else if (w == "{}" && findpaths != "") emit(findpaths)
1320
- else operand(w, Q[d, i], cwd, uncertain, DQ[d, i])
1778
+ git_path(d, i, cwd, uncertain, findpaths)
1321
1779
  }
1322
1780
  if (!paths) operand(".", 0, cwd, uncertain)
1323
1781
  }
@@ -1479,8 +1937,15 @@ function segment(d, start, end, cwd, uncertain, depth, findpaths, pipe, fed, out
1479
1937
  return ""
1480
1938
  }
1481
1939
  w = base(W[d, head])
1940
+ if (member("export declare typeset readonly local", w)) archive_exports(d, head, end)
1482
1941
  if (w == "git") git_clean(d, head, end, cwd, context, findpaths, depth, fed)
1483
1942
  else if (w == "find") find_command(d, head, end, cwd, context, depth + 1, fed)
1943
+ else if (bulk_family(w) != "") {
1944
+ if (w == "cp" || w == "rsync") {
1945
+ if (fed || !known_options(d, head + 1, end, w, cwd, context)) emit("!")
1946
+ else copy_effect(d, head, end, cwd, context)
1947
+ } else archive_command(d, head, end, cwd, context, fed, bulk_family(w))
1948
+ }
1484
1949
  else if (destructive(w)) {
1485
1950
  # xargs always adds/replaces operands from stdin, even with safe literal operands.
1486
1951
  if (fed) emit("!")
@@ -1498,6 +1963,7 @@ function parse(text, cwd, uncertain, depth, fed, n, i, start, kind, level, he
1498
1963
  # A depth slot may be reused by several script words.
1499
1964
  for (i = 1; i <= N[depth]; i++) { delete W[depth, i]; delete Q[depth, i]; delete DQ[depth, i]; delete CT[depth, i]; delete K[depth, i]; delete H[depth, i]; delete T[depth, i]; delete F[depth, i]; BC[depth, i] = 0 }
1500
1965
  n = lex(text, depth); N[depth] = n; start = 1; level = 0
1966
+ if (text ~ /(^|[[:space:]])GIT_[A-Z_]+=/) git_context_unknown = 1
1501
1967
  if (depth == 0) simple_tool = simple_command(text, depth, n)
1502
1968
  for (i = 1; i <= n + 1; i++) {
1503
1969
  kind = K[depth, i]
@@ -1531,7 +1997,7 @@ function parse(text, cwd, uncertain, depth, fed, n, i, start, kind, level, he
1531
1997
  }
1532
1998
  }
1533
1999
  function quote_path(path, q) { q = "\047"; gsub(/\047/, "\047\\\047\047", path); return q path q }
1534
- BEGIN { parse(ENVIRON["GSW_COMMAND"], ENVIRON["GSW_CWD"], 0, 0) }
2000
+ BEGIN { option_grammars(); parse(ENVIRON["GSW_COMMAND"], ENVIRON["GSW_CWD"], 0, 0) }
1535
2001
  AWK
1536
2002
  classifier="$script_directory/cratis-guard-writes.sh"
1537
2003
  repository_root="$cwd"
@@ -1544,6 +2010,11 @@ destructive_text="$(GSW_COMMAND="$command_text" GSW_CWD="$cwd" GSW_ROOT="$reposi
1544
2010
  if [ -n "$destructive_text" ]; then
1545
2011
  destructive_candidates=()
1546
2012
  while IFS= read -r candidate; do
2013
+ if [ "$candidate" = '!archive' ]; then
2014
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: archive extraction cannot be checked by the guard.' >&2
2015
+ archive_guidance
2016
+ exit 2
2017
+ fi
1547
2018
  if [ "$candidate" = '!' ]; then
1548
2019
  printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: a destructive command targets an operand that could not be resolved; use explicit paths or report the intended change.' >&2
1549
2020
  exit 2
@@ -0,0 +1,107 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import * as filesystem from 'node:fs';
5
+ import { join, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { TextDecoder } from 'node:util';
8
+
9
+ const entryDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
10
+
11
+ function nameMatcher(patterns) {
12
+ const expressions = patterns.map(pattern => new RegExp(`^${pattern.split('*').map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`, 'is'));
13
+ return name => expressions.some(expression => expression.test(name));
14
+ }
15
+
16
+ function unchanged(before, after) {
17
+ return ['dev', 'ino', 'mtimeMs', 'ctimeMs'].every(field => before[field] === after[field]);
18
+ }
19
+
20
+ function unlinkedDirectory(metadata) {
21
+ return metadata.isDirectory() && !metadata.isSymbolicLink();
22
+ }
23
+
24
+ function existingDirectory(path, fs) {
25
+ try { return fs.statSync(path).isDirectory(); }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return false;
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ function inventoryBudget(now, maxEntries, maxMs) {
33
+ const started = now();
34
+ let entries = 0;
35
+ return (additional = 0) => {
36
+ entries += additional;
37
+ if (entries > maxEntries || now() - started > maxMs) throw new Error('inventory limit');
38
+ };
39
+ }
40
+
41
+ function inspectEntry(directory, name, context, stack) {
42
+ context.budget(1);
43
+ if (context.matches(name)) return 1;
44
+ const path = join(directory, name);
45
+ if (unlinkedDirectory(context.fs.lstatSync(path))) stack.push({ path });
46
+ return 0;
47
+ }
48
+
49
+ function inspectDirectory(path, context, stack) {
50
+ const before = context.fs.lstatSync(path);
51
+ if (!unlinkedDirectory(before)) throw new Error('directory changed');
52
+ stack.push({ path, before });
53
+ for (const entry of context.fs.readdirSync(path, { encoding: 'buffer' })) {
54
+ // Decode losslessly or refuse the inventory; replacement characters can hide names.
55
+ const name = entryDecoder.decode(entry);
56
+ if (inspectEntry(path, name, context, stack)) return 1;
57
+ }
58
+ return 0;
59
+ }
60
+
61
+ function inspectFrame(frame, context, stack) {
62
+ if (frame.before) {
63
+ if (!unchanged(frame.before, context.fs.lstatSync(frame.path))) throw new Error('directory changed');
64
+ return 0;
65
+ }
66
+ if (context.visited.has(frame.path)) return 0;
67
+ context.visited.add(frame.path);
68
+ return inspectDirectory(frame.path, context, stack);
69
+ }
70
+
71
+ function walk(root, context) {
72
+ const stack = [{ path: root }];
73
+ while (stack.length) {
74
+ context.budget();
75
+ if (inspectFrame(stack.pop(), context, stack)) return 1;
76
+ }
77
+ return 0;
78
+ }
79
+
80
+ function inspectOperand(operand, context) {
81
+ context.budget();
82
+ if (!existingDirectory(operand, context.fs)) return 0;
83
+ const root = context.fs.realpathSync(operand);
84
+ if (walk(root, context)) return 1;
85
+ if (context.fs.realpathSync(operand) !== root) throw new Error('operand changed');
86
+ return 0;
87
+ }
88
+
89
+ // Injection is for deterministic specs only; the CLI always uses the fixed production limits.
90
+ // No file contents, input evaluation, or nested symlink traversal are involved.
91
+ export function inspectDescendants(paths, patterns, { fs = filesystem, now = () => performance.now(), maxEntries = 250000, maxMs = 5000 } = {}) {
92
+ const context = { fs, visited: new Set(), matches: nameMatcher(patterns), budget: inventoryBudget(now, maxEntries, maxMs) };
93
+ try {
94
+ for (const operand of paths) {
95
+ if (inspectOperand(operand, context)) return 1;
96
+ }
97
+ context.budget();
98
+ return 0;
99
+ } catch { return 2; }
100
+ }
101
+
102
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
103
+ const [countText, ...values] = process.argv.slice(2);
104
+ const count = Number(countText);
105
+ process.exitCode = Number.isInteger(count) && count > 0 && count <= values.length
106
+ ? inspectDescendants(values.slice(count), values.slice(0, count)) : 2;
107
+ }
@@ -565,6 +565,9 @@ manifest_writes_allowed() {
565
565
  repository_manifest_policy "$policy_root"
566
566
  }
567
567
 
568
+ # Batch directory inventory once per destructive call; ordinary references never inspect descendants.
569
+ inventory_directories=()
570
+
568
571
  # Judge $file (already absolute and normalized) and its physical destination.
569
572
  classify_resolved() {
570
573
  local physical_base=""
@@ -586,6 +589,12 @@ classify_resolved() {
586
589
  if names_match "$base" "${environment_patterns[@]}" || names_match "$physical_base" "${environment_patterns[@]}"; then
587
590
  classification=environment; return 0
588
591
  fi
592
+ if [ "$destructive_mode" = 1 ]; then
593
+ if [ -d "$file" ]; then inventory_directories[${#inventory_directories[@]}]="$file"; fi
594
+ if [ -n "$physical_file" ] && [ "$physical_file" != "$file" ] && [ -d "$physical_file" ]; then
595
+ inventory_directories[${#inventory_directories[@]}]="$physical_file"
596
+ fi
597
+ fi
589
598
  return 1
590
599
  }
591
600
 
@@ -638,6 +647,20 @@ if [ "$reference_mode" = 1 ]; then
638
647
  done < <(abspath "$candidate" "$cwd"; compgen -G "$REPLY" || true)
639
648
  fi
640
649
  done
650
+ if [ "${#inventory_directories[@]}" -gt 0 ]; then
651
+ inventory_status=0
652
+ if command -v node >/dev/null 2>&1; then
653
+ node "$script_directory/cratis-guard-writes-descendants.mjs" "${#environment_patterns[@]}" "${environment_patterns[@]}" "${inventory_directories[@]}" || inventory_status=$?
654
+ else inventory_status=2; fi
655
+ case "$inventory_status" in
656
+ 0) ;;
657
+ 1) printf '%s\n' "${inventory_directories[0]}" ;;
658
+ *)
659
+ printf '%s\n' 'BLOCKED by cratis-guard-writes: directory inventory could not be completed.' >&2
660
+ exit 2
661
+ ;;
662
+ esac
663
+ fi
641
664
  exit 0
642
665
  fi
643
666
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.184.0",
3
+ "version": "7.185.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [