From 53d80f7e85f9af905d2d6cbc43d8e6fa5fcaee21 Mon Sep 17 00:00:00 2001 From: CarlesUIPath Date: Wed, 25 Nov 2026 18:11:27 +0000 Subject: [PATCH 1/3] feat(criteria): opt-in match_on: simple_commands for command_executed A pattern can now match each simple command the shell runs instead of the raw Bash text, so a heredoc body, echo string or comment no longer counts as running a command. Heredoc bodies dropped (unquoted: substitutions kept; fed to a shell: parsed), $(...)/backticks/sh -c recursed, leading timeout/sudo/nohup/nice/exec/command/xargs/find -exec/stdbuf/time wrappers stripped; assignments and env stay visible. PowerShell/cmd calls and text that cannot be split fall back to raw matching, noted in the details. Matches count per simple command. Default behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 --- .claude/notes/contracts.md | 29 ++ docs/TASK_DEFINITION_GUIDE.md | 30 ++ plugins/coder-eval/reference/criteria.md | 10 +- src/coder_eval/criteria/command_executed.py | 112 +++++- src/coder_eval/models/criteria.py | 14 + src/coder_eval/shell_commands.py | 366 ++++++++++++++++++ .../test_command_executed_simple_commands.py | 333 ++++++++++++++++ 7 files changed, 881 insertions(+), 13 deletions(-) create mode 100644 src/coder_eval/shell_commands.py create mode 100644 tests/test_command_executed_simple_commands.py diff --git a/.claude/notes/contracts.md b/.claude/notes/contracts.md index c749413a5..19bb92513 100644 --- a/.claude/notes/contracts.md +++ b/.claude/notes/contracts.md @@ -125,6 +125,35 @@ The cost: with a null `tool_name`, a `max_count: 0` guard (and the legacy `command_not_executed` without a `tool_name`) no longer sees a command written into a Write or TodoWrite body. A guard on those bodies names the tool, one criterion per tool. +### Matching on simple commands + +`match_on: simple_commands` exists because graders could not tell a command that ran from a +mention of it. A `max_count: 0` guard tripped on a README heredoc that named the command, and +suites grew ever longer prefix lists and heredoc-skipping regexes to compensate (UiPath/skills +#5069). `coder_eval/shell_commands.py` splits the recorded text into simple commands once, +so a one-line anchored pattern replaces those regexes. + +The shape follows a blast-radius replay of 16,936 stored criterion evaluations (18 nightlies, +lab ticket 526): + +- It is opt-in per criterion, never global. With the patterns unchanged, 98 evaluations got + worse against 23 that got better: patterns that match quote characters, span two commands, + or target a python heredoc stop matching. +- Leading assignments and `env` options stay in the command. Stripping them lost the + `env -u UIPATH_STUDIO_PID` guards (43 evaluations). +- PowerShell / cmd.exe calls fall back to raw text. Parsing the Windows Codex + `pwsh -Command '...'` record as POSIX broke 9 evaluations. +- Matches are counted per simple command, not per call. Per call, a `min_count: 2` "passed" + on one real run plus a mention in a report. + +Text that cannot be split falls back to raw matching for that call, and the details say so. +So a parse failure never turns a match into a miss without notice. + +The splitter is linear: each nesting level re-scans only its own substring, and nesting is +capped. Each simple command is then windowed like a long command, so the ReDoS bound still +holds. Quoted and escaped operator characters are swapped for private-use stand-ins before +`shlex` runs, because `shlex` with `punctuation_chars` splits `';'` and `\;` like a bare `;`. + ## Recording a CLI invocation ### Evidence, not attestation diff --git a/docs/TASK_DEFINITION_GUIDE.md b/docs/TASK_DEFINITION_GUIDE.md index 1153735c0..7db2a46fb 100644 --- a/docs/TASK_DEFINITION_GUIDE.md +++ b/docs/TASK_DEFINITION_GUIDE.md @@ -1037,6 +1037,7 @@ Checks whether the agent executed specific tools/commands during evaluation. Ins | `max_count` | `null` | Optional inclusive upper bound. When set, the criterion passes iff `min_count <= matches <= max_count`. | | `require_success` | `false` | Only count commands that completed successfully. This is the reported success of the whole tool call, so `cmd \| tail` and `cmd; true` can pass when `cmd` fails. | | `exclude_pattern` | `null` | Regex that must NOT match; a command matching both `command_pattern` and `exclude_pattern` is skipped. It searches the same text as `command_pattern`, whether or not a `command_pattern` is set. | +| `match_on` | `command_text` | `command_text` matches the text of each call. `simple_commands` matches each command the shell runs, one at a time (see **Matching simple commands**). Set it per criterion. | **Which text is searched.** The shape of a call decides the text that `command_pattern` and `exclude_pattern` search: @@ -1066,6 +1067,35 @@ So with `tool_name: null`, a `max_count: 0` guard or an `exclude_pattern` does n With a pattern, `tool_name: null` searches the command of a shell call, not the parameters of every tool (see **Which text is searched**). +**Matching simple commands (`match_on: simple_commands`).** With the default `match_on: command_text`, a pattern searches the text of a shell call, so it cannot tell a command that runs from a mention of it. `match_on: simple_commands` splits each shell call into the simple commands the shell runs, and matches the pattern against each of them. A simple command is its argv with quotes resolved, joined by single spaces. + +```yaml +- type: "command_executed" + description: "Agent did not run flow debug" + command_pattern: "^(\\S*/)?uip (maestro )?flow debug\\b" + match_on: simple_commands + min_count: 0 + max_count: 0 +``` + +How the call is split: + +- **Not commands:** heredoc bodies, comments, and the words of a `for`/`select`/`case` header. A `<<'EOF'` body (quoted delimiter) is dropped whole. Of a `< bool: @@ -156,6 +170,46 @@ def _match_haystacks(cmd_text: str, *, is_shell: bool) -> list[str]: return haystacks +@lru_cache(maxsize=1024) +def _simple_command_texts(cmd_text: str) -> tuple[str, ...] | str: + """Each simple command ``cmd_text`` runs, as its argv joined by single spaces. + + A ``str`` instead is the reason the text is matched raw: it is PowerShell / cmd.exe, + or it cannot be split (see :mod:`coder_eval.shell_commands`). + + Memoized -- a pure function of ``cmd_text``, re-asked on every early-stop event. + + Rationale: .claude/notes/contracts.md § Matching on simple commands + """ + if _NON_POSIX_PREFIX.match(cmd_text): + return _NOT_POSIX + try: + argvs = simple_commands(cmd_text) + except (ShellSplitError, RecursionError): + return _UNPARSEABLE + if any(program_name(argv[0]) in NON_POSIX_SHELLS for argv in argvs): + return _NOT_POSIX + return tuple(" ".join(argv) for argv in argvs) + + +def _simple_commands_of(cmd: "CommandTelemetry") -> tuple[str, ...] | str | None: + """The simple commands of a shell call (see :func:`_simple_command_texts`), or None for another call. + + An argv list is re-quoted with ``shlex.join`` and split like a string. A call from a + PowerShell tool is not POSIX shell, whatever its text. + """ + if not _is_shell_call(cmd): + return None + raw_command = cmd.parameters.get("command") + if isinstance(raw_command, list) and raw_command and all(isinstance(a, str) for a in raw_command): + raw_command = shlex.join(raw_command) + if not isinstance(raw_command, str) or not raw_command: + return None + if "powershell" in (cmd.tool_name or "").lower(): + return _NOT_POSIX + return _simple_command_texts(raw_command) + + def _is_shell_call(cmd: "CommandTelemetry") -> bool: """True for a ``Bash`` call or any call with a ``command`` param (a shell tool under another name).""" return cmd.tool_name == "Bash" or "command" in cmd.parameters @@ -208,6 +262,24 @@ def _unsearched_note( return f"\n{len(unsearched)} call(s) without a command were not searched.{hint}" +def _raw_fallback_note(raw_fallbacks: dict[str, int]) -> str: + """A details line that says which shell calls ``match_on: simple_commands`` matched on raw text, or ``""``.""" + if not raw_fallbacks: + return "" + reasons = ", ".join(f"{n} {reason}" for reason, n in sorted(raw_fallbacks.items())) + return f"\nmatch_on=simple_commands: {sum(raw_fallbacks.values())} call(s) matched on raw text ({reasons})." + + +class _Matches(NamedTuple): + """What :meth:`CommandExecutedChecker._matching_commands` found.""" + + labels: list[str] + """One per match: a call, or with ``match_on: simple_commands`` a simple command.""" + unsearched: list["CommandTelemetry"] + raw_fallbacks: dict[str, int] + """Reason -> number of shell calls that ``match_on: simple_commands`` matched on raw text.""" + + @register_criterion class CommandExecutedChecker(BaseCriterion[CommandExecutedCriterion]): """Checker for CommandExecutedCriterion. @@ -224,7 +296,7 @@ def _matching_commands( all_commands: list["CommandTelemetry"], pattern: re.Pattern[str] | None, exclude_re: re.Pattern[str] | None, - ) -> tuple[list[str], list["CommandTelemetry"]]: + ) -> _Matches: """Filter + label the commands matching this criterion. Shared by ``_check_impl`` and ``live_verdict`` so a command can never @@ -232,18 +304,37 @@ def _matching_commands( score always agree on WHICH commands match). Callers compile the patterns and own error handling. - Returns the labels of the matching commands, and the calls a - ``command_pattern`` did not search because they gave no text (see - :func:`_search_text`). + Returns the labels of the matches, the calls a ``command_pattern`` did not + search because they gave no text (see :func:`_search_text`), and the shell + calls ``match_on: simple_commands`` matched on raw text. + + With ``match_on: simple_commands`` each simple command of a shell call is + matched on its own (both patterns, windowed like a long command), and each + matching one counts. """ matching: list[str] = [] unsearched: list[CommandTelemetry] = [] + raw_fallbacks: dict[str, int] = {} for cmd in all_commands: if criterion.tool_name is not None and cmd.tool_name != criterion.tool_name: continue if criterion.require_success and cmd.result_status != "success": continue + if criterion.match_on == "simple_commands": + units = _simple_commands_of(cmd) + if isinstance(units, tuple): + for unit in units: + windows = _search_windows(unit) + if pattern is not None and not any(pattern.search(w) for w in windows): + continue + if exclude_re is not None and any(exclude_re.search(w) for w in windows): + continue + matching.append(unit) + continue + if isinstance(units, str): + raw_fallbacks[units] = raw_fallbacks.get(units, 0) + 1 + searched = _search_text(cmd, tool_named=criterion.tool_name is not None) # Raw text AND, for a shell command, its quote-resolved form, so neither # the pattern nor the exclusion can be dodged by quoting. @@ -259,7 +350,7 @@ def _matching_commands( matching.append(searched[0]) else: matching.append(f"{cmd.tool_name}({json.dumps(cmd.parameters)[:80]})") - return matching, unsearched + return _Matches(matching, unsearched, raw_fallbacks) def live_verdict( self, @@ -291,7 +382,7 @@ def live_verdict( except re.error: return "undecided" - match_count = len(self._matching_commands(criterion, all_commands, pattern, exclude_re)[0]) + match_count = len(self._matching_commands(criterion, all_commands, pattern, exclude_re).labels) if criterion.max_count is not None and match_count > criterion.max_count: return "fail" if criterion.max_count is None and criterion.min_count > 0 and match_count >= criterion.min_count: @@ -363,7 +454,9 @@ def _check_impl( # Filter and count matching commands (shared with live_verdict so the # live trigger and the authoritative score never disagree on matches). - matching_commands, unsearched = self._matching_commands(criterion, all_commands, pattern, exclude_re) + matching_commands, unsearched, raw_fallbacks = self._matching_commands( + criterion, all_commands, pattern, exclude_re + ) match_count = len(matching_commands) @@ -385,6 +478,8 @@ def _check_impl( filters.append("require_success=True") if criterion.exclude_pattern is not None: filters.append(f"exclude=/{criterion.exclude_pattern}/") + if criterion.match_on == "simple_commands": + filters.append("match_on=simple_commands") filter_text = ", ".join(filters) if filters else "none" if criterion.max_count is None: @@ -393,6 +488,7 @@ def _check_impl( range_text = f"{match_count} matches (allowed range {criterion.min_count}..{criterion.max_count})" details = f"Matched {range_text} commands (filters: {filter_text})" details += _unsearched_note(criterion, unsearched, match_count) + details += _raw_fallback_note(raw_fallbacks) if matching_commands: # Show up to 3 example matches examples = matching_commands[:3] diff --git a/src/coder_eval/models/criteria.py b/src/coder_eval/models/criteria.py index e460e3d3e..2ff843385 100644 --- a/src/coder_eval/models/criteria.py +++ b/src/coder_eval/models/criteria.py @@ -940,6 +940,20 @@ class CommandExecutedCriterion(LiveSuccessCriterion): ), ) + match_on: Literal["command_text", "simple_commands"] = Field( + default="command_text", + description=( + "What a pattern matches in a shell call. `command_text` (default): the command text and its " + "shell-normalized form, once per call. `simple_commands`: each simple command the shell runs, " + "as its argv with quotes resolved, joined by single spaces -- heredoc bodies, comments and " + "echo strings are not commands, `$(...)` and `bash -c` strings are, and leading " + "timeout/sudo/nohup/nice/exec/command/xargs/stdbuf/time wrappers are stripped (assignments " + "and `env` stay). Each matching simple command counts towards min_count/max_count. A " + "PowerShell/cmd call or text that cannot be split is matched as `command_text`, which the " + "details say. Other tools' JSON params are matched as before." + ), + ) + @model_validator(mode="after") def _validate_count_bounds(self) -> CommandExecutedCriterion: """Reject impossible ranges where ``max_count < min_count``.""" diff --git a/src/coder_eval/shell_commands.py b/src/coder_eval/shell_commands.py new file mode 100644 index 000000000..7561fbdd1 --- /dev/null +++ b/src/coder_eval/shell_commands.py @@ -0,0 +1,366 @@ +"""Split a recorded shell command string into the simple commands it runs. + +Backs ``command_executed`` with ``match_on: simple_commands``: :func:`simple_commands` +returns the argv, quotes resolved, of each simple command the shell would run, so a +pattern can tell a command from a mention of it in a heredoc body, a string or a comment. +Leading wrappers (``timeout``, ``sudo``, ``nohup``, ...) are stripped; assignments and +``env`` stay. ``$(...)``, backticks, ``sh -c`` strings and heredocs fed to a shell are +parsed as commands. Not a shell: nothing is expanded or resolved. + +STDLIB-ONLY and pure. Linear in the length of the text: each nesting level re-scans only +its own substring, and nesting is capped at ``_MAX_DEPTH``. + +Rationale: .claude/notes/contracts.md § Matching on simple commands +""" + +import re +import shlex + + +SUBST = "__SUBST__" + +# A PowerShell / cmd.exe command is not POSIX shell; the caller falls back to raw text. +NON_POSIX_SHELLS = frozenset({"pwsh", "powershell", "cmd"}) + +_MAX_DEPTH = 6 +_SEP_CHARS = ";&|()\n" +# A quoted or escaped operator character is a word character. The scan swaps it for a +# private-use stand-in, so shlex cannot split on it, and the split swaps it back. +_PROTECTED = {ch: chr(0xE000 + k) for k, ch in enumerate(_SEP_CHARS)} +_PROTECT = str.maketrans(_PROTECTED) +_UNPROTECT = str.maketrans({v: k for k, v in _PROTECTED.items()}) +_HEREDOC = re.compile(r"<<(-?)[ \t]*(?:'([^'\n]*)'|\"([^\"\n]*)\"|(\\?)([A-Za-z0-9_.\-]+))") +_HEREDOC_MARK = re.compile(r"^__HEREDOC_(\d+)__$") +_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=") +# A redirection operator alone (target in the next token) or with its target attached. +_REDIRECT_OP = re.compile(r"^\d*(>>?|<<<|<>|<|>\|)$") +_REDIRECT_WITH_TARGET = re.compile(r"^\d*(>>?|<<<|<>|<|>\|)(?=.)") +_POSIX_SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"}) +_KEYWORDS = frozenset({"if", "then", "else", "elif", "fi", "do", "done", "while", "until", "!", "{", "}", "esac"}) +_HEADER_KEYWORDS = frozenset({"for", "select", "case"}) +_PLAIN_WRAPPERS = frozenset({"nohup", "exec", "command", "builtin"}) +# Wrapper -> its options that take a separate argument. +_FLAG_WRAPPERS: dict[str, frozenset[str]] = { + "sudo": frozenset({"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U", "--user", "--group"}), + "nice": frozenset({"-n", "--adjustment"}), + "stdbuf": frozenset({"-i", "-o", "-e"}), + "time": frozenset({"-f", "-o"}), + "xargs": frozenset({"-I", "-n", "-P", "-L", "-d", "-a", "-E", "-s", "--delimiter", "--max-args", "--max-procs"}), + "timeout": frozenset({"-s", "-k", "--signal", "--kill-after"}), +} + + +class ShellSplitError(ValueError): + """The text is not shell this module can split (an unterminated quote, ``$(`` or backtick).""" + + +def program_name(arg0: str) -> str: + """``arg0``'s basename, lowercased and without ``.exe``; ``/`` and ``\\`` both separate.""" + base = re.split(r"[\\/]", arg0)[-1].lower() + return base.removesuffix(".exe") + + +def simple_commands(text: str) -> list[list[str]]: + """The argv of each simple command ``text`` runs, in no particular order. + + Raises :class:`ShellSplitError` when the text cannot be split. + """ + return _commands(text, 0) + + +def _commands(text: str, depth: int) -> list[list[str]]: + if depth > _MAX_DEPTH: + raise ShellSplitError("nested deeper than the limit") + top, substitutions, heredocs = _scan(text) + result: list[list[str]] = [] + for argv in _split(top): + heredoc_ids = [int(m.group(1)) for t in argv if (m := _HEREDOC_MARK.match(t))] + argv = _strip_redirections([t for t in argv if not _HEREDOC_MARK.match(t)]) + argv, scripts, extra = _unwrap(argv) + for k in heredoc_ids: + quoted, body = heredocs[k] + if argv and _is_posix_shell(argv[0]) and _command_flag_index(argv) is None: + result.extend(_commands(body, depth + 1)) # a heredoc fed to a shell is a script + elif not quoted: + for sub in _body_substitutions(body): + result.extend(_commands(sub, depth + 1)) + for script in scripts: + result.extend(_commands(script, depth + 1)) + result.extend(e for e in extra if e) + if argv: + result.append(argv) + for sub in substitutions: + result.extend(_commands(sub, depth + 1)) + return result + + +def _scan(text: str) -> tuple[str, list[str], list[tuple[bool, str]]]: + """Remove comments, lift substitutions out and cut heredoc bodies. + + Returns the remaining text, the substitution bodies, and ``(quoted, body)`` per heredoc. + Each heredoc operator is replaced by a ``__HEREDOC___`` word, so the caller knows + which command it feeds. + """ + out: list[str] = [] + substitutions: list[str] = [] + heredocs: list[tuple[bool, str]] = [] + pending: list[tuple[int, bool, str]] = [] # (index, strip tabs, delimiter); bodies start after the newline + i, n = 0, len(text) + quote: str | None = None + while i < n: + c = text[i] + if quote == "'": + out.append(_PROTECTED.get(c, c)) + quote = None if c == "'" else quote + i += 1 + elif c == "\\" and i + 1 < n: + nxt = text[i + 1] + out.append( + " " if nxt == "\n" else _PROTECTED[nxt] if quote is None and nxt in _SEP_CHARS else text[i : i + 2] + ) + i += 2 + elif (c == "'" and quote is None) or c == '"': + quote = None if quote == c else c + out.append(c) + i += 1 + elif (sub := _substitution_at(text, i, quote)) is not None: + i, body, word = sub + if body is not None: + substitutions.append(body) + out.append(word) + elif quote is not None: + out.append(_PROTECTED.get(c, c)) + i += 1 + elif text.startswith((">&", "&>"), i): + out.append(">") + i += 2 + elif c == "#" and (i == 0 or text[i - 1] in " \t\n;&|()"): + j = text.find("\n", i) + i = n if j < 0 else j + elif text.startswith("<<", i) and not text.startswith("<<<", i) and (m := _HEREDOC.match(text, i)): + quoted = m.group(2) is not None or m.group(3) is not None or m.group(4) == "\\" + delimiter = next(g for g in (m.group(2), m.group(3), m.group(5)) if g is not None) + pending.append((len(heredocs), m.group(1) == "-", delimiter)) + heredocs.append((quoted, "")) + out.append(f" __HEREDOC_{len(heredocs) - 1}__ ") + i = m.end() + elif c == "\n" and pending: + out.append("\n") + i = _read_heredoc_bodies(text, i + 1, pending, heredocs) + pending = [] + else: + out.append(c) + i += 1 + if quote is not None: + raise ShellSplitError("unterminated quote") + return "".join(out), substitutions, heredocs + + +def _substitution_at(text: str, i: int, quote: str | None) -> tuple[int, str | None, str] | None: + """A substitution starting at ``text[i]``: (index after it, body to parse or None, word for the outer command). + + Backticks and ``$(...)`` expand inside double quotes too; ``<(...)`` / ``>(...)`` only + outside quotes. ``$((...))`` is arithmetic: one word, nothing to parse. + """ + c = text[i] + if c == "`": + j = _closing_backtick(text, i + 1) + return j + 1, text[i + 1 : j], SUBST + if c == "$" and text.startswith("((", i + 1): + j = _closing_paren(text, i + 1) + return j + 1, None, text[i : j + 1].translate(_PROTECT) + if (c == "$" or (c in "<>" and quote is None)) and text.startswith("(", i + 1): + j = _closing_paren(text, i + 1) + return j + 1, text[i + 2 : j], SUBST + return None + + +def _read_heredoc_bodies( + text: str, i: int, pending: list[tuple[int, bool, str]], heredocs: list[tuple[bool, str]] +) -> int: + """Read the body of each pending heredoc from ``text[i]`` on, store it, and return the index after the last one.""" + n = len(text) + for k, strip_tabs, delimiter in pending: + body: list[str] = [] + while i < n: + j = text.find("\n", i) + line = text[i:] if j < 0 else text[i:j] + i = n if j < 0 else j + 1 + if (line.lstrip("\t") if strip_tabs else line) == delimiter: + break + body.append(line) + heredocs[k] = (heredocs[k][0], "\n".join(body)) + return i + + +def _closing_backtick(text: str, start: int) -> int: + i = start + while i < len(text): + if text[i] == "\\": + i += 2 + continue + if text[i] == "`": + return i + i += 1 + raise ShellSplitError("unterminated backtick") + + +def _closing_paren(text: str, open_idx: int) -> int: + """Index of the ``)`` that closes the ``(`` at ``open_idx``, skipping quoted text.""" + depth = 0 + i = open_idx + quote: str | None = None + while i < len(text): + c = text[i] + if quote == "'": + if c == "'": + quote = None + elif c == "\\": + i += 1 + elif c == "'" and quote is None: + quote = "'" + elif c == '"': + quote = None if quote == '"' else '"' + elif quote is None and c == "(": + depth += 1 + elif quote is None and c == ")": + depth -= 1 + if depth == 0: + return i + i += 1 + raise ShellSplitError("unbalanced $(") + + +def _body_substitutions(body: str) -> list[str]: + """The ``$(...)`` and backtick contents of an unquoted heredoc body: the only part the shell runs.""" + subs: list[str] = [] + i = 0 + try: + while i < len(body): + c = body[i] + if c == "\\": + i += 2 + continue + if c == "`": + j = _closing_backtick(body, i + 1) + subs.append(body[i + 1 : j]) + i = j + 1 + continue + if c == "$" and body.startswith("(", i + 1) and not body.startswith("((", i + 1): + j = _closing_paren(body, i + 1) + subs.append(body[i + 2 : j]) + i = j + 1 + continue + i += 1 + except ShellSplitError: + pass # prose with a stray backtick or `$(`: keep what was found + return subs + + +def _split(top: str) -> list[list[str]]: + """Tokenize with shell quoting and cut the tokens into commands at the operators.""" + lexer = shlex.shlex(top, posix=True, punctuation_chars=_SEP_CHARS) + lexer.whitespace = " \t\r" + lexer.whitespace_split = True + lexer.commenters = "" + try: + tokens = list(lexer) + except ValueError as e: + raise ShellSplitError(str(e)) from e + commands: list[list[str]] = [] + current: list[str] = [] + for tok in tokens: + if tok and all(ch in _SEP_CHARS for ch in tok): + if current: + commands.append(current) + current = [] + else: + current.append(tok.translate(_UNPROTECT)) + if current: + commands.append(current) + return commands + + +def _strip_redirections(argv: list[str]) -> list[str]: + result: list[str] = [] + skip = False + for tok in argv: + if skip: + skip = False + elif _REDIRECT_OP.match(tok): + skip = True + elif not _REDIRECT_WITH_TARGET.match(tok): + result.append(tok) + return result + + +def _is_posix_shell(arg0: str) -> bool: + return program_name(arg0) in _POSIX_SHELLS + + +def _command_flag_index(argv: list[str]) -> int | None: + """Index of a POSIX shell's ``-c`` option cluster (``-c``, ``-lc``, ``-ic``), or None.""" + for i, tok in enumerate(argv[1:], 1): + if len(tok) >= 2 and tok[0] == "-" and tok[1] != "-" and tok[1:].isalpha() and "c" in tok[1:]: + return i + if not tok.startswith("-"): + return None + return None + + +def _skip_options(argv: list[str], with_argument: frozenset[str]) -> list[str]: + """``argv`` without its leading options; an option in ``with_argument`` also takes the next token.""" + while argv and argv[0].startswith("-") and argv[0] != "-": + argv = argv[2:] if argv[0] in with_argument else argv[1:] + return argv + + +def _unwrap(argv: list[str]) -> tuple[list[str], list[str], list[list[str]]]: + """Strip keywords and wrappers. Returns (argv, scripts to parse, extra commands).""" + scripts: list[str] = [] + extra: list[list[str]] = [] + while argv: + name = program_name(argv[0]) + if argv[0] in _KEYWORDS: + argv = argv[1:] + elif argv[0] in _HEADER_KEYWORDS: + return [], scripts, extra # `for x in a b` lists words, it runs nothing + elif name in _PLAIN_WRAPPERS: + argv = argv[1:] + elif name in _FLAG_WRAPPERS: + argv = _skip_options(argv[1:], _FLAG_WRAPPERS[name]) + if name == "timeout": + argv = argv[1:] # the duration + elif name == "eval": + scripts.append(" ".join(argv[1:])) + return [], scripts, extra + elif _is_posix_shell(argv[0]) and (k := _command_flag_index(argv)) is not None: + rest = argv[k + 1 :] + # A recorded argv-joined form (`bash -lc uip flow debug`) arrives unquoted, + # so more than one word after the flag is read as the script. + if rest: + scripts.append(" ".join(rest)) + return [], scripts, extra + else: + break + if argv and program_name(argv[0]) == "find": + argv, extra = _split_find_exec(argv) + return argv, scripts, extra + + +def _split_find_exec(argv: list[str]) -> tuple[list[str], list[list[str]]]: + """``find`` without its ``-exec CMD ;`` actions, and each ``CMD`` as a command of its own.""" + kept: list[str] = [] + commands: list[list[str]] = [] + i = 0 + while i < len(argv): + if argv[i] in ("-exec", "-execdir", "-ok", "-okdir"): + j = i + 1 + while j < len(argv) and argv[j] not in (";", "+"): + j += 1 + commands.append(_unwrap(argv[i + 1 : j])[0]) + i = j + 1 + else: + kept.append(argv[i]) + i += 1 + return kept, commands diff --git a/tests/test_command_executed_simple_commands.py b/tests/test_command_executed_simple_commands.py new file mode 100644 index 000000000..4f89ec3b4 --- /dev/null +++ b/tests/test_command_executed_simple_commands.py @@ -0,0 +1,333 @@ +"""Tests for ``match_on: simple_commands`` on CommandExecutedCriterion and its shell splitter.""" + +import time +from datetime import datetime + +import pytest + +from coder_eval.criteria.command_executed import CommandExecutedChecker +from coder_eval.models import CommandExecutedCriterion +from coder_eval.models.results import TurnRecord +from coder_eval.models.telemetry import CommandTelemetry +from coder_eval.shell_commands import SUBST, ShellSplitError, simple_commands + + +def _texts(text: str) -> set[str]: + return {" ".join(argv) for argv in simple_commands(text)} + + +def _turn(*commands: str | list[str], tool_name: str = "Bash") -> list[TurnRecord]: + return [ + TurnRecord( + iteration=1, + user_input="test", + agent_output="ok", + commands=[ + CommandTelemetry( + tool_name=tool_name, + tool_id=f"tool-{i}", + timestamp=datetime.now(), + parameters={"command": c}, + result_status="success", + ) + for i, c in enumerate(commands) + ], + ) + ] + + +def _check(turns: list[TurnRecord], **fields): + criterion = CommandExecutedCriterion(description="t", match_on="simple_commands", **fields) + return CommandExecutedChecker().check(criterion, None, turn_records=turns) + + +VOICE = r"^(\S*/)?uip (maestro )?flow debug\b" + + +class TestHeredocs: + def test_quoted_delimiter_drops_the_whole_body(self): + assert _texts("cat > a.md <<'EOF'\nuip flow debug $(uip x)\nEOF\nuip flow pack") == {"cat", "uip flow pack"} + + def test_double_quoted_and_escaped_delimiters_are_quoted(self): + assert _texts('cat <<"EOF"\nuip a\nEOF') == {"cat"} + assert _texts("cat <<\\EOF\nuip a\nEOF") == {"cat"} + + def test_unquoted_body_keeps_only_substitutions(self): + text = "cat > a.md </dev/null") == {f"diff {SUBST} {SUBST}", "uip a", "uip b"} + + def test_substitution_inside_double_quotes(self): + assert _texts('echo "id=$(uip a)"') == {f"echo id={SUBST}", "uip a"} + + def test_arithmetic_is_not_a_command(self): + assert _texts("echo $((1 + 2))") == {"echo $((1 + 2))"} + + def test_single_quotes_do_not_expand(self): + assert _texts("echo '$(uip a)'") == {"echo $(uip a)"} + + def test_shell_dash_c_string_is_parsed(self): + assert _texts('bash -lc "cd /x && uip flow debug \\"a b\\""') == {"cd /x", "uip flow debug a b"} + assert _texts("sh -c 'uip a; uip b'") == {"uip a", "uip b"} + + def test_argv_joined_dash_c_form(self): + assert _texts("bash -lc uip flow debug x") == {"uip flow debug x"} + + def test_eval_is_parsed(self): + assert _texts("eval 'uip a; uip b'") == {"uip a", "uip b"} + + +class TestWrappers: + def test_wrappers_with_flags_are_stripped(self): + text = "timeout -s KILL 60 sudo -u me nohup nice -n 5 stdbuf -oL uip flow debug a" + assert _texts(text) == {"uip flow debug a"} + + def test_exec_command_time_builtin(self): + assert _texts("exec uip a; command uip b; time -p uip c; builtin echo d") == { + "uip a", + "uip b", + "uip c", + "echo d", + } + + def test_xargs_with_flags(self): + assert _texts("ls | xargs -I{} -n1 -P 4 uip y {}") == {"ls", "uip y {}"} + + def test_find_exec_is_its_own_command(self): + assert _texts(r"find . -name x -exec timeout 5 uip flow debug {} \; -print") == { + "find . -name x -print", + "uip flow debug {}", + } + assert _texts("find . -exec rm {} + ; find . -execdir uip a ';'") == {"find .", "rm {}", "uip a"} + + def test_assignments_and_env_stay_visible(self): + assert _texts("env -u UIPATH_STUDIO_PID uip rpa build; X=1 Y=2 uip x") == { + "env -u UIPATH_STUDIO_PID uip rpa build", + "X=1 Y=2 uip x", + } + + def test_stripping_stops_at_an_assignment(self): + assert _texts("timeout 5 X=1 uip a") == {"X=1 uip a"} + + +class TestSplitting: + def test_operators_split(self): + assert _texts("uip a; uip b && uip c || uip d | uip e & uip f\nuip g |& uip h") == { + f"uip {c}" for c in "abcdefgh" + } + + def test_subshell_and_group(self): + assert _texts("(cd x && uip a) ; { uip b; }") == {"cd x", "uip a", "uip b"} + + def test_keywords_are_not_commands(self): + assert _texts("if [ -f x ]; then uip z; elif true; then :; else uip y; fi") == { + "[ -f x ]", + "uip z", + "true", + ":", + "uip y", + } + assert _texts("while ! uip ping; do sleep 1; done") == {"uip ping", "sleep 1"} + + def test_loop_header_is_not_a_command_and_variables_are_not_expanded(self): + assert _texts("for t in 'flow debug' b; do uip $t; done") == {"uip $t"} + + def test_redirections_are_dropped(self): + assert _texts("uip a > out.txt 2>&1; uip b 2>/dev/null >>log &> all") == {"uip a", "uip b"} + + def test_backslash_continuation(self): + assert _texts("uip flow \\\n debug x") == {"uip flow debug x"} + + +class TestQuotingAndComments: + def test_quotes_are_resolved(self): + assert _texts("uip 'flow' \"debug\" a\\ b") == {"uip flow debug a b"} + + def test_quoted_operators_are_words(self): + assert _texts("echo ';' 'a|b' \"x && y\" a\\;b; uip z") == {"echo ; a|b x && y a;b", "uip z"} + + def test_echo_string_is_an_argument(self): + assert _texts('echo "uip flow debug x"') == {"echo uip flow debug x"} + + def test_comments_are_dropped(self): + assert _texts("uip a # then uip flow debug\n# uip b\nuip c") == {"uip a", "uip c"} + + def test_hash_inside_a_word_is_not_a_comment(self): + assert _texts("echo a#b $#") == {"echo a#b $#"} + + def test_unterminated_quote_is_unparseable(self): + with pytest.raises(ShellSplitError): + simple_commands("echo 'oops") + with pytest.raises(ShellSplitError): + simple_commands("echo $(uip a") + + +class TestLinearTime: + @pytest.mark.parametrize( + "unit", + [ + "uip flow debug a && echo 'x;y' | tee log\n", + "cat < float: + text = unit * (chars // len(unit) + 1) + best = float("inf") + for _ in range(3): + start = time.perf_counter() + simple_commands(text) + best = min(best, time.perf_counter() - start) + return best + + assert cost(2000) < 0.1 + small, large = cost(20_000), cost(80_000) + assert large < 8 * small + 0.01 # x4 input: linear, with slack for noise + + +class TestChecker: + def test_heredoc_mention_does_not_trip_a_guard(self): + turns = _turn("cat > notes.md <<'EOF'\nNext: uip flow debug\nEOF", "echo 'uip flow debug' >> x") + assert _check(turns, command_pattern=VOICE, min_count=0, max_count=0).score == 1.0 + + def test_real_call_trips_the_guard(self): + turns = _turn("cd proj && timeout 60 uip maestro flow debug f.flow --output json") + result = _check(turns, command_pattern=VOICE, min_count=0, max_count=0) + assert result.score == 0.0 + assert "uip maestro flow debug f.flow --output json" in result.details + + def test_default_match_on_keeps_raw_matching(self): + turns = _turn("cat > notes.md <<'EOF'\nuip flow debug\nEOF") + criterion = CommandExecutedCriterion( + description="t", command_pattern="uip flow debug", min_count=0, max_count=0 + ) + assert criterion.match_on == "command_text" + assert CommandExecutedChecker().check(criterion, None, turn_records=turns).score == 0.0 + + def test_counts_per_simple_command(self): + turns = _turn("uip solution pack a && uip solution pack b", "echo 'uip solution pack'") + result = _check(turns, command_pattern=r"^uip solution pack\b", min_count=2) + assert result.score == 1.0 + assert "Matched 2/2" in result.details + assert _check(turns, command_pattern=r"^uip solution pack\b", max_count=1).score == 0.0 + + def test_exclude_applies_per_simple_command(self): + turns = _turn("uip a --dry-run; uip a") + result = _check(turns, command_pattern="^uip a", exclude_pattern="--dry-run", min_count=1, max_count=1) + assert result.score == 1.0 + + def test_env_assignment_visible_to_the_pattern(self): + turns = _turn("env -u UIPATH_STUDIO_PID uip rpa build .") + assert _check(turns, command_pattern=r"^env -u UIPATH_STUDIO_PID uip rpa build").score == 1.0 + + def test_unparseable_falls_back_to_raw_and_says_so(self): + turns = _turn("echo 'oops; uip flow debug x") + result = _check(turns, command_pattern="uip flow debug", min_count=1) + assert result.score == 1.0 + assert "1 call(s) matched on raw text (1 not splittable into simple commands)" in result.details + + @pytest.mark.parametrize( + "command", + [ + "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'echo uip flow debug'", + "pwsh -Command \"Write-Output 'x'; uip flow debug\"", + "cd x; powershell.exe -c 'uip flow debug'", + ], + ) + def test_powershell_falls_back_to_raw(self, command): + result = _check(_turn(command), command_pattern="uip flow debug", min_count=1) + assert result.score == 1.0 + assert "not POSIX shell" in result.details + + def test_powershell_tool_falls_back_to_raw(self): + turns = _turn("Write-Host 'a'; uip flow debug", tool_name="ExecutePowershellCommand") + result = _check(turns, command_pattern="uip flow debug", min_count=1) + assert "not POSIX shell" in result.details + + def test_argv_list_is_split(self): + turns = _turn(["/bin/zsh", "-lc", "cat <<'EOF'\nuip flow debug\nEOF\nuip flow pack"]) + assert _check(turns, command_pattern=VOICE, min_count=0, max_count=0).score == 1.0 + assert _check(turns, command_pattern=r"^uip flow pack$").score == 1.0 + + def test_non_shell_tool_json_is_matched_as_before(self): + turns = [ + TurnRecord( + iteration=1, + user_input="test", + agent_output="ok", + commands=[ + CommandTelemetry( + tool_name="Write", + tool_id="w", + timestamp=datetime.now(), + parameters={"file_path": "a.sh", "content": "uip flow debug"}, + result_status="success", + ) + ], + ) + ] + assert _check(turns, tool_name="Write", command_pattern="uip flow debug").score == 1.0 + + def test_live_verdict_counts_like_the_score(self): + turns = _turn("uip a; uip a", "cat <<'EOF'\nuip a\nEOF") + criterion = CommandExecutedCriterion( + description="t", match_on="simple_commands", command_pattern="^uip a$", max_count=1 + ) + assert CommandExecutedChecker().live_verdict(criterion, turns) == "fail" + guard = CommandExecutedCriterion( + description="t", match_on="simple_commands", command_pattern="^uip b", min_count=0, max_count=0 + ) + assert CommandExecutedChecker().live_verdict(guard, turns) == "undecided" + + def test_legacy_command_not_executed_keeps_match_on(self): + from coder_eval.models import SandboxConfig, TaskDefinition + + td = TaskDefinition( + task_id="t", + description="d", + initial_prompt="p", + agent=None, + sandbox=SandboxConfig(driver="tempdir"), + success_criteria=[ + { + "type": "command_not_executed", + "description": "no debug", + "command_pattern": VOICE, + "match_on": "simple_commands", + } + ], + ) + criterion = td.success_criteria[0] + assert isinstance(criterion, CommandExecutedCriterion) + assert (criterion.match_on, criterion.max_count) == ("simple_commands", 0) From df82240f9fb9a15c2d57db01deebca192915bb0e Mon Sep 17 00:00:00 2001 From: CarlesUIPath Date: Wed, 25 Nov 2026 18:22:44 +0000 Subject: [PATCH 2/3] fix(criteria): simple_commands parses find -exec sh -c and X=1 bash -c, keeps quoted < > as words, treats unwrapped PowerShell as non-POSIX Co-Authored-By: Claude Opus 5.5 --- docs/TASK_DEFINITION_GUIDE.md | 6 +- plugins/coder-eval/reference/criteria.md | 11 ++- src/coder_eval/criteria/command_executed.py | 8 +- src/coder_eval/shell_commands.py | 95 +++++++++++++------ .../test_command_executed_simple_commands.py | 30 +++++- 5 files changed, 107 insertions(+), 43 deletions(-) diff --git a/docs/TASK_DEFINITION_GUIDE.md b/docs/TASK_DEFINITION_GUIDE.md index 7db2a46fb..33d69c3ba 100644 --- a/docs/TASK_DEFINITION_GUIDE.md +++ b/docs/TASK_DEFINITION_GUIDE.md @@ -1081,9 +1081,9 @@ With a pattern, `tool_name: null` searches the command of a shell call, not the How the call is split: - **Not commands:** heredoc bodies, comments, and the words of a `for`/`select`/`case` header. A `<<'EOF'` body (quoted delimiter) is dropped whole. Of a `< tuple[str, ...] | str: Rationale: .claude/notes/contracts.md § Matching on simple commands """ - if _NON_POSIX_PREFIX.match(cmd_text): + if _NON_POSIX_PREFIX.match(cmd_text) or _POWERSHELL_ENV.search(cmd_text): return _NOT_POSIX try: argvs = simple_commands(cmd_text) except (ShellSplitError, RecursionError): return _UNPARSEABLE - if any(program_name(argv[0]) in NON_POSIX_SHELLS for argv in argvs): + if any(program_name(argv[0]) in NON_POSIX_SHELLS or _POWERSHELL_CMDLET.fullmatch(argv[0]) for argv in argvs): return _NOT_POSIX return tuple(" ".join(argv) for argv in argvs) diff --git a/src/coder_eval/shell_commands.py b/src/coder_eval/shell_commands.py index 7561fbdd1..4dcc6f7eb 100644 --- a/src/coder_eval/shell_commands.py +++ b/src/coder_eval/shell_commands.py @@ -24,9 +24,10 @@ _MAX_DEPTH = 6 _SEP_CHARS = ";&|()\n" -# A quoted or escaped operator character is a word character. The scan swaps it for a -# private-use stand-in, so shlex cannot split on it, and the split swaps it back. -_PROTECTED = {ch: chr(0xE000 + k) for k, ch in enumerate(_SEP_CHARS)} +# A quoted or escaped operator or redirection character is a word character. The scan swaps +# it for a private-use stand-in, so shlex cannot split on it and it is not read as a +# redirection; the stand-in is swapped back once redirections are stripped. +_PROTECTED = {ch: chr(0xE000 + k) for k, ch in enumerate(_SEP_CHARS + "<>")} _PROTECT = str.maketrans(_PROTECTED) _UNPROTECT = str.maketrans({v: k for k, v in _PROTECTED.items()}) _HEREDOC = re.compile(r"<<(-?)[ \t]*(?:'([^'\n]*)'|\"([^\"\n]*)\"|(\\?)([A-Za-z0-9_.\-]+))") @@ -73,27 +74,38 @@ def _commands(text: str, depth: int) -> list[list[str]]: raise ShellSplitError("nested deeper than the limit") top, substitutions, heredocs = _scan(text) result: list[list[str]] = [] - for argv in _split(top): - heredoc_ids = [int(m.group(1)) for t in argv if (m := _HEREDOC_MARK.match(t))] - argv = _strip_redirections([t for t in argv if not _HEREDOC_MARK.match(t)]) - argv, scripts, extra = _unwrap(argv) - for k in heredoc_ids: - quoted, body = heredocs[k] - if argv and _is_posix_shell(argv[0]) and _command_flag_index(argv) is None: - result.extend(_commands(body, depth + 1)) # a heredoc fed to a shell is a script - elif not quoted: - for sub in _body_substitutions(body): - result.extend(_commands(sub, depth + 1)) - for script in scripts: - result.extend(_commands(script, depth + 1)) - result.extend(e for e in extra if e) - if argv: - result.append(argv) + for index, argv in enumerate(_split(top)): + fed = [heredocs[int(m.group(1))] for t in argv if (m := _HEREDOC_MARK.match(t))] + words = _strip_redirections([t for t in argv if not _HEREDOC_MARK.match(t)]) + argv = [t.translate(_UNPROTECT) for t in words] + result.extend(_argv_commands(argv, fed, depth, joined=depth == 0 and index == 0)) for sub in substitutions: result.extend(_commands(sub, depth + 1)) return result +def _argv_commands(argv: list[str], fed: list[tuple[bool, str]], depth: int, *, joined: bool) -> list[list[str]]: + """The commands one split-out argv runs: itself unwrapped, its scripts, ``find -exec`` actions and fed heredocs. + + ``joined``: the argv starts the recorded text, so a shell ``-c`` may be in the argv-joined form. + """ + argv, scripts, actions = _unwrap(argv, joined=joined) + result: list[list[str]] = [] + for quoted, body in fed: + if argv and _is_posix_shell(argv[0]) and _command_flag_index(argv) is None: + result.extend(_commands(body, depth + 1)) # a heredoc fed to a shell is a script + elif not quoted: + for sub in _body_substitutions(body): + result.extend(_commands(sub, depth + 1)) + for script in scripts: + result.extend(_commands(script, depth + 1)) + for action in actions: + result.extend(_argv_commands(action, [], depth, joined=False)) + if argv: + result.append(argv) + return result + + def _scan(text: str) -> tuple[str, list[str], list[tuple[bool, str]]]: """Remove comments, lift substitutions out and cut heredoc bodies. @@ -116,7 +128,7 @@ def _scan(text: str) -> tuple[str, list[str], list[tuple[bool, str]]]: elif c == "\\" and i + 1 < n: nxt = text[i + 1] out.append( - " " if nxt == "\n" else _PROTECTED[nxt] if quote is None and nxt in _SEP_CHARS else text[i : i + 2] + " " if nxt == "\n" else _PROTECTED[nxt] if quote is None and nxt in _PROTECTED else text[i : i + 2] ) i += 2 elif (c == "'" and quote is None) or c == '"': @@ -275,7 +287,7 @@ def _split(top: str) -> list[list[str]]: commands.append(current) current = [] else: - current.append(tok.translate(_UNPROTECT)) + current.append(tok) if current: commands.append(current) return commands @@ -315,8 +327,13 @@ def _skip_options(argv: list[str], with_argument: frozenset[str]) -> list[str]: return argv -def _unwrap(argv: list[str]) -> tuple[list[str], list[str], list[list[str]]]: - """Strip keywords and wrappers. Returns (argv, scripts to parse, extra commands).""" +def _unwrap(argv: list[str], *, joined: bool) -> tuple[list[str], list[str], list[list[str]]]: + """Strip keywords and wrappers. Returns (argv, scripts to parse, ``find -exec`` actions). + + With ``joined``, every word after a leading shell's ``-c`` is the script: Codex rollout + recovery records argv joined without re-quoting (``bash -lc uip flow debug``). Anywhere + else only the next word is the script, as in the shell (``sh -c 'cmd "$1"' _ {}``). + """ scripts: list[str] = [] extra: list[list[str]] = [] while argv: @@ -335,19 +352,39 @@ def _unwrap(argv: list[str]) -> tuple[list[str], list[str], list[list[str]]]: scripts.append(" ".join(argv[1:])) return [], scripts, extra elif _is_posix_shell(argv[0]) and (k := _command_flag_index(argv)) is not None: - rest = argv[k + 1 :] - # A recorded argv-joined form (`bash -lc uip flow debug`) arrives unquoted, - # so more than one word after the flag is read as the script. + rest = argv[k + 1 :] if joined else argv[k + 1 : k + 2] if rest: scripts.append(" ".join(rest)) return [], scripts, extra else: break - if argv and program_name(argv[0]) == "find": - argv, extra = _split_find_exec(argv) + prefix = _assignment_prefix_len(argv) + program = argv[prefix:] + if program and _is_posix_shell(program[0]) and (k := _command_flag_index(program)) is not None: + # `X=1 bash -c '...'`: the assignments stay, the script is parsed. + scripts.extend(program[k + 1 : k + 2]) + argv = [*argv[: prefix + k + 1], SUBST] + elif program and program_name(program[0]) == "find": + kept, extra = _split_find_exec(program) + argv = argv[:prefix] + kept return argv, scripts, extra +def _assignment_prefix_len(argv: list[str]) -> int: + """How many leading words are assignments or ``env`` with its options and assignments.""" + i = 0 + while i < len(argv): + if _ASSIGNMENT.match(argv[i]): + i += 1 + elif program_name(argv[i]) == "env": + i += 1 + while i < len(argv) and (argv[i].startswith("-") or _ASSIGNMENT.match(argv[i])): + i += 2 if argv[i] in ("-u", "--unset", "-C", "--chdir", "-S", "--split-string") else 1 + else: + break + return i + + def _split_find_exec(argv: list[str]) -> tuple[list[str], list[list[str]]]: """``find`` without its ``-exec CMD ;`` actions, and each ``CMD`` as a command of its own.""" kept: list[str] = [] @@ -358,7 +395,7 @@ def _split_find_exec(argv: list[str]) -> tuple[list[str], list[list[str]]]: j = i + 1 while j < len(argv) and argv[j] not in (";", "+"): j += 1 - commands.append(_unwrap(argv[i + 1 : j])[0]) + commands.append(argv[i + 1 : j]) i = j + 1 else: kept.append(argv[i]) diff --git a/tests/test_command_executed_simple_commands.py b/tests/test_command_executed_simple_commands.py index 4f89ec3b4..4232f063b 100644 --- a/tests/test_command_executed_simple_commands.py +++ b/tests/test_command_executed_simple_commands.py @@ -1,5 +1,6 @@ """Tests for ``match_on: simple_commands`` on CommandExecutedCriterion and its shell splitter.""" +import gc import time from datetime import datetime @@ -129,6 +130,18 @@ def test_find_exec_is_its_own_command(self): } assert _texts("find . -exec rm {} + ; find . -execdir uip a ';'") == {"find .", "rm {}", "uip a"} + def test_find_exec_shell_script_is_parsed(self): + assert _texts("find . -name '*.flow' -exec sh -c 'uip flow validate \"$1\"' _ {} \\;") == { + "find . -name *.flow", + "uip flow validate $1", + } + + def test_assignment_before_a_shell_keeps_the_assignment_and_parses_the_script(self): + assert _texts("X=1 env -u Y bash -lc 'uip a && uip b'") == {f"X=1 env -u Y bash -lc {SUBST}", "uip a", "uip b"} + + def test_assignment_before_find_exec(self): + assert _texts("X=1 find . -exec uip a {} +") == {"X=1 find .", "uip a {}"} + def test_assignments_and_env_stay_visible(self): assert _texts("env -u UIPATH_STUDIO_PID uip rpa build; X=1 Y=2 uip x") == { "env -u UIPATH_STUDIO_PID uip rpa build", @@ -175,6 +188,9 @@ def test_quotes_are_resolved(self): def test_quoted_operators_are_words(self): assert _texts("echo ';' 'a|b' \"x && y\" a\\;b; uip z") == {"echo ; a|b x && y a;b", "uip z"} + def test_quoted_redirection_characters_are_words(self): + assert _texts("grep '>' file.txt; uip a \\< b \"\"") == {"grep > file.txt", "uip a < b "} + def test_echo_string_is_an_argument(self): assert _texts('echo "uip flow debug x"') == {"echo uip flow debug x"} @@ -205,10 +221,14 @@ def test_time_grows_linearly(self, unit): def cost(chars: int) -> float: text = unit * (chars // len(unit) + 1) best = float("inf") - for _ in range(3): - start = time.perf_counter() - simple_commands(text) - best = min(best, time.perf_counter() - start) + gc.disable() # a collection pause is not the splitter's cost + try: + for _ in range(5): + start = time.process_time() + simple_commands(text) + best = min(best, time.process_time() - start) + finally: + gc.enable() return best assert cost(2000) < 0.1 @@ -263,6 +283,8 @@ def test_unparseable_falls_back_to_raw_and_says_so(self): "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'echo uip flow debug'", "pwsh -Command \"Write-Output 'x'; uip flow debug\"", "cd x; powershell.exe -c 'uip flow debug'", + "$env:UIPATH_STUDIO_PID = $null; uip flow debug x", + "Get-Content a.txt; uip flow debug x", ], ) def test_powershell_falls_back_to_raw(self, command): From 3df13d261708fa602940d9b73c5c52088f26b89c Mon Sep 17 00:00:00 2001 From: CarlesUIPath Date: Wed, 25 Nov 2026 19:41:03 +0000 Subject: [PATCH 3/3] fix(criteria): simple_commands heredoc mark out of band, any splitter error falls back to raw - The heredoc mark is a private-use code point, not `__HEREDOC___`: a literal `__HEREDOC_0__` word in agent text raised IndexError (score 0.0, early stop disarmed) or fed a real heredoc body to the wrong command. A text that holds one of the splitter's own marks (U+E000-U+E007, U+E0FF) is not split; other private-use code points (Codex citation marks) are words. - Any exception from the splitter falls back to raw matching, logged and named in the details (`splitter error `), instead of failing the check. - A heredoc fed to a shell behind assignments or `env` (`X=1 bash <F, 21 F->P (as before); crash scan of 146,745 calls: 0 exceptions. Co-Authored-By: Claude Opus 5.5 --- .claude/notes/contracts.md | 12 ++- docs/TASK_DEFINITION_GUIDE.md | 4 +- plugins/coder-eval/reference/criteria.md | 6 +- src/coder_eval/criteria/command_executed.py | 80 +++++++----------- src/coder_eval/models/criteria.py | 14 ++-- src/coder_eval/shell_commands.py | 83 +++++++++++++------ tests/lint/live_verdict_contract.py | 21 +++++ .../test_command_executed_simple_commands.py | 62 +++++++++++++- 8 files changed, 195 insertions(+), 87 deletions(-) diff --git a/.claude/notes/contracts.md b/.claude/notes/contracts.md index 19bb92513..c02f17160 100644 --- a/.claude/notes/contracts.md +++ b/.claude/notes/contracts.md @@ -147,7 +147,17 @@ lab ticket 526): on one real run plus a mention in a report. Text that cannot be split falls back to raw matching for that call, and the details say so. -So a parse failure never turns a match into a miss without notice. +So a parse failure never turns a match into a miss without notice. Any other exception from +the splitter falls back the same way (logged, reason `splitter error `): a splitter +bug must not score a guard 0.0, nor disarm early stop for every criterion of the task. + +The splitter's own marks (operator stand-ins, heredoc positions) are private-use code points, +and a text that holds one of those is not split. Only those: Codex commands do hold other +private-use code points (citation marks; 3 calls in 18 nightlies). A mark written as ASCII (`__HEREDOC_0__`) was agent +text too: a literal one raised IndexError or fed a real heredoc body to the wrong command. + +Stdin piped into a shell (`cat < bool: - """True if argv[0]'s basename looks like a POSIX shell. - - A predicate rather than an enumerated allowlist: the set of shells is open - (``bash``/``sh`` on Linux, ``zsh`` on macOS — Codex shells through the host's - login shell, see codex_agent.py — plus ``dash``/``ksh``/…), and every common - shell basename ends in ``sh``. Matching is additive (the raw text stays a - haystack), so favouring recall over a hand-maintained list is safe. - """ - return arg0.rsplit("/", 1)[-1].endswith("sh") - - -def _is_command_flag(tok: str) -> bool: - """True for a short-option cluster carrying a ``-c`` command string. - - Covers ``-c``, ``-lc``, ``-ic``, ``-lic`` (login/interactive + command) in - any order — a single ``-``-prefixed token whose option letters are all - alphabetic and include ``c``. ``--long`` options and ``-o=val`` forms are - rejected, so this is the first flag that actually introduces the command - string. The combined and split (``bash -l -c``) forms both work: a non-``c`` - short flag like ``-l`` simply isn't the command flag and the scan continues. - """ - return len(tok) >= 2 and tok[0] == "-" and tok[1] != "-" and tok[1:].isalpha() and "c" in tok[1:] - - @lru_cache(maxsize=1024) def _normalize_shell(cmd_text: str) -> str | None: """Quote-resolved, wrapper-stripped form of a shell command, or None. @@ -94,26 +76,21 @@ def _normalize_shell(cmd_text: str) -> str | None: if not tokens: return None # Unwrap `bash -lc "