@cratis/pi 7.170.5 → 7.170.7

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.
@@ -44,6 +44,11 @@ Reader glob probes skip directories only when decoded options establish a nonrec
44
44
  unknown or recursive grep options keep directory matches conservative. Simple sed print/substitution
45
45
  programs are data only without in-place edits, execution, or file writes; `-f` remains a file operand.
46
46
  GitHub API endpoints are normalized before checking sensitive paths.
47
+ GitHub output filters (`--jq`/`-q`, `--template`/`-t`) may select response fields such as `.env`,
48
+ but may not read the process environment through `env` or `$ENV`, including within expressions.
49
+ Quoted strings and comments in jq filters remain data. Bundled filter flags are checked too;
50
+ `-t` is a title or subject only for `pr`/`issue`/`release` create/edit, `pr merge`, and
51
+ `ssh-key`/`gpg-key` add. API endpoint names never opt out of template checks.
47
52
 
48
53
  The shell-write guard classifies **write-target words**, not every word. It lexes the command into
49
54
  simple commands. When every command is a reviewed reader or staging verb (`cat`, `head`, `tail`, `wc`,
@@ -66,7 +71,45 @@ is admitted after a `cd`, and writes to those files stay refused. The working di
66
71
  copy runs. A write-target word with expansion syntax (`$`, backtick, `~`, parentheses or braces) is judged by every
67
72
  suffix that follows a slash in it (`$PWD/.cratis/x` and `~+/.cratis/x` are treated as `.cratis/x` in the working
68
73
  directory), without parsing the expansion, and refused if a suffix is protected, which includes a read of a protected path through a variable. This is a
69
- best-effort lexical check, not enforcement: a variable holding the whole path still passes.
74
+ best-effort lexical check, not enforcement: a variable holding the whole path still passes for ordinary commands.
75
+ A separate destructive-operand scan refuses removal, move sources, `find -delete` and `git clean` operands
76
+ that reach protected controls or their ancestors. Literal cwd changes are resolved:
77
+ `cd node_modules && rm -rf .` is allowed when that directory contains no controls; an uncertain cwd or
78
+ unresolved destructive operand is refused only after a destructive operation is identified.
79
+
80
+ Command positions are exposed only by assignments and these established execution prefixes:
81
+ `sudo`, `doas`, `env`, `command`, `builtin`, `exec`, `nohup`, `nice`, `ionice`, `timeout`, `time`,
82
+ `stdbuf`, `xargs`, `setsid`, `chroot`, `nsenter`, and `busybox`. The scan also handles `eval`, literal
83
+ `sh`/`bash`/`dash`/`zsh`/`ksh`/`ash` scripts (`-c`, including option arguments), `find` actions
84
+ (`-exec`, `-execdir`, `-ok`, `-okdir`, `-delete`), and Git global options before `clean` (including
85
+ value-taking `--attr-source`, `--config-env`, and legacy `--super-prefix`). `env -S`/`--split-string`
86
+ values are split into argv (whitespace, quotes and supported escapes), never parsed as shell source;
87
+ argument punctuation remains data. Unsupported split-string shapes use the uncertainty rule below.
88
+ Every wrapper uses the same argv dispatch, retaining the original command's redirections, heredoc
89
+ bodies and inherited pipeline input through nested prefixes and split strings. Destructive `xargs`
90
+ executions have unresolved stdin operands even with replacement strings or safe literal operands.
91
+ Literal shell stdin from here-strings, heredocs, and `echo`, simple `printf`, or `cat` pipelines is
92
+ inspected, including shells selecting `-`, `/dev/stdin`, `/dev/fd/0`, or `/proc/self/fd/0`. Input
93
+ redirections are applied in order: fd-0 aliases retain inherited data, `/dev/null` or other opaque
94
+ files replace it, and nonzero input descriptors do not replace stdin. Arbitrary file contents are not read.
95
+ Only stdout that still feeds the pipeline is propagated; `|&` is a pipe operator with a conservative
96
+ merged-descriptor route. Effective non-interactive `-n`/`-o noexec` scripts are not executed. Calling-shell substitutions are still inspected, including for syntax-only
97
+ shells. Ordinary reader data, comments, and properly terminated non-executed heredoc bodies remain data.
98
+ Arithmetic shifts are not heredoc redirections. Unquoted heredoc substitutions are checked accordingly.
99
+
100
+ An unclassified execution boundary uses one uncertainty rule: refuse when its remaining executable text
101
+ contains destructive-verb, Git-clean, or find-delete evidence; otherwise allow. This includes nesting
102
+ beyond four recursive script levels, unterminated or ambiguous heredocs/arithmetic, and unknown option
103
+ value shapes. Known heredoc bodies are removed from the depth fallback unless selected as shell stdin.
104
+
105
+ This guard is cooperative, not a sandbox. Arbitrary wrappers, script files, interpreter programs, and
106
+ unknown-program arguments are not inspected; for example, `unknown-program rm -rf .` is allowed.
107
+ Expansion-produced verbs (`r=rm; $r -rf .`), dynamic stdin scripts,
108
+ filesystem changes earlier in the command (including newly created symlinks), and `CDPATH`
109
+ effects remain limitations. Tools outside the destructive verb set (such as `rsync --delete`,
110
+ `tar --remove-files`, `zip -m`, and interpreter one-liners) are not covered. No command text is executed
111
+ by the guard. The separate existing reference/readonly and secrets checks still apply.
112
+ Run `cratis ai update` to receive this protection.
70
113
 
71
114
  Git reflog selectors with unprotected prefixes (`stash@{0}`, `HEAD@{1}`, `branch@{upstream}`) are revisions, not paths.
72
115
 
@@ -595,7 +595,18 @@ function sed_slots(A, s, n, i, w, program, explicit, ended, scripts) {
595
595
  return scripts > 0
596
596
  }
597
597
  # Only fully modeled literal non-readers can distinguish data slots from paths.
598
- function nonreader(A, M, n, i, w, first, read) {
598
+ function gh_reader_bundle(A, i, n, j, flag) {
599
+ for (j = 2; j <= length(A[i]); j++) {
600
+ flag = substr(A[i], j, 1)
601
+ if (flag ~ /^[icwd]$/) continue
602
+ if (flag != "q" && flag != "t") return 0
603
+ DATA[i] = 1
604
+ if (j == length(A[i])) { if (++i > n) return 0; DATA[i] = 1 }
605
+ return i
606
+ }
607
+ return i
608
+ }
609
+ function nonreader(A, M, n, i, w, first, read, nexti) {
599
610
  delete DATA
600
611
  for (i = 1; i <= n; i++) if (expands(A[i], M[i]) || index(A[i], "`") || A[i] ~ /^</) return 0
601
612
  first = tolower(base(A[1]))
@@ -627,9 +638,11 @@ function nonreader(A, M, n, i, w, first, read) {
627
638
  for (i = A[2] == "api" ? 3 : 4; i <= n; i++) {
628
639
  w = A[i]
629
640
  if (w ~ /^>/) { if (w == ">" || w == ">>") i++; continue }
641
+ if (w ~ /^--(jq|template)=/) { DATA[i] = 1; continue }
630
642
  if (w ~ /^(--jq|-q|--template|-t)$/) { if (++i > n) return 0; DATA[i] = 1; continue }
631
643
  if (w ~ /^(--json|--repo|-R|--limit|-L|--hostname|--header|-H)$/) { if (++i > n) return 0; DATA[i] = 1; continue }
632
644
  if (A[2] == "api" && w ~ /^(--method|-X)$/) { if (++i > n || A[i] !~ /^(GET|HEAD)$/) return 0; continue }
645
+ if (w ~ /^-[^-]/) { nexti = gh_reader_bundle(A, i, n); if (!nexti) return 0; i = nexti; continue }
633
646
  if (w ~ /^-/ && w !~ /^(--paginate|--slurp|--include|--silent|--log|--log-failed|--web)$/) return 0
634
647
  if (A[2] != "api") DATA[i] = 1
635
648
  }
@@ -885,7 +898,19 @@ function tokenize(s, i, n, c, c2, j, dash, delim) {
885
898
  }
886
899
 
887
900
  # ── option parsing shared by the CLIs: positionals P/PI, output format, -f/--format value, --raw ──
888
- function kparse(A, s, n, shortvals, i, w, eq, key, val, f, rest) {
901
+ function gh_short_options(A, i, shortvals, output_filters, j, f, rest, value) {
902
+ for (j = 2; j <= length(A[i]); j++) {
903
+ f = substr(A[i], j, 1)
904
+ if (!index(shortvals, f)) continue
905
+ rest = substr(A[i], j + 1)
906
+ if (rest == "") value = A[++i]
907
+ else { value = rest; sub(/^=/, "", value) }
908
+ if (f == "q" || (f == "t" && output_filters == 1)) check_gh_filter(value)
909
+ return i
910
+ }
911
+ return i
912
+ }
913
+ function kparse(A, s, n, shortvals, output_filters, i, w, eq, key, val, f, rest) {
889
914
  delete P; delete PI
890
915
  np = 0; outfmt = ""; fmtval = ""; tmpl = ""; tmplfile = 0; dd = 0; raw = 0
891
916
  for (i = s; i <= n; i++) {
@@ -894,7 +919,11 @@ function kparse(A, s, n, shortvals, i, w, eq, key, val, f, rest) {
894
919
  if (substr(w, 1, 2) == "--") {
895
920
  eq = index(w, "="); key = w; val = ""
896
921
  if (eq) { key = substr(w, 1, eq - 1); val = substr(w, eq + 1) }
897
- if (key == "--output") { if (!eq) { i++; val = A[i] } outfmt = tolower(val) }
922
+ if (output_filters && (key == "--jq" || key == "--template")) {
923
+ if (!eq) { i++; val = A[i] }
924
+ check_gh_filter(val)
925
+ }
926
+ else if (key == "--output") { if (!eq) { i++; val = A[i] } outfmt = tolower(val) }
898
927
  else if (key == "--format") { if (!eq) { i++; val = A[i] } fmtval = val }
899
928
  else if (key == "--template") {
900
929
  if (!eq) { i++; val = A[i] } tmpl = val
@@ -906,6 +935,7 @@ function kparse(A, s, n, shortvals, i, w, eq, key, val, f, rest) {
906
935
  continue
907
936
  }
908
937
  if (substr(w, 1, 1) == "-" && length(w) > 1) {
938
+ if (output_filters) { i = gh_short_options(A, i, shortvals, output_filters); continue }
909
939
  f = substr(w, 2, 1); rest = substr(w, 3)
910
940
  if (f == "o") {
911
941
  if (rest == "") { i++; val = A[i] } else val = (substr(rest, 1, 1) == "=" ? substr(rest, 2) : rest)
@@ -1664,8 +1694,45 @@ function endpoint_path(path, i, pair, value, decoded) {
1664
1694
  sub(/[?#].*$/, "", decoded); gsub(/\/\/+/, "/", decoded); sub(/\/+$/, "", decoded)
1665
1695
  return decoded
1666
1696
  }
1697
+ # Ignore string literals and field names, but inspect expressions inside string interpolation.
1698
+ function filter_reads_environment(s, i, c, nextc, quoted, depth, parens, token, previous, level, containers, object_key) {
1699
+ for (i = 1; i <= length(s); i++) {
1700
+ c = substr(s, i, 1); nextc = substr(s, i + 1, 1)
1701
+ if (quoted) {
1702
+ if (c == "\\") {
1703
+ if (nextc == "(") { parens[++depth] = 1; quoted = 0; previous = "" }
1704
+ i++
1705
+ } else if (c == "\"") quoted = 0
1706
+ continue
1707
+ }
1708
+ if (c == "\"") { quoted = 1; previous = "string"; continue }
1709
+ if (c == "#") { while (i <= length(s) && substr(s, i, 1) != "\n") i++; continue }
1710
+ if (depth && c == "(") parens[depth]++
1711
+ if (depth && c == ")" && --parens[depth] == 0) { depth--; quoted = 1; continue }
1712
+ if (c == "[" || c == "{") containers[++level] = c
1713
+ if (c == "]" || c == "}") { delete containers[level]; level-- }
1714
+ if (c ~ /[A-Za-z_]/) {
1715
+ token = c
1716
+ while (substr(s, i + 1, 1) ~ /[A-Za-z0-9_]/) token = token substr(s, ++i, 1)
1717
+ object_key = containers[level] == "{" && (previous == "{" || previous == ",") && substr(s, i + 1) ~ /^[[:space:]]*:[^:]/
1718
+ if ((token == "env" && previous != "." && previous != "$" && !object_key) || (token == "ENV" && previous == "$")) return 1
1719
+ previous = token
1720
+ } else if (c !~ /[[:space:]]/) previous = c
1721
+ }
1722
+ return 0
1723
+ }
1724
+ function check_gh_filter(value) {
1725
+ if (filter_reads_environment(value))
1726
+ report("gh output filter reads the process environment, including credentials", "select response fields without env or $ENV")
1727
+ }
1728
+ function gh_title_option() {
1729
+ return (P[1] ~ /^(pr|issue|release)$/ && P[2] ~ /^(create|edit)$/) ||
1730
+ (P[1] == "pr" && P[2] == "merge") || (P[1] ~ /^(ssh-key|gpg-key)$/ && P[2] == "add")
1731
+ }
1667
1732
  function gh(A, s, n, i, w, mutating, k, path, kind) {
1668
1733
  kparse(A, s + 1, n, "XHfFqtR")
1734
+ # Only named command pairs use -t for a title or subject rather than an output template.
1735
+ kparse(A, s + 1, n, "XHfFqtR", (gh_title_option() ? 2 : 1))
1669
1736
  if (P[1] == "secret") {
1670
1737
  if (P[2] != "set" && P[2] != "delete" && P[2] != "remove")
1671
1738
  report("gh secret " P[2] " reads the repository secret store", "gh secret set NAME (writes nothing to the output); refer to secrets by name only")
@@ -752,6 +752,670 @@ BEGIN {
752
752
  exit readonly(text) ? 0 : 1
753
753
  }
754
754
  AWK
755
+ # This stage is independent of the readonly/reference grammar above. Prefix syntax is
756
+ # never a reason to refuse a reader: only a discovered destructive operation has operands.
757
+ IFS= read -r -d '' destructive_program <<'AWK' || true
758
+ function base(word) { sub(/^.*\//, "", word); return word }
759
+ function member(list, word) { return index(" " list " ", " " word " ") > 0 }
760
+ function destructive(word) { return member("rm rmdir unlink shred mv", base(word)) }
761
+ function shell(word) { return member("sh bash dash zsh ksh ash", base(word)) }
762
+ # Only these established execution prefixes expose another command position.
763
+ function wrapper(word) {
764
+ return member("sudo doas env command builtin exec nohup nice ionice timeout time stdbuf xargs setsid chroot nsenter busybox", base(word))
765
+ }
766
+ function emit(path) { if (path != "" && !seen[path]++) print path }
767
+ # Every unclassified execution boundary uses the same fail-closed evidence rule.
768
+ # Callers pass only the remaining uncertain region, never known heredoc data.
769
+ function unclassified(text) {
770
+ gsub(/["\047\\]/, "", text)
771
+ if (text ~ /(^|[[:space:];|&()`\/])(rm|rmdir|unlink|shred|mv)([[:space:];|&()`]|$)/ ||
772
+ (text ~ /(^|[[:space:];|&()`\/])git[[:space:]]/ && text ~ /(^|[[:space:]])clean([[:space:]]|$)/) ||
773
+ (text ~ /(^|[[:space:];|&()`\/])find[[:space:]]/ && text ~ /(^|[[:space:]])-delete([[:space:]]|$)/)) emit("!")
774
+ }
775
+ function remaining(d, start, end, i, j, text) {
776
+ for (i = start; i <= end; i++) {
777
+ text = text " " W[d, i]
778
+ for (j = 1; j <= BC[d, i]; j++) text = text " " B[d, i, j]
779
+ }
780
+ return text
781
+ }
782
+ # Arithmetic shifts are not redirections. Consume balanced arithmetic as one word;
783
+ # its contents are otherwise uncertain, including any nested executable substitution.
784
+ function arithmetic(text, start, bracket, i, c, quote, level, parens) {
785
+ level = bracket ? 1 : 2; quote = ""; arithmetic_complete = 0
786
+ for (i = start; i <= length(text); i++) {
787
+ c = substr(text, i, 1)
788
+ if (c == "\\") { i++; continue }
789
+ if (quote != "") { if (c == quote) quote = ""; continue }
790
+ if (c == "\047" || c == "\"") { quote = c; continue }
791
+ if (bracket) {
792
+ if (c == "(") parens++
793
+ else if (c == ")" && parens) parens--
794
+ else if (!parens && c == "[") level++
795
+ else if (!parens && c == "]") level--
796
+ } else {
797
+ if (c == "(") level++
798
+ else if (c == ")") level--
799
+ }
800
+ if (!level) { arithmetic_complete = 1; break }
801
+ }
802
+ arithmetic_end = i
803
+ return substr(text, start, i - start)
804
+ }
805
+ function arithmetic_prefix(text, i, quoted) {
806
+ arithmetic_bracket = substr(text, i, 2) == "$["
807
+ if (arithmetic_bracket) return i + 2
808
+ if (substr(text, i, 3) == "$((") return i + 3
809
+ if (!quoted && substr(text, i, 2) == "((") return i + 2
810
+ return 0
811
+ }
812
+ # Expand only the documented literal prefixes; never evaluate shell text.
813
+ function resolved(word, quoted, cwd, uncertain, suffix, rest) {
814
+ if (word ~ /^\$PWD(\/|$)/) word = cwd substr(word, 5)
815
+ else if (word ~ /^\$\{PWD\}(\/|$)/) word = cwd substr(word, 7)
816
+ else if (word ~ /^\$HOME(\/|$)/) word = ENVIRON["HOME"] substr(word, 6)
817
+ else if (word ~ /^\$\{HOME\}(\/|$)/) word = ENVIRON["HOME"] substr(word, 8)
818
+ else if (!quoted && word ~ /^~(\/|$)/) word = ENVIRON["HOME"] substr(word, 2)
819
+ else if (!quoted && word ~ /^~\+(\/|$)/) word = cwd substr(word, 3)
820
+ else if (!quoted && word ~ /^~/) return "!"
821
+ if (word ~ /[$`]/) {
822
+ # A variable prefix with a literal suffix is not evidence of a root operand.
823
+ rest = word
824
+ if (rest ~ /^\$\{[A-Za-z_][A-Za-z0-9_]*\}\//) sub(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}\//, "", rest)
825
+ else if (rest ~ /^\$[A-Za-z_][A-Za-z0-9_]*\//) sub(/^\$[A-Za-z_][A-Za-z0-9_]*\//, "", rest)
826
+ else return "!"
827
+ if (rest == "" || rest ~ /[$`]/) return "!"
828
+ word = rest
829
+ }
830
+ if (word ~ /^\//) return word
831
+ if (uncertain) return "!"
832
+ return cwd "/" word
833
+ }
834
+ function operand(word, quoted, cwd, uncertain) {
835
+ if (word != "" && word != "{}") emit(resolved(word, quoted, cwd, uncertain))
836
+ }
837
+ # Heredoc delimiters are quote-removed, never expanded or executed.
838
+ function heredoc_word(text, start, i, c, quote, word, active) {
839
+ hd_quoted = 0; quote = ""; active = 0
840
+ for (i = start; substr(text, i, 1) ~ /[ \t]/; i++) {}
841
+ for (; i <= length(text); i++) {
842
+ c = substr(text, i, 1)
843
+ if (quote != "") { if (c == quote) quote = ""; else word = word c; continue }
844
+ if (c == "\047" || c == "\"") { quote = c; hd_quoted = active = 1; continue }
845
+ if (c == "\\") { word = word substr(text, ++i, 1); hd_quoted = active = 1; continue }
846
+ if (c ~ /[ \t\r\n;&|()<>]/ || (c == "#" && !active)) break
847
+ word = word c; active = 1
848
+ }
849
+ hd_valid = active && quote == "" && i <= length(text) + 1
850
+ hd_end = i - 1
851
+ return word
852
+ }
853
+ function heredoc_body(text, start, delimiter, strip, i, size, line, body) {
854
+ i = start; hd_complete = 0
855
+ while (i <= length(text)) {
856
+ size = index(substr(text, i), "\n")
857
+ if (!size) size = length(text) - i + 2
858
+ line = substr(text, i, size - 1)
859
+ if (strip) sub(/^\t+/, "", line)
860
+ if (line == delimiter) { hd_complete = 1; hd_end = i + size - 1; return body }
861
+ body = body line "\n"; i += size
862
+ }
863
+ hd_end = length(text)
864
+ return body
865
+ }
866
+ # Return a substitution body without executing it. Ignore parentheses in data/comments.
867
+ function substitution(text, start, tick, i, c, quote, nesting, body, id, count, j, delimiter, strip, end, k) {
868
+ nesting = 1; quote = ""; id = ++sub_id; count = 0
869
+ for (i = start; i <= length(text); i++) {
870
+ c = substr(text, i, 1)
871
+ if (c == "\\") { body = body c substr(text, ++i, 1); continue }
872
+ if (tick) { if (c == "`") break }
873
+ else if (quote != "") { if (c == quote) quote = "" }
874
+ else if (c == "\047" || c == "\"") quote = c
875
+ else if (c == "#" && (i == start || substr(text, i - 1, 1) ~ /[ \t\n;&|()]/)) {
876
+ while (i <= length(text) && substr(text, i, 1) != "\n") body = body substr(text, i++, 1)
877
+ i--; continue
878
+ } else if ((k = arithmetic_prefix(text, i, 0))) {
879
+ arithmetic(text, k, arithmetic_bracket)
880
+ body = body substr(text, i, arithmetic_end - i + 1); i = arithmetic_end; continue
881
+ } else if (c == "<" && substr(text, i, 2) == "<<" && substr(text, i, 3) != "<<<") {
882
+ strip = substr(text, i + 2, 1) == "-"
883
+ delimiter = heredoc_word(text, i + 2 + strip)
884
+ if (!hd_valid) { unclassified(substr(text, i)); sub_end = length(text); return body }
885
+ SD[id, ++count] = delimiter; SS[id, count] = strip
886
+ body = body substr(text, i, hd_end - i + 1); i = hd_end; continue
887
+ } else if (c == "(") nesting++
888
+ else if (c == ")" && !--nesting) break
889
+ body = body c
890
+ if (c == "\n" && quote == "" && count) {
891
+ for (j = 1; j <= count; j++) {
892
+ end = i
893
+ delimiter = heredoc_body(text, i + 1, SD[id, j], SS[id, j])
894
+ if (!hd_complete) unclassified(delimiter)
895
+ i = hd_end; body = body substr(text, end + 1, i - end)
896
+ }
897
+ count = 0
898
+ }
899
+ }
900
+ if (i > length(text) || count) unclassified(body)
901
+ sub_end = i
902
+ return body
903
+ }
904
+ function data_substitutions(text, d, word, i, c, body, k) {
905
+ for (i = 1; i <= length(text); i++) {
906
+ c = substr(text, i, 1)
907
+ if (c == "\\") { i++; continue }
908
+ if ((k = arithmetic_prefix(text, i, 1))) {
909
+ body = arithmetic(text, k, arithmetic_bracket); unclassified(body); i = arithmetic_end; continue
910
+ }
911
+ if (c == "`" || substr(text, i, 2) == "$(") {
912
+ body = substitution(text, i + (c == "`" ? 1 : 2), c == "`")
913
+ B[d, word, ++BC[d, word]] = body; i = sub_end
914
+ }
915
+ }
916
+ }
917
+ function lex(text, d, i, c, nextc, quote, word, quoted, active, n, body, k, pending, delimiter, strip, hd_index, end) {
918
+ n = 0; quote = ""; word = ""; active = 0; quoted = 0; pending = 0
919
+ for (i = 1; i <= length(text); i++) {
920
+ c = substr(text, i, 1); nextc = substr(text, i + 1, 1)
921
+ if (quote != "\047" && (k = arithmetic_prefix(text, i, quote != ""))) {
922
+ body = arithmetic(text, k, arithmetic_bracket); unclassified(body)
923
+ i = arithmetic_end; word = word "$__arithmetic"; active = 1; continue
924
+ }
925
+ if (quote != "\047" && (c == "`" || (c == "$" && nextc == "("))) {
926
+ body = substitution(text, i + (c == "`" ? 1 : 2), c == "`")
927
+ B[d, n + 1, ++BC[d, n + 1]] = body
928
+ i = sub_end; word = word "$__sub"; active = 1; continue
929
+ }
930
+ if (quote != "") {
931
+ if (c == quote) { quote = ""; continue }
932
+ if (c == "\\" && quote != "\047" && nextc ~ /[$`"\\]/) c = substr(text, ++i, 1)
933
+ word = word c; continue
934
+ }
935
+ if (c == "\047" || c == "\"" || (c == "$" && nextc == "\047")) {
936
+ if (c == "$") c = substr(text, ++i, 1)
937
+ quote = c; if (!active) quoted = 1; active = 1; continue
938
+ }
939
+ if (c == "\\") { if (!active) quoted = 1; word = word substr(text, ++i, 1); active = 1; continue }
940
+ if (c == "#" && !active) {
941
+ while (i <= length(text) && substr(text, i, 1) != "\n") i++
942
+ i--; continue
943
+ }
944
+ # Parameter expansion braces and find placeholders are words, not groups.
945
+ if (c == "$" && nextc == "{") {
946
+ k = i + 2
947
+ while (k <= length(text) && substr(text, k, 1) != "}") k++
948
+ word = word substr(text, i, k - i + 1); i = k; active = 1; continue
949
+ }
950
+ if (c == "{" && nextc == "}") { word = word "{}"; i++; active = 1; continue }
951
+ if (c ~ /[ \t\r\n;&|(){}<>]/) {
952
+ if (active) { W[d, ++n] = word; Q[d, n] = quoted; K[d, n] = "word"; T[d, n] = i - 1; F[d, n] = !quoted && word ~ /^[0-9]+$/ && substr(text, i - length(word), length(word)) == word; word = ""; active = quoted = 0 }
953
+ if (c ~ /[ \t\r]/) continue
954
+ if (c == "<" && nextc == "<") {
955
+ if (substr(text, i, 3) == "<<<") { W[d, ++n] = "<<<"; K[d, n] = "<<<"; T[d, n] = i; i += 2; continue }
956
+ strip = substr(text, i + 2, 1) == "-"
957
+ delimiter = heredoc_word(text, i + 2 + strip)
958
+ if (!hd_valid) { unclassified(substr(text, i)); return n }
959
+ W[d, ++n] = "<<"; K[d, n] = "<<"; T[d, n] = i
960
+ W[d, ++n] = delimiter; K[d, n] = "word"; Q[d, n] = hd_quoted
961
+ HS[d, n] = strip; HP[d, ++pending] = n
962
+ i = hd_end; continue
963
+ }
964
+ end = i
965
+ if (c == "&" && nextc == ">") {
966
+ c = "&>"; i++
967
+ if (substr(text, i + 1, 1) == ">") { c = "&>>"; i++ }
968
+ } else if (c == ">") {
969
+ if (nextc == ">" || nextc == "&") { c = c nextc; i++ }
970
+ else if (nextc == "|") i++
971
+ } else if (c == "<" && nextc == "&") { c = "<&"; i++ }
972
+ else if ((c == "&" || c == "|") && (nextc == c || (c == "|" && nextc == "&"))) { i++; c = c nextc }
973
+ W[d, ++n] = c; K[d, n] = c; T[d, n] = end
974
+ if (c == "\n" && pending) {
975
+ for (k = 1; k <= pending; k++) {
976
+ hd_index = HP[d, k]
977
+ H[d, hd_index] = heredoc_body(text, i + 1, W[d, hd_index], HS[d, hd_index]); i = hd_end
978
+ if (!hd_complete) unclassified(H[d, hd_index])
979
+ if (!Q[d, hd_index]) data_substitutions(H[d, hd_index], d, hd_index)
980
+ }
981
+ pending = 0
982
+ }
983
+ continue
984
+ }
985
+ word = word c; active = 1
986
+ }
987
+ if (active) { W[d, ++n] = word; Q[d, n] = quoted; K[d, n] = "word" }
988
+ if (quote != "" || pending) unclassified(remaining(d, 1, n))
989
+ return n
990
+ }
991
+ function wrapper_value(program, option) {
992
+ if (program == "env") return member("-u --unset -C --chdir -a --argv0", option)
993
+ if (program == "sudo") return member("-u -g -h -p -C -T -r -t -D -R -U -a -c --user --group --host --prompt --close-from --command-timeout --role --type --chdir --chroot", option)
994
+ if (program == "doas") return member("-u -C", option)
995
+ if (program == "exec") return option == "-a"
996
+ if (program == "nice") return member("-n --adjustment", option)
997
+ if (program == "ionice") return member("-c -n -p -P -u --class --classdata --pid --pgid --uid", option)
998
+ if (program == "timeout") return member("-s -k --signal --kill-after", option)
999
+ if (program == "time") return member("-f -o --format --output", option)
1000
+ if (program == "stdbuf") return member("-i -o -e --input --output --error", option)
1001
+ if (program == "xargs") return member("-I -J -E -d -L -n -P -s -a -R -S --eof --delimiter --max-lines --max-args --max-procs --max-chars --arg-file", option)
1002
+ if (program == "chroot") return member("--userspec --groups", option)
1003
+ if (program == "nsenter") return member("-t -S -G --target --setuid --setgid --root --wd --wdns", option)
1004
+ return 0
1005
+ }
1006
+ function wrapper_flag(program, option) {
1007
+ if (program == "env") return option ~ /^-[i0v]+$/ || member("--ignore-environment --null --debug --list-signal-handling --default-signal --ignore-signal --block-signal", option)
1008
+ if (program == "sudo") return option ~ /^-[nEHKSbklvVeis]+$/ || member("--non-interactive --preserve-env --set-home --reset-timestamp --remove-timestamp --stdin --background --validate --list --edit --login --shell", option)
1009
+ if (program == "doas") return member("-n -s -L", option)
1010
+ if (program == "command") return option == "-p"
1011
+ if (program == "exec") return member("-c -l", option)
1012
+ if (program == "time") return member("-p -v -q --portability --verbose --quiet", option)
1013
+ if (program == "xargs") return member("-0 -r -t -p -x -i --null --no-run-if-empty --verbose --interactive --exit --show-limits --replace", option)
1014
+ if (program == "setsid") return member("-c -f -w --ctty --fork --wait", option)
1015
+ if (program == "chroot") return option == "--skip-chdir"
1016
+ if (program == "nsenter") return member("-a -m -u -i -n -p -U -C -T --all --mount --uts --ipc --net --pid --user --cgroup --time --preserve-credentials --no-fork --follow-context", option)
1017
+ return 0
1018
+ }
1019
+ # Dispatch uses an argv copy, never shell source. Every prefix shares the same
1020
+ # redirection tail and inherited pipe input; splitting env argv cannot discard either.
1021
+ function copy_token(source, from, dest, to, j) {
1022
+ W[dest, to] = W[source, from]; Q[dest, to] = Q[source, from]; K[dest, to] = K[source, from]
1023
+ H[dest, to] = H[source, from]; T[dest, to] = T[source, from]; F[dest, to] = F[source, from]
1024
+ BC[dest, to] = BC[source, from]
1025
+ for (j = 1; j <= BC[source, from]; j++) B[dest, to, j] = B[source, from, j]
1026
+ }
1027
+ function redirection(d, i) { return K[d, i] ~ /^[<>]/ || K[d, i] ~ /^&>/ }
1028
+ function dispatch(d, start, end, slot, redirects, i, n, r) {
1029
+ slot = --dispatch_id; redirects = --dispatch_id
1030
+ for (i = start; i <= end; i++) {
1031
+ if (F[d, i] && redirection(d, i + 1) && T[d, i] + 1 == T[d, i + 1]) {
1032
+ copy_token(d, i++, redirects, ++r)
1033
+ }
1034
+ if (redirection(d, i)) {
1035
+ copy_token(d, i, redirects, ++r)
1036
+ if (i < end) copy_token(d, ++i, redirects, ++r)
1037
+ } else copy_token(d, i, slot, ++n)
1038
+ }
1039
+ for (i = 1; i <= r; i++) copy_token(redirects, i, slot, ++n)
1040
+ dispatch_head = executable(slot, 1, n)
1041
+ return slot
1042
+ }
1043
+ # env -S recognizes whitespace, quotes and escapes, not shell operators or substitutions.
1044
+ # Unsupported expansion/escape shapes use the shared destructive-evidence fallback.
1045
+ function env_words(text, slot, i, c, nextc, quote, word, active, n) {
1046
+ for (i = 1; i <= length(text) + 1; i++) {
1047
+ c = substr(text, i, 1); nextc = substr(text, i + 1, 1)
1048
+ if (c == "" || (quote == "" && c ~ /[[:space:]]/)) {
1049
+ if (active) { W[slot, ++n] = word; Q[slot, n] = 1; K[slot, n] = "word"; word = ""; active = 0 }
1050
+ continue
1051
+ }
1052
+ if (quote == "" && c == "#" && !active) break
1053
+ if (c == "\\" && quote != "\047") {
1054
+ i++
1055
+ if (nextc == "c") break
1056
+ if (nextc == "_") {
1057
+ if (quote == "") {
1058
+ if (active) { W[slot, ++n] = word; Q[slot, n] = 1; K[slot, n] = "word"; word = ""; active = 0 }
1059
+ continue
1060
+ }
1061
+ c = " "
1062
+ } else if (nextc == "n") c = "\n"
1063
+ else if (nextc == "r") c = "\r"
1064
+ else if (nextc == "t") c = "\t"
1065
+ else if (nextc == "v") c = "\v"
1066
+ else if (nextc == "f") c = "\f"
1067
+ else if (nextc ~ /[\\#\$"\047]/) c = nextc
1068
+ else { unclassified(text); return -1 }
1069
+ } else if (c == "\047" || c == "\"") {
1070
+ if (quote == "") { quote = c; active = 1; continue }
1071
+ if (quote == c) { quote = ""; continue }
1072
+ } else if (c == "$" && quote != "\047") { unclassified(text); return -1 }
1073
+ word = word c; active = 1
1074
+ }
1075
+ if (quote != "") { unclassified(text); return -1 }
1076
+ if (active) { W[slot, ++n] = word; Q[slot, n] = 1; K[slot, n] = "word" }
1077
+ return n
1078
+ }
1079
+ function executable(d, start, end, i, j, program, option, split_at, text, slot, count, first, expansions) {
1080
+ prefix_uncertain = 0; prefix_fed = 0; dispatch_end = end; i = start
1081
+ while (i <= end) {
1082
+ if (W[d, i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) { i++; continue }
1083
+ program = base(W[d, i])
1084
+ if (!wrapper(program)) return redirection(d, i) ? 0 : i
1085
+ if (member("chroot nsenter", program)) prefix_uncertain = 1
1086
+ if (program == "xargs") prefix_fed = 1
1087
+ i++
1088
+ while (i <= end && W[d, i] ~ /^-/) {
1089
+ option = W[d, i++]
1090
+ if (option == "--") break
1091
+ if (member("--help --version", option) || (program == "command" && member("-v -V", option)) || (program == "busybox" && member("--list --list-full", option))) return 0
1092
+ if ((program == "env" && (option ~ /^-C/ || option ~ /^--chdir(=|$)/)) || (program == "sudo" && (option ~ /^-[DR]/ || option ~ /^--(chdir|chroot)(=|$)/))) prefix_uncertain = 1
1093
+ if (program == "env" && (option ~ /^-[i0v]*S/ || option ~ /^--split-string(=|$)/)) {
1094
+ first = i - 1
1095
+ if (option == "--split-string" || option ~ /^-[i0v]*S$/) text = W[d, i++]
1096
+ else if (option ~ /^--/) text = substr(option, 16)
1097
+ else { split_at = index(option, "S"); text = substr(option, split_at + 1) }
1098
+ if (++expansions > 64) { unclassified(text " " remaining(d, i, end)); return 0 }
1099
+ slot = --dispatch_id; count = env_words(text, slot)
1100
+ if (count < 0) { unclassified(remaining(d, i, end)); return 0 }
1101
+ # Stage the suffix before replacing tokens, including all original redirects.
1102
+ for (j = i; j <= end; j++) copy_token(d, j, slot, count + j - i + 1)
1103
+ for (j = 1; j <= count + end - i + 1; j++) copy_token(slot, j, d, first + j - 1)
1104
+ end += count - (i - first); dispatch_end = end; i = first
1105
+ continue
1106
+ }
1107
+ if (wrapper_value(program, option)) { i++; continue }
1108
+ if (wrapper_flag(program, option) || option ~ /^--[^=]+=/ || (length(option) > 2 && wrapper_value(program, substr(option, 1, 2)))) continue
1109
+ unclassified(remaining(d, i - 1, end)); return 0
1110
+ }
1111
+ if (program == "timeout" || program == "chroot") i++
1112
+ }
1113
+ return 0
1114
+ }
1115
+ function removal(d, verb, end, cwd, uncertain, findpaths, i, w, count, options, target, j, sources) {
1116
+ count = 0; options = 1; target = 0; sources = 0
1117
+ for (i = verb + 1; i <= end; i++) {
1118
+ w = W[d, i]
1119
+ if (redirection(d, i)) break
1120
+ if (options && w == "--") { options = 0; continue }
1121
+ if (options && base(W[d, verb]) == "mv") {
1122
+ if (w == "-t" || w == "--target-directory") { target = 1; i++; continue }
1123
+ if (w ~ /^--target-directory=/ || w ~ /^-t./) { target = 1; continue }
1124
+ }
1125
+ if (options && w ~ /^-/) continue
1126
+ O[d, ++count] = w; OQ[d, count] = Q[d, i]
1127
+ }
1128
+ if (base(W[d, verb]) == "mv" && !target) count--
1129
+ for (j = 1; j <= count; j++) {
1130
+ w = O[d, j]
1131
+ if (w == "{}") {
1132
+ if (findpaths != "") emit(findpaths)
1133
+ else emit("!")
1134
+ } else operand(w, OQ[d, j], cwd, uncertain)
1135
+ sources++
1136
+ }
1137
+ }
1138
+ function git_clean(d, verb, end, cwd, uncertain, findpaths, depth, fed, i, j, w, subcommand, dry, paths, skip, alias, name, call, script, option) {
1139
+ subcommand = 0; call = ++git_call
1140
+ for (i = verb + 1; i <= end; i++) {
1141
+ w = W[d, i]
1142
+ if (w == "-C") {
1143
+ cwd = resolved(W[d, ++i], Q[d, i], cwd, uncertain)
1144
+ if (cwd == "!") uncertain = 1
1145
+ } else if (w == "-c") {
1146
+ alias = W[d, ++i]
1147
+ if (alias ~ /^alias\.[^=]+=/) {
1148
+ name = alias; sub(/^alias\./, "", name); sub(/=.*/, "", name)
1149
+ sub(/^[^=]*=/, "", alias); A[call, name] = alias
1150
+ }
1151
+ # Git 2.50.1 git.c handle_options(), plus legacy --super-prefix.
1152
+ } else if (member("--git-dir --work-tree --namespace --config-env --attr-source --super-prefix --shallow-file", w)) i++
1153
+ else if (w ~ /^--(git-dir|work-tree|namespace|config-env|attr-source|super-prefix|exec-path)=/) continue
1154
+ else if (member("-h --help -v --version --html-path --man-path --info-path --exec-path", w) || w ~ /^--list-cmds=/) return
1155
+ 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
1156
+ else if (w ~ /^-/) { unclassified("git " remaining(d, i, end)); return }
1157
+ else { subcommand = i; break }
1158
+ }
1159
+ if (!subcommand) return
1160
+ if (A[call, W[d, subcommand]] != "") {
1161
+ script = A[call, W[d, subcommand]]
1162
+ if (substr(script, 1, 1) == "!") script = substr(script, 2)
1163
+ else script = "git " script
1164
+ for (i = subcommand + 1; i <= end; i++) script = script " " quote_path(W[d, i])
1165
+ parse(script, cwd, uncertain, depth + 1, fed)
1166
+ return
1167
+ }
1168
+ # Once a subcommand is established, later words are its data, never another subcommand.
1169
+ if (W[d, subcommand] != "clean") return
1170
+ dry = 0; paths = 0; skip = 0
1171
+ for (i = subcommand + 1; i <= end; i++) {
1172
+ w = W[d, i]
1173
+ if (K[d, i] ~ /^[<>]/) break
1174
+ if (!skip && w == "--") { skip = 1; continue }
1175
+ if (!skip && w == "--exclude") { i++; continue }
1176
+ if (!skip && w ~ /^--exclude=/) continue
1177
+ if (!skip && w == "--dry-run") { dry = 1; continue }
1178
+ if (!skip && w ~ /^-[^-]/) {
1179
+ for (j = 2; j <= length(w); j++) {
1180
+ option = substr(w, j, 1)
1181
+ if (option == "e") { if (j == length(w)) i++; break }
1182
+ if (option == "n") dry = 1
1183
+ }
1184
+ continue
1185
+ }
1186
+ if (!skip && w ~ /^-/) continue
1187
+ GP[call, ++paths] = i
1188
+ }
1189
+ if (dry) return
1190
+ if (fed) { emit("!"); return }
1191
+ for (j = 1; j <= paths; j++) {
1192
+ i = GP[call, j]; w = W[d, i]
1193
+ if (w ~ /^:\// || w ~ /^:\(top/) emit(ENVIRON["GSW_ROOT"])
1194
+ else if (w ~ /^:\(/) emit("!")
1195
+ else if (w == "{}" && findpaths != "") emit(findpaths)
1196
+ else operand(w, Q[d, i], cwd, uncertain)
1197
+ }
1198
+ if (!paths) operand(".", 0, cwd, uncertain)
1199
+ }
1200
+ function find_command(d, verb, end, cwd, uncertain, depth, fed, i, j, start, paths, w, action, have, deleted, p) {
1201
+ paths = ""; have = 0; deleted = 0
1202
+ for (i = verb + 1; i <= end; i++) {
1203
+ w = W[d, i]
1204
+ if (member("-H -L -P", w)) continue
1205
+ if (w ~ /^-/ || w == "!" || w == "(") break
1206
+ p = resolved(w, Q[d, i], cwd, uncertain)
1207
+ FP[depth, ++have] = p
1208
+ }
1209
+ if (!have) FP[depth, ++have] = resolved(".", 0, cwd, uncertain)
1210
+ for (j = 1; j <= have; j++) paths = paths (j == 1 ? "" : "\n") FP[depth, j]
1211
+ for (; i <= end; i++) {
1212
+ w = W[d, i]
1213
+ if (w == "-delete") deleted = 1
1214
+ if (member("-exec -execdir -ok -okdir", w)) {
1215
+ start = i + 1
1216
+ while (++i <= end && W[d, i] != ";" && W[d, i] != "+") {}
1217
+ segment(d, start, i - 1, cwd, uncertain, depth, paths, "", fed)
1218
+ }
1219
+ }
1220
+ if (deleted) {
1221
+ if (fed) emit("!")
1222
+ else for (j = 1; j <= have; j++) emit(FP[depth, j])
1223
+ }
1224
+ }
1225
+ function stdin_data(d, start, end, pipe, i, data, kind, fd, target) {
1226
+ data = pipe
1227
+ for (i = start; i <= end; i++) {
1228
+ kind = K[d, i]
1229
+ if (kind !~ /^</) continue
1230
+ fd = descriptor(d, i - 1) ? W[d, i - 1] : 0
1231
+ target = W[d, ++i]
1232
+ if (fd != 0) continue
1233
+ if (kind == "<<<") data = target
1234
+ else if (kind == "<<") data = H[d, i]
1235
+ # Unknown files stay opaque, exactly as for an unwrapped shell. fd-0 aliases
1236
+ # preserve the inherited input, and later redirects replace earlier ones.
1237
+ else if (kind == "<" && member("/dev/stdin /dev/fd/0 /proc/self/fd/0", target)) continue
1238
+ else if (kind == "<&" && target == "0") continue
1239
+ else data = ""
1240
+ }
1241
+ return data
1242
+ }
1243
+ function descriptor(d, i) { return F[d, i] && T[d, i] + 1 == T[d, i + 1] && (K[d, i + 1] ~ /^[<>]/ || K[d, i + 1] ~ /^&>/) }
1244
+ function stdout_pipe(d, head, end, outgoing, i, fd, target, kind, call) {
1245
+ # |& can feed either descriptor to the consumer; conservatively retain both
1246
+ # routes when explicit descriptor duplication precedes the implicit merge.
1247
+ call = ++redirect_call; RD[call, 1] = 1; RD[call, 2] = outgoing == "|&"
1248
+ for (i = head + 1; i <= end; i++) {
1249
+ kind = K[d, i]
1250
+ if (kind !~ /^>/ && kind !~ /^&>/) continue
1251
+ fd = descriptor(d, i - 1) ? W[d, i - 1] : 1
1252
+ target = W[d, ++i]
1253
+ if (kind ~ /^&>/) { RD[call, 1] = RD[call, 2] = 0; continue }
1254
+ if (kind == ">&") {
1255
+ if (target == "-") RD[call, fd] = 0
1256
+ else if (target ~ /^[0-9]+$/) RD[call, fd] = ((call SUBSEP target) in RD) ? RD[call, target] : -1
1257
+ else RD[call, fd] = -1
1258
+ } else RD[call, fd] = 0
1259
+ }
1260
+ if (RD[call, 1] < 0) unclassified(remaining(d, head, end))
1261
+ return RD[call, 1] == 1
1262
+ }
1263
+ function reader_data(d, head, end, pipe, outgoing, program, i, word, data, format) {
1264
+ program = base(W[d, head])
1265
+ if (!member("cat echo printf", program) || !stdout_pipe(d, head, end, outgoing)) return ""
1266
+ if (program == "cat") {
1267
+ for (i = head + 1; i <= end; i++) {
1268
+ if (descriptor(d, i)) continue
1269
+ if (K[d, i] ~ /^[<>]/ || K[d, i] ~ /^&>/) { i++; continue }
1270
+ if (W[d, i] !~ /^-/) return ""
1271
+ }
1272
+ return stdin_data(d, head + 1, end, pipe)
1273
+ }
1274
+ if (program != "echo" && program != "printf") return ""
1275
+ i = head + 1
1276
+ if (program == "printf") {
1277
+ format = W[d, i++]
1278
+ if (format ~ /%/ && format != "%s" && format != "%s\\n") return ""
1279
+ if (format !~ /%/) { gsub(/\\n/, "\n", format); return format }
1280
+ } else while (i <= end && W[d, i] ~ /^-[neE]+$/) i++
1281
+ for (; i <= end; i++) {
1282
+ if (descriptor(d, i)) continue
1283
+ if (K[d, i] ~ /^[<>]/ || K[d, i] ~ /^&>/) { i++; continue }
1284
+ word = W[d, i]
1285
+ if (program == "printf") data = data word (format == "%s\\n" ? "\n" : "")
1286
+ else data = data (data == "" ? "" : " ") word
1287
+ }
1288
+ return data
1289
+ }
1290
+ function shell_command(d, head, end, cwd, uncertain, depth, pipe, fed, i, j, word, option, value, enabled, command, stdin, noexec, interactive, script) {
1291
+ command = stdin = noexec = interactive = 0; i = head + 1
1292
+ while (i <= end) {
1293
+ word = W[d, i]
1294
+ if (K[d, i] ~ /^[<>]/ || K[d, i] ~ /^&>/) { i += 2; continue }
1295
+ if (descriptor(d, i)) { i++; continue }
1296
+ if (word == "--" || word == "-") { if (word == "-") stdin = 1; i++; break }
1297
+ if (member("--help --version", word)) return
1298
+ if (member("--rcfile --init-file", word)) { i += 2; continue }
1299
+ if (member("--noprofile --norc --posix --restricted --verbose --debugger --login --noediting --dump-strings --dump-po-strings --pretty-print", word)) { i++; continue }
1300
+ if (word ~ /^[-+][A-Za-z]+$/) {
1301
+ enabled = substr(word, 1, 1) == "-"
1302
+ i++
1303
+ for (j = 2; j <= length(word); j++) {
1304
+ option = substr(word, j, 1)
1305
+ if (option == "c" && enabled) command = 1
1306
+ else if (option == "s") stdin = enabled
1307
+ else if (option == "n") noexec = enabled
1308
+ else if (option == "i") interactive = enabled
1309
+ else if (option == "o" || option == "O") {
1310
+ value = W[d, i++]
1311
+ if (option == "o" && value == "noexec") noexec = enabled
1312
+ } else if (option !~ /^[abefhkmptuvxBCEHPTirl]$/) { unclassified(remaining(d, head, end)); return }
1313
+ }
1314
+ continue
1315
+ }
1316
+ if (word ~ /^[-+]/) { unclassified(remaining(d, head, end)); return }
1317
+ break
1318
+ }
1319
+ if (noexec && !interactive) return
1320
+ if (command) { if (i <= end) parse(W[d, i], cwd, uncertain, depth + 1, fed); return }
1321
+ # Standard fd-0 aliases select stdin; ordinary script files remain opaque.
1322
+ if (member("- /dev/stdin /dev/fd/0 /proc/self/fd/0", W[d, i])) stdin = 1
1323
+ if (i <= end && !stdin) return
1324
+ script = stdin_data(d, head + 1, end, pipe)
1325
+ if (script != "") parse(script, cwd, uncertain, depth + 1, fed)
1326
+ }
1327
+ function segment(d, start, end, cwd, uncertain, depth, findpaths, pipe, fed, outgoing, head, i, j, k, w, script, context) {
1328
+ if (start > end) return ""
1329
+ # Substitutions/redirections execute in the calling shell, even for unknown programs.
1330
+ if (depth > 4) unclassified(remaining(d, start, end))
1331
+ for (i = start; depth <= 4 && i <= end; i++) {
1332
+ for (k = 1; k <= BC[d, i]; k++) parse(B[d, i, k], cwd, uncertain, depth + 1, 0)
1333
+ if ((K[d, i] == ">" || K[d, i] == "&>") && i < end && W[d, i + 1] !~ /[$`]/ && W[d, i + 1] != "/dev/null") operand(W[d, i + 1], Q[d, i + 1], cwd, uncertain)
1334
+ }
1335
+ d = dispatch(d, start, end); head = dispatch_head; end = dispatch_end
1336
+ context = uncertain || prefix_uncertain; fed = fed || prefix_fed
1337
+ if (!head) return ""
1338
+ if (depth > 4) {
1339
+ unclassified(remaining(d, head, end))
1340
+ if (shell(base(W[d, head]))) unclassified(stdin_data(d, head + 1, end, pipe))
1341
+ return ""
1342
+ }
1343
+ w = base(W[d, head])
1344
+ if (w == "git") git_clean(d, head, end, cwd, context, findpaths, depth, fed)
1345
+ else if (w == "find") find_command(d, head, end, cwd, context, depth + 1, fed)
1346
+ else if (destructive(w)) {
1347
+ # xargs always adds/replaces operands from stdin, even with safe literal operands.
1348
+ if (fed) emit("!")
1349
+ else removal(d, head, end, cwd, context, findpaths)
1350
+ } else if (w == "eval") {
1351
+ script = ""
1352
+ for (j = head + 1; j <= end; j++) script = script (j == head + 1 ? "" : " ") W[d, j]
1353
+ parse(script, cwd, context, depth + 1, fed)
1354
+ } else if (shell(w)) shell_command(d, head, end, cwd, context, depth, pipe, fed)
1355
+ else if (!fed) return reader_data(d, head, end, pipe, outgoing)
1356
+ return ""
1357
+ }
1358
+ function parse(text, cwd, uncertain, depth, fed, n, i, start, kind, level, head, path, old, j, pipe, data) {
1359
+ # Lex before the depth fallback so properly terminated heredoc bodies stay data.
1360
+ # A depth slot may be reused by several script words.
1361
+ for (i = 1; i <= N[depth]; i++) { delete W[depth, i]; delete Q[depth, i]; delete K[depth, i]; delete H[depth, i]; delete T[depth, i]; delete F[depth, i]; BC[depth, i] = 0 }
1362
+ n = lex(text, depth); N[depth] = n; start = 1; level = 0
1363
+ for (i = 1; i <= n + 1; i++) {
1364
+ kind = K[depth, i]
1365
+ if (i <= n && kind != ";" && kind != "\n" && kind != "&" && kind != "&&" && kind != "|" && kind != "|&" && kind != "||" && kind != "(" && kind != ")" && kind != "{" && kind != "}") continue
1366
+ data = segment(depth, start, i - 1, cwd, uncertain, depth, "", pipe, fed, kind)
1367
+ pipe = (kind == "|" || kind == "|&" ? data : "")
1368
+ head = start
1369
+ while (head < i && W[depth, head] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) head++
1370
+ if (kind != "|" && kind != "|&" && member("cd pushd popd", W[depth, head])) {
1371
+ path = W[depth, head + 1]
1372
+ if (path == "--") path = W[depth, head + 2]
1373
+ if (W[depth, head] == "popd" || path == "" || path == "-") uncertain = 1
1374
+ else {
1375
+ if (path ~ /[$`]/ && path !~ /^\$(PWD|HOME)(\/|$)/ && path !~ /^\$\{(PWD|HOME)\}(\/|$)/) old = "!"
1376
+ else old = resolved(path, Q[depth, head + 1], cwd, uncertain)
1377
+ if (old == "!") uncertain = 1
1378
+ else { cwd = old; uncertain = 0 }
1379
+ }
1380
+ }
1381
+ if (kind == "(") { CWD[depth, ++level] = cwd; UNC[depth, level] = uncertain }
1382
+ if (kind == ")" && level > 0) { cwd = CWD[depth, level]; uncertain = UNC[depth, level--] }
1383
+ start = i + 1
1384
+ }
1385
+ }
1386
+ function quote_path(path, q) { q = "\047"; gsub(/\047/, "\047\\\047\047", path); return q path q }
1387
+ BEGIN { parse(ENVIRON["GSW_COMMAND"], ENVIRON["GSW_CWD"], 0, 0) }
1388
+ AWK
1389
+ classifier="$script_directory/cratis-guard-writes.sh"
1390
+ repository_root="$cwd"
1391
+ while [ ! -e "$repository_root/.git" ]; do
1392
+ if [ "$repository_root" = / ]; then repository_root=''; break; fi
1393
+ repository_root="${repository_root%/*}"
1394
+ [ -n "$repository_root" ] || repository_root=/
1395
+ done
1396
+ destructive_text="$(GSW_COMMAND="$command_text" GSW_CWD="$cwd" GSW_ROOT="$repository_root" LC_ALL=C awk "$destructive_program" </dev/null)" || parser_failed
1397
+ if [ -n "$destructive_text" ]; then
1398
+ destructive_candidates=()
1399
+ while IFS= read -r candidate; do
1400
+ if [ "$candidate" = '!' ]; then
1401
+ 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
1402
+ exit 2
1403
+ fi
1404
+ destructive_candidates[${#destructive_candidates[@]}]="$candidate"
1405
+ done <<<"$destructive_text"
1406
+ destructive_input="$(jq -nc --arg cwd "$cwd" --args '{cwd:$cwd,tool_input:{file_paths:$ARGS.positional}}' -- "${destructive_candidates[@]}")" || parser_failed
1407
+ destructive_references="$("$BASH" "$classifier" --destructive-references <<<"$destructive_input")" || {
1408
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: could not check references (write guard failed).' >&2
1409
+ exit 2
1410
+ }
1411
+ if [ -n "$destructive_references" ]; then
1412
+ destructive_reference="${destructive_references%%$'\n'*}"
1413
+ destructive_reference="${destructive_reference#"$cwd"/}"
1414
+ destructive_reference="${destructive_reference#./}"
1415
+ printf "BLOCKED by cratis-guard-shell-writes: protected reference '%s' (cratis-guard-writes). Use the edit/write tools, or report the intended change; for a read, name literal paths or use the Read/Grep tools.\n" "$destructive_reference" >&2
1416
+ exit 2
1417
+ fi
1418
+ fi
755
1419
  glob_shell_safe=1
756
1420
  if [[ -n "${BASH_ENV+x}" || -n "${ENV+x}" || -n "${GLOBIGNORE+x}" ]]; then glob_shell_safe=0; fi
757
1421
  candidates_text="$(GSW_COMMAND="$command_text" GSW_CWD="$cwd" GSW_GLOB_SAFE="$glob_shell_safe" GSW_MODE=targets LC_ALL=C awk "$program" </dev/null)" || parser_failed
@@ -42,8 +42,9 @@ parser_failed() {
42
42
  # as a command substitution would drop them); a missing, null or false path is empty.
43
43
  # The process substitution's exit status does not reach the reading group, and Bash 3.2 (macOS /bin/bash)
44
44
  # cannot wait on its PID, so a sentinel field is written only after jq succeeds.
45
- reference_mode=0
45
+ reference_mode=0 destructive_mode=0 reference_root=""
46
46
  [ "${1:-}" != --references ] || reference_mode=1
47
+ if [ "${1:-}" = --destructive-references ]; then reference_mode=1; destructive_mode=1; fi
47
48
  cwd="" file="" notebook="" new_content="" new_string="" references="" parser_status=""
48
49
  {
49
50
  IFS= read -r -d '' cwd
@@ -296,6 +297,7 @@ control_match() {
296
297
  # Do not turn a standalone placeholder into a path by appending descendants.
297
298
  [ "$value" != '{}' ] || return 1
298
299
  [ "$reference_mode" = 1 ] || return 1
300
+ [ "$destructive_mode" != 1 ] || [ "$value" != '.' ] || return 0
299
301
  if [ "$reference_pattern" = 0 ]; then
300
302
  shopt -s nocasematch
301
303
  for pattern in "$@"; do
@@ -329,6 +331,13 @@ agent_control_target() {
329
331
  local target="$1" directory policy_root target_rel managed pattern
330
332
  dir_of "$target"
331
333
  directory="$REPLY"
334
+ if [ "$destructive_mode" = 1 ]; then
335
+ [ ! -d "$target" ] || directory="$target"
336
+ # A mutation of the repository or any containing directory reaches its controls too.
337
+ if [[ -n "$reference_root" && ( "$target" == / || "$reference_root" == "$target" || "$reference_root" == "$target"/* ) ]]; then
338
+ directory="$reference_root"
339
+ fi
340
+ fi
332
341
  # Keep the addressed spelling here, even when an adapter directory is a symlink.
333
342
  # .git is a directory in a checkout and a file in a linked worktree.
334
343
  while [ ! -e "$directory/.git" ]; do
@@ -337,8 +346,8 @@ agent_control_target() {
337
346
  directory="$REPLY"
338
347
  done
339
348
  policy_root="$directory"
340
- relative_to "$target" "$policy_root"
341
- target_rel="$REPLY"
349
+ if [[ "$destructive_mode" == 1 && ( "$target" == / || "$policy_root" == "$target" || "$policy_root" == "$target"/* ) ]]; then target_rel='.'
350
+ else relative_to "$target" "$policy_root"; target_rel="$REPLY"; fi
342
351
  # Policy files remain controls even in the authored corpus repository.
343
352
  if control_match "$target_rel" '.cratis/ai.manifest.json' '.cratis/ai.json'; then return 0; fi
344
353
  if [ ! -f "$policy_root/.cratis/ai.manifest.json" ] && authored_corpus_repository "$policy_root"; then
@@ -419,6 +428,11 @@ classify_file() {
419
428
  }
420
429
 
421
430
  if [ "$reference_mode" = 1 ]; then
431
+ reference_root="$cwd"
432
+ while [ ! -e "$reference_root/.git" ]; do
433
+ if [ "$reference_root" = / ]; then reference_root=''; break; fi
434
+ dir_of "$reference_root"; reference_root="$REPLY"
435
+ done
422
436
  candidates=() parser_status=""
423
437
  while IFS= read -r -d '' candidate; do candidates[${#candidates[@]}]="$candidate"; done < <(
424
438
  jq -j 'if type == "array" and length <= 256 and all(.[]; type == "string" and (explode | all(.[]; . != 0 and . != 9 and . != 10 and . != 13)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.170.5",
3
+ "version": "7.170.7",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [