Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier3): end feedback chat URL spans where a path after them can start (#389)

Narendran Raghavanecd09e553b7c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d18efb2..b23abe54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -142,17 +142,32 @@ All notable changes to SkillEvaluator are documented in this file.
the default `legacy` policy.
- `skillevaluator tier3 feedback` now writes the evaluated skill's directory
- (known from `--skill` or a run in the skill's `evals/results`) as its name
- and the home directory as `~` in the evidence it sends to the LLM, so an
- error naming the skill's `SKILL.md` no longer shows its local path. A copied
- run's path starting with `~user/` or `$HOME/` is now also replaced with the
- run ID. Path masking now skips a URL other than a `file:` URL together with
- any text after it up to the next whitespace, so in minified JSON a run,
- skill, or home path that follows such a URL is sent as is, where 0.8.0
- replaced the run's path with the run ID. A field over 65,536 characters with
- no whitespace after its limit now keeps a masked prefix, cut at punctuation
- such as `,` or `}` but never inside a URL's user info or host, so `Error: `
- followed by minified JSON no longer arrives as `Error: ...<truncated>`.
+ (known from `--skill` or a run in the skill's `evals/results`) as its name and
+ the home directory as `~` in the evidence it sends to the LLM, so an error
+ naming the skill's `SKILL.md` no longer shows its local path. A copied run's
+ path starting with `~user/` or `$HOME/` is now also replaced with the run ID.
+ Path masking now leaves a URL unchanged, even when its query or fragment names
+ a local path, unless its scheme is `file:` or ends in `+file:`, such as
+ `git+file:`. The URL ends at whitespace, a quote, `<`, `>`, a backtick, `^`,
+ `{`, `|`, `}`, or an ANSI escape, at a `\n`, `\r`, or `\t` escape, and before
+ an absolute path or another scheme after a `,` or `;` (also with a name such
+ as `LOG=` or `--find-links=`) or a Markdown `](`, so a run, skill, or home
+ path after it in minified JSON, on the next line of an escaped env dump, or in
+ a `,`- or `;`-separated list is still masked, and so is a `file:` URL after
+ it. A Windows path in a URL is kept, also with a folder whose name starts with
+ `n`, `r`, or `t`, such as `\runs\` or `\t\`, unless that name holds a
+ character other than a letter, a digit, `_`, `.`, `~`, `$`, `%`, or `-`, such
+ as `\runs(old)\`, or no backslash follows it, as in `\notes.txt`; the URL then
+ ends there. A copied run's path right after a `\n`, `\r`, or `\t` escape or an
+ ANSI code, such as a color or erase-line code, is now replaced with the run
+ ID, and the escape or code is kept, also with no URL before it. 0.8.0 sent
+ such a path as is after a word, as in `done.\n/srv/...`, or after a raw ANSI
+ code, and replaced an escape or an escaped code with it otherwise. A relative
+ path after such an escape is no longer read as an absolute one. A field over
+ 65,536 characters with no whitespace after its limit now keeps a masked
+ prefix, cut at punctuation such as `,` or `}` but never inside a URL's user
+ info or host, so `Error: ` followed by minified JSON no longer arrives as
+ `Error: ...<truncated>`.
- Tier 3 security grading again warns about network exfiltration, lowering
the Security score to 0.5, for an HTTPie method word after a capitalized
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index 1bc4958a..5025f336 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -636,22 +636,47 @@ the configured model. Type `exit` or press Ctrl-D to end the chat. Ctrl-C
during an answer discards that question and returns to the prompt.
The chat uses the provider and model configured for LLM checks
-(`SKILL_EVAL_LLM_PROVIDER` and `SKILL_EVAL_LLM_MODEL`; see
-[Environment Variables](environment-variables.mdx)). Each question sends the
-run's compact evidence to that provider. The evidence names the run by its ID
-instead of its local path. In every text field, such as errors, warnings, case
-questions and saved feedback, an absolute path that ends in the run's directory
-is replaced with that ID. This covers the path a copied run had on the machine
-where it ran, also when it starts with `~user/`, `$HOME/`, `${HOME}/` or
-`%USERPROFILE%\`, unless that path contains a space. A path joined to it, such as
-`/usr/bin` in `PATH=/usr/bin:/home/ci/results/RUN_ID`, is kept. A root right after
-`,` `;` `:` `=` `(` `[` or `{` starts a new path, so a directory name that ends in
-one of those characters before a `/` is read as two paths and only the second is
-replaced. The evaluated skill's directory
-is replaced with its name and your home directory with `~`; the skill directory
-is known when you pass `--skill` or the run is in the skill's `evals/results`
-directory. Credential-shaped text is redacted before the text is shortened, and
-a shortened field ends in `...<truncated>`. The command writes nothing to disk.
+(`SKILL_EVAL_LLM_PROVIDER` and `SKILL_EVAL_LLM_MODEL`; see [Environment
+Variables](environment-variables.mdx)). Each question sends the run's compact
+evidence to that provider. The evidence names the run by its ID instead of its
+local path. In every text field, such as errors, warnings, case questions and
+saved feedback, an absolute path that ends in the run's directory is replaced
+with that ID. This covers the path a copied run had on the machine where it ran,
+also when it starts with `~user/`, `$HOME/`, `${HOME}/` or `%USERPROFILE%\`,
+unless that path contains a space. A path joined to it, such as `/usr/bin` in
+`PATH=/usr/bin:/home/ci/results/RUN_ID`, is kept. A root right after `,` `;` `:`
+`=` `(` `[` or `{` starts a new path, so a directory name that ends in one of
+those characters before a `/` is read as two paths and only the second is
+replaced. So does a root right after a `\n`, `\r` or `\t` escape in JSON or repr
+text, such as the next line of an env dump, also with ANSI codes after the
+escape, as on a progress line (`\r\u001b[K`); a relative path after one is kept,
+and a UNC server name that starts with `n`, `r` or `t`, such as `\\nas01\share`,
+is not read as an escape. A path may also start right after an ANSI code, such
+as the color code `\u001b[0m` or the erase-line code `\u001b[K`, and a path
+colored in parts is replaced whole. The evaluated skill's directory is replaced
+with its name and your home directory with `~`; the skill directory is known
+when you pass `--skill` or the run is in the skill's `evals/results` directory.
+Path masking leaves a URL unchanged, even a path in its query or fragment,
+unless its scheme is `file:` or ends in `+file:`, such as `git+file:`. A URL
+ends at whitespace; at a quote, `<`, `>`, a backtick, `^`, `{`, `|`, `}` or an
+ANSI escape (raw, `\u001b` or `\x1b`); at a `\n`, `\r` or `\t` escape; and
+before an absolute path or another scheme that follows a `,` or `;` (also with
+an option or variable name and `=`, such as `LOG=` or `--find-links=`) or a
+Markdown `](`. So a path after a URL in JSON, on the next line of an escaped env
+dump or stderr, in a `,`- or `;`-separated list or in
+`DOC=https://host/e;LOG=/path`, and a `file:` URL listed after one, are still
+replaced. A path joined to a URL by any other character, such as `:`, `=`, `(`
+or `)`, is not. The escape may have a doubled backslash, as in JSON inside JSON.
+A backslash and `n`, `r` or `t` that start a Windows folder name made of
+letters, digits, `_`, `.`, `~`, `$`, `%` or `-` and followed by as many
+backslashes, such as `\runs\` or `\t\` (`\\runs\\` in JSON), are not an escape
+unless an escaped character such as `\u001b` or `\xa0` comes next and is not
+itself followed by a name and as many backslashes, so a Windows path with such
+folders, such as `\t\x64\runs\`, in a URL is kept. Any other folder or file name
+that starts with `n`, `r` or `t`, such as `\runs(old)\` or `\notes.txt`, ends
+the URL there. Credential-shaped text is redacted before the text is shortened,
+and a shortened field ends in `...<truncated>`. The command writes nothing to
+disk.
No request is sent before the first question, so the command exits 0
immediately when standard input is empty. Piped input sends each line as a
diff --git a/src/skillevaluator/evaluation/tier3_feedback_chat.py b/src/skillevaluator/evaluation/tier3_feedback_chat.py
index 0b10a4fa..9d2bbe64 100644
--- a/src/skillevaluator/evaluation/tier3_feedback_chat.py
+++ b/src/skillevaluator/evaluation/tier3_feedback_chat.py
@@ -250,22 +250,246 @@ def _finite_score(value: Any) -> float | None:
_NAME_CHARS = "_.~-"
# An absolute-path root: POSIX or UNC, the home of this or another user (``~/``,
# ``~alice/``), a drive letter, or a home variable.
-_ABSOLUTE_PATH_ROOT = re.compile(r"[\\/]|~[\w.-]*[\\/]|[A-Za-z]:[\\/]|(?:\$HOME|\$\{HOME\}|%USERPROFILE%)[\\/]")
+_ABSOLUTE_PATH_ROOT_PATTERN = r"[\\/]|~[\w.-]*[\\/]|[A-Za-z]:[\\/]|(?:\$HOME|\$\{HOME\}|%USERPROFILE%)[\\/]"
+_ABSOLUTE_PATH_ROOT = re.compile(_ABSOLUTE_PATH_ROOT_PATTERN)
# A root right after one of these starts a path of its own: ``/opt/bin,/home/a``,
# ``--out=/home/a``, ``log(/home/a)``. A colon counts unless it is a drive letter's.
_PATH_LIST_SEPARATORS = ",;:=([{"
-_FILE_URL_LOCALHOST_PATH_RE = re.compile(r"(?i)\b(?P<prefix>file://localhost)(?P<path>/\S*)")
-_URL_SPAN_RE = re.compile(r"(?i)\b(?!file:)[a-z][a-z0-9+.-]*://\S+")
+# Like a URL (``_URL_SPAN_RE``), it may start right after a ``\n`` ``\r`` or ``\t`` escape.
+_FILE_URL_LOCALHOST_PATH_RE = re.compile(r"(?i)(?:\b|(?<=(?-i:\\[nrt])))(?P<prefix>file://localhost)(?P<path>/\S*)")
+# The rest of a Windows folder name after ``\n`` ``\r`` or ``\t``.
+_FOLDER_NAME_TAIL = re.compile(r"[\w.~$%-]*")
+_BACKSLASHES = re.compile(r"\\+")
+# The first character of a UNC share name (``\\nas01\share``).
+_UNC_SHARE_START = re.compile(r"[\w.~$-]")
+# A ``\u`` or ``\x`` escape of one character, after its backslash (``\u201c``,
+# ``\xa0``, ``\x1b``).
+_ESCAPED_CHARACTER = re.compile(r"u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}")
+# How many folders named only ``n`` ``r`` or ``t`` in a row (``\r\n``) are read
+# together as escapes or as folders.
+_LINE_ESCAPE_CHAIN = 8
+# The rest of a folder named like an escape (``x64@2``, ``x64(1)``): up to a
+# separator, whitespace, quote or the ``[`` of an ANSI code.
+_ESCAPED_FOLDER_NAME_TAIL = re.compile(r"[^\\/\s\"'<>|\[]*")
+# An ANSI control sequence, raw or escaped as in JSON or repr text: a color
+# code (``\u001b[1m``, ``\x1b[1;38;2;255;255;255m``, ``\x1b[38:5:208m``) or
+# another one, such as erase line (``\x1b[K``) or cursor up (``\x1b[1A``). A
+# path may start right after one: ``ERROR\u001b[0m/home/a``, ``\r\x1b[K/home/a``.
+_ANSI_CODE_END = re.compile(r"(?:\x1b|\\+(?:u001[bB]|x1[bB]))\[[0-9:;?]{0,64}[A-Za-z]\Z")
+_ANSI_CODE_AFTER_BACKSLASHES = re.compile(r"(?:u001[bB]|x1[bB])\[[0-9:;?]{0,64}[A-Za-z]")
+# The longest such code that ``_ANSI_CODE_END`` looks back for.
+_ANSI_CODE_LOOKBACK = 80
+# A URL that path masking leaves unchanged: any scheme but ``file:`` and a
+# ``+file:`` one such as ``git+file:``, which name local paths. The scheme is at
+# most 64 characters, so a long dotted word is not rescanned from every word
+# boundary. The URL ends at whitespace; at a character a URL never holds
+# unencoded (``"`` ``<`` ``>`` a backtick ``^`` ``{`` ``|`` ``}``, an ANSI
+# escape raw or as ``\u001b`` ``\x1b``); at a single quote, which closes a
+# quoted URL far more often than it appears in one; at a ``\n`` ``\r`` or
+# ``\t`` escape (JSON or repr text), so the next line is not part of it; and
+# before an absolute-path root or another scheme that follows a
+# ``,`` or ``;`` (a list), a ``,`` or ``;`` and an option or variable name with
+# ``=`` (``DOC=https://h/e;LOG=/home/a``, ``,--find-links=file:///home/a``), or
+# a Markdown ``](``. So a ``file:`` URL in a list is masked. The escape's
+# backslash may be doubled (JSON inside JSON). It is a Windows folder instead
+# when a name of ``_FOLDER_NAME_TAIL`` characters and as many backslashes
+# follow it, and no escaped character such as ``\u001b`` or ``\xa0`` follows
+# those unless a name and as many backslashes follow it too:
+# ``C:\Users\t\runs``, ``C:\\Users\\t\\runs``, ``\t\x64\runs``. Other backslashes stay in the
+# URL, so a Windows path in one is kept unless a folder or file name in it
+# starts with ``n`` ``r`` or ``t`` and is not such a folder (``\notes.txt``,
+# ``\runs(old)\``). So in
+# ``{"doc":"https://host/e","log":"/home/a/<id>"}``,
+# ``"https://host/e\nLOG=/home/a/<id>"`` or ``https://host/a,/home/a/<id>`` the
+# path after the URL is still masked. The scheme starts after such an escape,
+# not inside it: ``\nfile:///home/a`` is a ``file:`` URL, not ``nfile:``.
+_URL_SPAN_RE = re.compile(
+ r"(?i)(?:\b(?<!\\)|(?<=(?-i:\\[nrt])))(?!(?:[a-z0-9+.-]{0,62}\+)?file:)[a-z][a-z0-9+.-]{0,63}://"
+ r"(?:(?!(?:[,;](?:-{0,2}[a-z_][\w.-]*=)?|\]\()(?:"
+ + _ABSOLUTE_PATH_ROOT_PATTERN
+ + r"|[a-z][a-z0-9+.-]{0,63}:)|(?<!\\)\\+(?-i:u001[bB]|x1[bB])|(?<!\\)(\\+)(?-i:[nrt])(?!"
+ + _FOLDER_NAME_TAIL.pattern
+ + r"\1(?!\\)(?:(?!(?-i:"
+ + _ESCAPED_CHARACTER.pattern
+ + r"))|(?-i:"
+ + _ESCAPED_CHARACTER.pattern
+ + r")"
+ + _FOLDER_NAME_TAIL.pattern
+ + r"\1(?!\\|(?-i:"
+ + _ESCAPED_CHARACTER.pattern
+ + r")))))[^\s\"'<>`^{|}\x1b])*"
+)
+
+
+def _separates_folders(value: str, index: int, count: int) -> bool:
+ """Whether exactly ``count`` backslashes are at ``index``, as between two folder names.
+
+ In JSON the next name may start with an escaped letter or digit, whose
+ backslash follows them: ``\\\\t\\\\\\u00e9cole`` is a folder ``t`` before a
+ folder whose name starts with an escaped ``\\u00e9``.
+ """
+ if not value.startswith("\\" * count, index):
+ return False
+ if value[index + count : index + count + 1] != "\\":
+ return True
+ half = count // 2
+ end = index + count + half
+ return (
+ bool(half)
+ and not count % 2
+ and value.startswith("\\" * half, index + count)
+ and value[end : end + 1] != "\\"
+ and _escapes_name_character(value, end)
+ )
+
+
+def _escapes_name_character(value: str, index: int) -> bool:
+ """Whether a ``\\u`` or ``\\x`` escape of a letter or digit (``\\u00e9``) is at ``index``, after its backslash."""
+ escape = _ESCAPED_CHARACTER.match(value, index)
+ return escape is not None and chr(int(escape.group()[1:], 16)).isalnum()
+
+
+def _follows_line_escape(value: str, index: int) -> bool:
+ """Whether a JSON or repr escape for a line break or tab (``\\n`` ``\\r`` ``\\t``) ends right before ``index``.
+
+ Its backslash may be doubled, as in JSON inside JSON. A Windows folder name
+ and as many backslashes after it make it a folder instead, unless another
+ escape follows them: ``C:\\Users\\t\\runs`` has a folder ``t``, while
+ ``\\n\\u001b[2m`` starts a line with an ANSI color code. That escape is a
+ folder too when a name and the same backslashes follow it
+ (``C:\\Users\\t\\u1234\\runs``). An even run of backslashes, a name, then
+ half as many backslashes and a share name start a UNC path instead:
+ ``\\\\nas01\\share`` (``\\\\\\\\nas01\\\\share`` in JSON), but not a server
+ named only ``n`` ``r`` or ``t`` before an escaped character: ``\\\\n\\u201c``
+ is a doubled escape before a single one (JSON around repr text). A folder
+ named only ``n`` ``r`` or ``t`` before another such escape is read with the
+ escapes after it, so ``\\r\\n\\u001b[2m`` is three escapes.
+ """
+ if index < 2 or value[index - 2] != "\\" or value[index - 1] not in "nrt":
+ return False
+ start = index - 2
+ while start and value[start - 1] == "\\":
+ start -= 1
+ count = index - 1 - start
+ name_end = _FOLDER_NAME_TAIL.match(value, index).end()
+ half = count // 2
+ if (
+ not count % 2
+ and value.startswith("\\" * half, name_end)
+ and _UNC_SHARE_START.match(value, name_end + half)
+ and (name_end > index or not _ESCAPED_CHARACTER.match(value, name_end + half))
+ ):
+ return False
+ # A bounded number of steps, so the scan stays linear on a long chain.
+ for _step in range(_LINE_ESCAPE_CHAIN):
+ if not _separates_folders(value, name_end, count):
+ return True
+ after = name_end + count
+ if name_end > index or value[after : after + 1] not in ("n", "r", "t"):
+ break
+ index = after + 1
+ name_end = _FOLDER_NAME_TAIL.match(value, index).end()
+ else:
+ return True
+ escape = _ESCAPED_CHARACTER.match(value, name_end + count)
+ if escape is None:
+ return False
+ # Folders named like escapes in a row (``\\t\\x64\\x86\\runs``) are
+ # folders when a name that is not one follows them with the same
+ # backslashes; escaped characters in a row (``\\n\\ud83d\\udcc1/srv``)
+ # end at a root or other text.
+ for _step in range(_LINE_ESCAPE_CHAIN):
+ escape_name_end = _ESCAPED_FOLDER_NAME_TAIL.match(value, escape.end()).end()
+ if not _separates_folders(value, escape_name_end, count):
+ return True
+ escape = _ESCAPED_CHARACTER.match(value, escape_name_end + count)
+ if escape is None:
+ return False
+ return True
+
+
+def _escape_backslashes_end(value: str, index: int) -> int | None:
+ """Where the backslashes end when the one at ``index`` belongs to an escape that is not a path.
+
+ That is a ``\\n`` ``\\r`` or ``\\t`` escape, or the start of an ANSI code
+ (``\\u001b[1m``, ``\\u001b[K``), after which a path may start on its own.
+ """
+ if value[index] != "\\":
+ return None
+ end = _BACKSLASHES.match(value, index).end()
+ if value[end : end + 1] in ("n", "r", "t") and _follows_line_escape(value, end + 1):
+ return end
+ if _ANSI_CODE_AFTER_BACKSLASHES.match(value, end):
+ return end
+ return None
+
+
+def _follows_ansi_code(value: str, index: int) -> bool:
+ """Whether an ANSI code (``\\u001b[0m``, ``\\x1b[K`` or a raw one) ends right before ``index``."""
+ previous = value[index - 1 : index]
+ return (
+ previous.isascii()
+ and previous.isalpha()
+ and _ANSI_CODE_END.search(value, max(0, index - _ANSI_CODE_LOOKBACK), index) is not None
+ )
+
+
+def _follows_split_ansi_code(value: str, index: int) -> bool:
+ """Whether ANSI codes end right before ``index`` and a line escape or path separator precedes them.
+
+ So in ``/opt/a.py\\r\\x1b[K/srv/<id>`` the root after the codes starts a path of its own.
+ """
+ if value[index] not in "/\\~$%" and value[index + 1 : index + 2] != ":":
+ return False
+ if (
+ value.find("[", max(0, index - _ANSI_CODE_LOOKBACK), index) == -1
+ or not _follows_ansi_code(value, index)
+ or not _starts_absolute_path(value, index)
+ ):
+ return False
+ code_start = None
+ for _step in range(_LINE_ESCAPE_CHAIN):
+ if not _follows_ansi_code(value, index):
+ break
+ match = _ANSI_CODE_END.search(value, max(0, index - _ANSI_CODE_LOOKBACK), index)
+ if match is None:
+ break
+ index = code_start = match.start()
+ if not code_start:
+ return False
+ if _follows_line_escape(value, code_start):
+ # The codes are escaped like the line escape (``\\r\\u001b[K``,
+ # ``\\\\r\\\\x1b[K``); a raw ESC, or one escaped with other
+ # backslashes, follows a folder named ``n`` ``r`` or ``t``.
+ escape_start = code_start - 2
+ while escape_start and value[escape_start - 1] == "\\":
+ escape_start -= 1
+ count = code_start - 1 - escape_start
+ # The code's own backslashes: as many as the escape's, or after an
+ # escaped separator (``C:\\\\work\\\\t\\\\\\u001b[0m``) half as many more.
+ backslashes = _BACKSLASHES.match(value, code_start)
+ code_backslashes = backslashes.end() - code_start if backslashes else 0
+ return code_backslashes == count or (not count % 2 and code_backslashes == count + count // 2)
+ return value[code_start - 1] in _PATH_LIST_SEPARATORS and _follows_path_separator(value, code_start)
def _starts_absolute_path(value: str, index: int) -> bool:
"""Whether a POSIX, home, UNC, drive-letter or home-variable absolute path starts at ``index``.
- The character before it must not belong to a name, so ``a/b`` is not read as ``/b``.
+ The character before it must not belong to a name, so ``a/b`` is not read as ``/b``,
+ unless it ends a ``\\n`` ``\\r`` or ``\\t`` escape or an ANSI code. The backslash of
+ such an escape or code is never a root, so ``\\nevals/results`` stays a relative path.
"""
if value[index] not in "/\\~$%" and value[index + 1 : index + 2] != ":":
return False
- if index and (value[index - 1].isalnum() or value[index - 1] in _NAME_CHARS):
+ if (
+ index
+ and (value[index - 1].isalnum() or value[index - 1] in _NAME_CHARS)
+ and not _follows_line_escape(value, index)
+ and not _follows_ansi_code(value, index)
+ ):
+ return False
+ if _escape_backslashes_end(value, index) is not None:
return False
return _ABSOLUTE_PATH_ROOT.match(value, index) is not None
@@ -284,7 +508,12 @@ def _follows_path_separator(value: str, index: int) -> bool:
letter >= 0
and value[letter].isascii()
and value[letter].isalpha()
- and (letter == 0 or not (value[letter - 1].isalnum() or value[letter - 1] in _NAME_CHARS + "/\\"))
+ and (
+ letter == 0
+ or not (value[letter - 1].isalnum() or value[letter - 1] in _NAME_CHARS + "/\\")
+ or _follows_line_escape(value, letter)
+ or _follows_ansi_code(value, letter)
+ )
)
return not is_drive
@@ -293,18 +522,33 @@ def _path_start(value: str, start: int, end: int) -> int | None:
"""Where the absolute path that ends at ``end`` starts, searching from ``start``.
It starts at the first root, unless a later root follows a path separator
- (``/opt/bin,/home/a``, ``PATH=/usr/bin:/home/a``); then that later root
- starts it and the text before it is kept. A separator that is not followed
- by a root (``/home/a/my(project)``) is part of the path.
+ (``/opt/bin,/home/a``, ``PATH=/usr/bin:/home/a``) or a ``\\n`` ``\\r`` or
+ ``\\t`` escape, also with ANSI codes after it (``\\r\\x1b[K``); then that
+ later root starts it and the text before it is kept. An ANSI code on its
+ own does not split a path, as one colored in parts
+ (``\\u001b[34m/srv/ci\\u001b[0m/runs``) is still one path. A separator that
+ is not followed by a root (``/home/a/my(project)``) is part of the path.
+ Only the first backslash of a run can be a root, so ``evals\\\\results``
+ (JSON) is not read as ``\\results``.
"""
for index in range(end, start, -1):
if (
- value[index - 1] in _PATH_LIST_SEPARATORS
- and _follows_path_separator(value, index)
- and _starts_absolute_path(value, index)
- ):
+ (value[index - 1] in _PATH_LIST_SEPARATORS and _follows_path_separator(value, index))
+ or _follows_line_escape(value, index)
+ or _follows_split_ansi_code(value, index)
+ ) and _starts_absolute_path(value, index):
return index
- return next((index for index in range(start, end + 1) if _starts_absolute_path(value, index)), None)
+ index = start
+ while index <= end:
+ if _starts_absolute_path(value, index):
+ return index
+ # Skip the rest of a run of backslashes at once, so a long run is not
+ # rescanned from each of its backslashes.
+ if value[index] == "\\":
+ index = _BACKSLASHES.match(value, index).end()
+ else:
+ index += 1
+ return None
def _path_spellings(path: Path) -> set[str]:
@@ -361,7 +605,9 @@ class _Scrubber:
run_id = run_dir.name
# The run directory is replaced wherever it occurs, as a prefix of
# longer names too. The skill and home directories are replaced only as
- # whole paths, so ``/home/alice2`` is not read as ``~2``.
+ # whole paths, so ``/home/alice2`` is not read as ``~2``; one right after
+ # a JSON or repr escape for a line break or tab (``\n`` ``\r`` ``\t``)
+ # starts a line, so it counts as whole.
entries: dict[str, tuple[str, bool]] = {}
for spelling in (str(run_dir), run_dir.as_posix()):
entries.setdefault(spelling, (run_id, False))
@@ -375,7 +621,7 @@ class _Scrubber:
reverse=True,
)
alternatives = [
- rf"(?<![\w.~-])(?P<p{index}>{re.escape(spelling)})(?![\w-]|\.\w)"
+ rf"(?:(?<![\w.~-])|(?<=\\[nrt]))(?P<p{index}>{re.escape(spelling)})(?![\w-]|\.\w)"
if whole
else rf"(?P<p{index}>{re.escape(spelling)})"
for index, (spelling, _replacement, whole) in enumerate(ordered)
@@ -397,9 +643,12 @@ class _Scrubber:
spaces included; the longest wins. A copied run keeps its ID, so the
path it had on another machine is found by its last segment: the path
starts at the first absolute-path root after the preceding whitespace
- or quote, or at a later root that follows ``,;:=([{``. Such a path
- that contains a space is not recognized. Relative paths are kept.
- URL spans through the next whitespace are left unchanged.
+ or quote (also right after an ANSI code such as a color code), or at a
+ later root that follows ``,;:=([{`` or a ``\\n`` ``\\r`` or ``\\t``
+ escape, also with ANSI codes in between. Such a path that contains a
+ space is not recognized. Relative paths are kept.
+ A URL is left unchanged, up to where ``_URL_SPAN_RE`` ends it, unless
+ its scheme is ``file:`` or ends in ``+file:``.
"""
def scrub_segment(segment: str) -> str:
diff --git a/tests/evaluation/test_tier3_feedback_chat.py b/tests/evaluation/test_tier3_feedback_chat.py
index 8cbefc9f..e603ff4b 100644
--- a/tests/evaluation/test_tier3_feedback_chat.py
+++ b/tests/evaluation/test_tier3_feedback_chat.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import json
import unicodedata
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch
@@ -415,6 +415,408 @@ def test_context_leaves_url_path_values_unchanged_while_scrubbing_other_paths(tm
assert context["agents"]["codex"]["execution_errors"] == [f"Failed at {scrubbed_skill_path}; URL: {query_url}"]
+def test_context_masks_paths_that_follow_a_url_in_minified_json(tmp_path: Path) -> None:
+ # The URL ends at its closing quote, so the run, skill and home paths after
+ # it in the same unbroken JSON text are still masked; the URL is kept.
+ home = tmp_path / "home" / "alice"
+ skill = home / "work" / "acme-skill"
+ run_dir = skill / "evals" / "results" / RUN_ID
+ error = json.dumps(
+ {
+ "doc": "https://docs.example.test/errors/e1",
+ "log": str(run_dir / "agent.log"),
+ "skill": str(skill / "SKILL.md"),
+ "cache": str(home / ".cache"),
+ },
+ separators=(",", ":"),
+ )
+ payload = {"agents": {"codex": {"execution_errors": [f"Error: {error}"]}}}
+
+ context = compact_run_context(payload, run_dir=run_dir, skill_dir=skill, home=home)
+
+ [sent] = context["agents"]["codex"]["execution_errors"]
+ assert json.loads(sent.removeprefix("Error: ")) == {
+ "doc": "https://docs.example.test/errors/e1",
+ "log": str(Path(RUN_ID) / "agent.log"),
+ "skill": str(Path("acme-skill") / "SKILL.md"),
+ "cache": str(Path("~") / ".cache"),
+ }
+ assert str(home) not in sent
+
+
+ ("text", "expected"),
+ [
+ # A character a URL never holds unencoded, or a quote, ends it.
+ ('"https://h.test/a","/home/alice/x"', '"https://h.test/a","~/x"'),
+ ("'https://h.test/a','/home/alice/x'", "'https://h.test/a','~/x'"),
+ ("`https://h.test/a`/home/alice/x", "`https://h.test/a`~/x"),
+ ("<https://h.test/a>/home/alice/x", "<https://h.test/a>~/x"),
+ ("https://h.test/a|/home/alice/x", "https://h.test/a|~/x"),
+ ("{https://h.test/a}/home/alice/x", "{https://h.test/a}~/x"),
+ ("https://h.test/a^/home/alice/x", "https://h.test/a^~/x"),
+ ("https://h.test/a</home/alice/x", "https://h.test/a<~/x"),
+ ("https://h.test/a{/home/alice/x", "https://h.test/a{~/x"),
+ # So does an ANSI escape, raw or escaped as in JSON or repr text.
+ (f"https://h.test/e\x1b[0m/srv/ci/runs/{RUN_ID}/a", f"https://h.test/e\x1b[0m{RUN_ID}/a"),
+ (f'"https://h.test/e\\u001b[0m/srv/ci/runs/{RUN_ID}/a"', f'"https://h.test/e\\u001b[0m{RUN_ID}/a"'),
+ # A `,` or `;` that an absolute-path root follows starts a path list.
+ (
+ f"fetch https://h.test/a,/home/bob/ci/results/{RUN_ID}/x",
+ f"fetch https://h.test/a,{RUN_ID}/x",
+ ),
+ ("https://h.test/a;/home/alice/x", "https://h.test/a;~/x"),
+ (f"https://h.test/a,~/ci/results/{RUN_ID}/x", f"https://h.test/a,{RUN_ID}/x"),
+ # So do a `,` or `;` with an option or variable name and `=`, and a
+ # Markdown `](`, each before a root; the path is masked.
+ ("DOC=https://h.test/e;LOG=/home/alice/x", "DOC=https://h.test/e;LOG=~/x"),
+ ("OPTS=https://h.test/e;--log-dir=/home/alice/x", "OPTS=https://h.test/e;--log-dir=~/x"),
+ ("DOC=https://h.test/e,log-file=/home/alice/x", "DOC=https://h.test/e,log-file=~/x"),
+ ("[https://h.test/e](/home/alice/x)", "[https://h.test/e](~/x)"),
+ # A `\n` `\r` or `\t` escape (JSON or repr text) ends a URL, so the
+ # next line of an env dump or stderr is masked; the escape is kept.
+ ('"https://h.test/a\\n/home/alice/x"', '"https://h.test/a\\n~/x"'),
+ (f'"https://h.test/a\\n/home/alice/runs/{RUN_ID}/x"', f'"https://h.test/a\\n{RUN_ID}/x"'),
+ (f'"https://h.test/a\\t/home/bob/ci/results/{RUN_ID}/x"', f'"https://h.test/a\\t{RUN_ID}/x"'),
+ ("line1\\n/home/alice/x", "line1\\n~/x"),
+ (
+ f'"URL=https://h.test/e\\nHOME=/home/alice\\nLOG=/home/alice/runs/{RUN_ID}/a.log"',
+ f'"URL=https://h.test/e\\nHOME=~\\nLOG={RUN_ID}/a.log"',
+ ),
+ (
+ f'"GET https://h.test/e\\nERROR:/home/bob/ci/results/{RUN_ID}/a.log"',
+ f'"GET https://h.test/e\\nERROR:{RUN_ID}/a.log"',
+ ),
+ ('"https://h.test/e\\r\\n--log=/home/alice/x"', '"https://h.test/e\\r\\n--log=~/x"'),
+ ('"https://h.test/e\\r/home/alice/x"', '"https://h.test/e\\r~/x"'),
+ ('"https://h.test/e\\nfile://localhost/home/alice/x"', '"https://h.test/e\\nfile://localhost/~/x"'),
+ # Another escape right after it, such as an ANSI color code at the
+ # start of the next line, does not make it a folder.
+ (
+ f'"https://h.test/e\\n\\u001b[2m/home/alice/runs/{RUN_ID}/a.log\\u001b[0m"',
+ f'"https://h.test/e\\n\\u001b[2m{RUN_ID}/a.log\\u001b[0m"',
+ ),
+ (f"'https://h.test/e\\t\\x1b[1m/home/bob/ci/{RUN_ID}/a'", f"'https://h.test/e\\t\\x1b[1m{RUN_ID}/a'"),
+ (f'"https://h.test/e\\r\\u001b[K/srv/ci/runs/{RUN_ID}/a.log"', f'"https://h.test/e\\r\\u001b[K{RUN_ID}/a.log"'),
+ (f'"https://h.test/e\\n\\u2502/srv/ci/runs/{RUN_ID}/a"', f'"https://h.test/e\\n{RUN_ID}/a"'),
+ # A URL starts right after an escape, so its query is kept.
+ (
+ '"https://h.test/a\\nhttps://h.test/b?p=/home/alice/x"',
+ '"https://h.test/a\\nhttps://h.test/b?p=/home/alice/x"',
+ ),
+ ('"x\\nhttps://h.test/?path=/home/alice/x"', '"x\\nhttps://h.test/?path=/home/alice/x"'),
+ ('"https://h.test/e\\nfile:///home/alice/x"', '"https://h.test/e\\nfile://~/x"'),
+ ('"https://h.test/e\\tgit+file:///home/alice/x"', '"https://h.test/e\\tgit+file://~/x"'),
+ # In JSON inside JSON the escape's backslash is doubled.
+ (
+ '{"s":"{\\"e\\":\\"https://h.test/e\\\\n/home/alice/x\\"}"}',
+ '{"s":"{\\"e\\":\\"https://h.test/e\\\\n~/x\\"}"}',
+ ),
+ (
+ f'{{"s":"{{\\"e\\":\\"https://h.test/e\\\\nLOG=/home/bob/ci/results/{RUN_ID}/a\\"}}"}}',
+ f'{{"s":"{{\\"e\\":\\"https://h.test/e\\\\nLOG={RUN_ID}/a\\"}}"}}',
+ ),
+ # Another scheme after a `,` `;` (with or without a name and `=`) or
+ # `](` starts its own URL, so a `file:` or `+file:` one there is
+ # masked like one on its own.
+ ("pip install git+file:///home/alice/x", "pip install git+file://~/x"),
+ ("links=https://h.test/e,file:///home/alice/x", "links=https://h.test/e,file://~/x"),
+ ("[a](https://h.test/e)[b](git+file:///home/alice/x)", "[a](https://h.test/e)[b](git+file://~/x)"),
+ ("https://h.test/e,FIND_LINKS=file:///home/alice/x", "https://h.test/e,FIND_LINKS=file://~/x"),
+ ("https://h.test/e;--find-links=git+file:///home/alice/x", "https://h.test/e;--find-links=git+file://~/x"),
+ ("pip install git+https://h.test/x", "pip install git+https://h.test/x"),
+ # A copied run's path after a list separator and an escape keeps both.
+ (f"PATH=/usr/bin:\\n/srv/runs/{RUN_ID}", f"PATH=/usr/bin:\\n{RUN_ID}"),
+ (f"x\\tD:\\runs\\{RUN_ID}\\a.log", f"x\\t{RUN_ID}\\a.log"),
+ # A relative path after an escape is kept, with or without a URL. So is
+ # the rest of a Windows path in a URL when a folder name that starts
+ # with n, r or t has a character outside `_FOLDER_NAME_TAIL` and so
+ # reads as an escape that ends the URL.
+ (
+ f"vscode://file/C:\\Users\\bob\\node@18\\runs\\{RUN_ID}\\a.log",
+ f"vscode://file/C:\\Users\\bob\\node@18\\runs\\{RUN_ID}\\a.log",
+ ),
+ (
+ f'{{"stderr":"see https://docs.test/e\\nevals/results/{RUN_ID}/agent.log"}}',
+ f'{{"stderr":"see https://docs.test/e\\nevals/results/{RUN_ID}/agent.log"}}',
+ ),
+ (f'"\\nevals/results/{RUN_ID}/a"', f'"\\nevals/results/{RUN_ID}/a"'),
+ (f'"\\n\\u001b[2mevals/results/{RUN_ID}/a"', f'"\\n\\u001b[2mevals/results/{RUN_ID}/a"'),
+ # Line breaks in a row before a code are escapes too, so the relative path is kept.
+ (f'"\\r\\n\\u001b[2mevals/results/{RUN_ID}/a"', f'"\\r\\n\\u001b[2mevals/results/{RUN_ID}/a"'),
+ (
+ '"' + "\\n" * 12 + f'\\u001b[2mevals/results/{RUN_ID}/a"',
+ '"' + "\\n" * 12 + f'\\u001b[2mevals/results/{RUN_ID}/a"',
+ ),
+ # Also with JSON-escaped backslashes: the second of a pair is not a root.
+ (f'"\\nevals\\\\results\\\\{RUN_ID}\\\\a.log"', f'"\\nevals\\\\results\\\\{RUN_ID}\\\\a.log"'),
+ (f'"\\n\\u001b[2mevals\\\\results\\\\{RUN_ID}"', f'"\\n\\u001b[2mevals\\\\results\\\\{RUN_ID}"'),
+ (f'"x evals\\\\results\\\\{RUN_ID}"', f'"x evals\\\\results\\\\{RUN_ID}"'),
+ (
+ f'"\\n\\u001b[1;38;2;255;255;255mevals/results/{RUN_ID}/a"',
+ f'"\\n\\u001b[1;38;2;255;255;255mevals/results/{RUN_ID}/a"',
+ ),
+ (f'"\\n\\u001b[38:5:208mevals/results/{RUN_ID}/a"', f'"\\n\\u001b[38:5:208mevals/results/{RUN_ID}/a"'),
+ # An odd run of backslashes before n is a literal backslash and an escape
+ # (`\\` and `\n` in JSON), not a UNC server.
+ (f'"see \\\\\\\\\\nevals\\\\results\\\\{RUN_ID}"', f'"see \\\\\\\\\\nevals\\\\results\\\\{RUN_ID}"'),
+ # A path may start right after an ANSI code, escaped or raw: a color
+ # code, or another one such as erase line or cursor up.
+ (f'"\\nERROR\\u001b[K/srv/ci/runs/{RUN_ID}/a.log"', f'"\\nERROR\\u001b[K{RUN_ID}/a.log"'),
+ (f"\r\x1b[K\\\\nas01\\share\\runs\\{RUN_ID}\\a.log", f"\r\x1b[K{RUN_ID}\\a.log"),
+ (f"\x1b[1A\x1b[2K/srv/ci/runs/{RUN_ID}/a.log", f"\x1b[1A\x1b[2K{RUN_ID}/a.log"),
+ (f"\x1b[?25l\\\\srv\\share\\{RUN_ID}", f"\x1b[?25l{RUN_ID}"),
+ (f'"\\n\\u001b[?25levals/results/{RUN_ID}/a"', f'"\\n\\u001b[?25levals/results/{RUN_ID}/a"'),
+ # A root after ANSI codes that follow a line escape or a separator
+ # starts a new path, so an earlier path and the codes are kept.
+ (f'"/opt/app/a.py\\r\\u001b[K/srv/ci/runs/{RUN_ID}/a.log"', f'"/opt/app/a.py\\r\\u001b[K{RUN_ID}/a.log"'),
+ (f'"/opt/app\\n\\u001b[2m/srv/ci/runs/{RUN_ID}/a"', f'"/opt/app\\n\\u001b[2m{RUN_ID}/a"'),
+ (f"PATH=/usr/bin:\x1b[1m/srv/ci/runs/{RUN_ID}", f"PATH=/usr/bin:\x1b[1m{RUN_ID}"),
+ (
+ f'"/opt/app/a.py\\n\\u001b[1A\\u001b[2K/srv/ci/runs/{RUN_ID}/a.log"',
+ f'"/opt/app/a.py\\n\\u001b[1A\\u001b[2K{RUN_ID}/a.log"',
+ ),
+ # A path that ends in a backslash before a color code is not a folder `t`.
+ (f'"C:\\\\work\\\\t\\\\\\u001b[0m/srv/ci/{RUN_ID}"', f'"C:\\\\work\\\\t\\\\\\u001b[0m{RUN_ID}"'),
+ (f'"\\r\\u001b[K\\/srv\\/ci\\/{RUN_ID}"', f'"\\r\\u001b[K{RUN_ID}"'),
+ # A folder named n, r or t before a color code that is not escaped like
+ # it (a raw ESC after `\t`, or `\u001b` after `\\t`) is a folder, so
+ # the whole copied path is masked.
+ (f"\x1b[2mD:\\ci\\bob\\t\x1b[0m\\{RUN_ID}\\a.log", f"\x1b[2m{RUN_ID}\\a.log"),
+ (f'"\\u001b[2mD:\\\\ci\\\\bob\\\\t\\u001b[0m\\\\{RUN_ID}\\\\a.log"', f'"\\u001b[2m{RUN_ID}\\\\a.log"'),
+ (f"\x1b[2m\\\\nas01\\share\\r\x1b[0m\\{RUN_ID}", f"\x1b[2m{RUN_ID}"),
+ # A drive letter right after an ANSI code starts the path.
+ (f"\r\x1b[KC:\\ci\\runs\\{RUN_ID}\\a.log", f"\r\x1b[K{RUN_ID}\\a.log"),
+ (f'"\\u001b[31mC:\\\\ci\\\\bob\\\\{RUN_ID}"', f'"\\u001b[31m{RUN_ID}"'),
+ (f'"\\nERROR\\u001b[0m/srv/ci/runs/{RUN_ID}/a.log"', f'"\\nERROR\\u001b[0m{RUN_ID}/a.log"'),
+ (f"ERROR\x1b[0m/srv/ci/runs/{RUN_ID}/a.log", f"ERROR\x1b[0m{RUN_ID}/a.log"),
+ (
+ f'"ERROR\\u001b[1;38;2;255;255;255m/srv/ci/runs/{RUN_ID}/a.log"',
+ f'"ERROR\\u001b[1;38;2;255;255;255m{RUN_ID}/a.log"',
+ ),
+ (f"ERROR\x1b[38:5:208m/srv/ci/runs/{RUN_ID}/a.log", f"ERROR\x1b[38:5:208m{RUN_ID}/a.log"),
+ (
+ f'"ERROR\\u001b[38;2;255;255;255;48;2;10;10;10m/srv/ci/runs/{RUN_ID}/a.log"',
+ f'"ERROR\\u001b[38;2;255;255;255;48;2;10;10;10m{RUN_ID}/a.log"',
+ ),
+ # Line breaks before a color code are all escapes, so they are kept too.
+ (f'"\\r\\n\\u001b[2m/srv/ci/runs/{RUN_ID}/a.log"', f'"\\r\\n\\u001b[2m{RUN_ID}/a.log"'),
+ (f'"Error: \\r\\n\\u001b[31m/srv/ci/runs/{RUN_ID}/a.log"', f'"Error: \\r\\n\\u001b[31m{RUN_ID}/a.log"'),
+ (f'"\\n\\n\\n\\u001b[2m/srv/ci/runs/{RUN_ID}/a.log"', f'"\\n\\n\\n\\u001b[2m{RUN_ID}/a.log"'),
+ ('"' + "\\n" * 12 + f'\\u001b[2m/srv/ci/runs/{RUN_ID}/a"', '"' + "\\n" * 12 + f'\\u001b[2m{RUN_ID}/a"'),
+ # Bold with truecolor foreground and background, as Rich writes it.
+ (
+ f'"ERROR\\u001b[1;38;2;255;255;255;48;2;255;255;255m/srv/ci/runs/{RUN_ID}/a.log"',
+ f'"ERROR\\u001b[1;38;2;255;255;255;48;2;255;255;255m{RUN_ID}/a.log"',
+ ),
+ (
+ f"ERROR\x1b[1;38;2;255;255;255;48;2;255;255;255m/srv/ci/runs/{RUN_ID}/a.log",
+ f"ERROR\x1b[1;38;2;255;255;255;48;2;255;255;255m{RUN_ID}/a.log",
+ ),
+ # A path colored in parts is still one path.
+ (f'"\\u001b[34m/srv/ci\\u001b[0m/runs/{RUN_ID}/a"', f'"\\u001b[34m{RUN_ID}/a"'),
+ # A Windows folder named n, r or t is not an escape: its name is
+ # followed by as many backslashes as precede it. So the whole copied
+ # path is masked.
+ (f"C:\\Users\\bob\\t\\runs\\{RUN_ID}\\agent.log", f"{RUN_ID}\\agent.log"),
+ (
+ f'{{"log":"C:\\\\Users\\\\bob\\\\t\\\\runs\\\\{RUN_ID}\\\\agent.log"}}',
+ f'{{"log":"{RUN_ID}\\\\agent.log"}}',
+ ),
+ (f"\\\\srv\\share\\n\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ (f"C:\\Users\\t~1\\runs\\{RUN_ID}", RUN_ID),
+ (f"C:\\Users\\bob\\t\\x64\\runs\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ (f"C:\\Users\\bob\\t\\n\\runs\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ # More backslashes after the name than before it do not make a folder.
+ (
+ f'"https://h.test/e\\n\\\\\\\\srv\\\\share\\\\{RUN_ID}\\\\a.log"',
+ f'"https://h.test/e\\n{RUN_ID}\\\\a.log"',
+ ),
+ (f'"x\\n\\\\\\\\srv\\\\share\\\\{RUN_ID}\\\\a.log"', f'"x\\n{RUN_ID}\\\\a.log"'),
+ # A UNC server whose name starts with n, r or t has half as many
+ # backslashes after it, so it is not an escape either.
+ (f"\\\\nas01\\share\\runs\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ (f"x \\\\tsclient\\C\\Users\\bob\\{RUN_ID}", f"x {RUN_ID}"),
+ (f"--out=\\\\nas01\\ci\\{RUN_ID}", f"--out={RUN_ID}"),
+ (f"\\\\n\\share\\{RUN_ID}", RUN_ID),
+ (f'"\\\\\\\\nas01\\\\share\\\\{RUN_ID}\\\\a.log"', f'"{RUN_ID}\\\\a.log"'),
+ (f'"log:\\n\\\\\\\\nas01\\\\share\\\\{RUN_ID}"', f'"log:\\n{RUN_ID}"'),
+ # A UNC share named like an escape is still a share.
+ (f"\\\\nas01\\x64\\builds\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ (f'"\\\\\\\\nas01\\\\x64\\\\builds\\\\{RUN_ID}\\\\a.log"', f'"{RUN_ID}\\\\a.log"'),
+ # A doubled `\n` escape and a doubled `\u001b` escape are not a UNC server.
+ (f'"\\\\n\\\\u001b[2m/srv/ci/runs/{RUN_ID}/a"', f'"\\\\n\\\\u001b[2m{RUN_ID}/a"'),
+ # A folder named like an escape after a folder named n, r or t is a
+ # folder too when a name and as many backslashes follow it.
+ (f"C:\\Users\\bob\\t\\u1234\\runs\\{RUN_ID}\\a.log", f"{RUN_ID}\\a.log"),
+ (f'"C:\\\\Users\\\\bob\\\\n\\\\uabcd\\\\{RUN_ID}"', f'"{RUN_ID}"'),
+ (f'"\\n\\ud83d\\udcc1/srv/ci/runs/{RUN_ID}/a"', f'"\\n{RUN_ID}/a"'),
+ # Inside a URL, `,` `;` `(` `)` `=` and the like do not end it.
+ ("https://h.test/a,b;c=d/e(f)!*+$&@:%20~[0]", "https://h.test/a,b;c=d/e(f)!*+$&@:%20~[0]"),
+ ("https://h.test/a;jsessionid=abc/x?v=1,2&w=3;z", "https://h.test/a;jsessionid=abc/x?v=1,2&w=3;z"),
+ # Other backslashes stay in the URL, so a Windows path in one is kept,
+ # with folders named n, r or t and JSON-escaped backslashes too.
+ (
+ f"http://localhost:8080/runs\\{RUN_ID}\\agent.html?log=/home/alice/x",
+ f"http://localhost:8080/runs\\{RUN_ID}\\agent.html?log=/home/alice/x",
+ ),
+ (f"https://h.test/dir\\t\\runs\\{RUN_ID}/log", f"https://h.test/dir\\t\\runs\\{RUN_ID}/log"),
+ (f"smb://srv/share\\n\\{RUN_ID}", f"smb://srv/share\\n\\{RUN_ID}"),
+ (
+ f'"vscode://file/C:\\\\Users\\\\bob\\\\new\\\\{RUN_ID}\\\\a"',
+ f'"vscode://file/C:\\\\Users\\\\bob\\\\new\\\\{RUN_ID}\\\\a"',
+ ),
+ (
+ f'"vscode://file/C:\\\\Users\\\\bob\\\\t\\\\runs\\\\{RUN_ID}"',
+ f'"vscode://file/C:\\\\Users\\\\bob\\\\t\\\\runs\\\\{RUN_ID}"',
+ ),
+ # `\X1B` and `\U001B` are not escapes, so they stay in the URL.
+ (f"vscode://file/C:\\work\\X1Bcache\\{RUN_ID}\\a.log", f"vscode://file/C:\\work\\X1Bcache\\{RUN_ID}\\a.log"),
+ (f"https://h.test/x\\t\\UBEEF\\{RUN_ID}\\a.log", f"https://h.test/x\\t\\UBEEF\\{RUN_ID}\\a.log"),
+ (f"https://h.test/x\\t\\x64\\runs\\{RUN_ID}\\a.log", f"https://h.test/x\\t\\x64\\runs\\{RUN_ID}\\a.log"),
+ (f"https://h.test/x\\t\\x64\\U1234\\{RUN_ID}\\a.log", f"https://h.test/x\\t\\x64\\U1234\\{RUN_ID}\\a.log"),
+ # An escaped character after `\\n` makes it an escape, so the URL ends there.
+ (f"'https://h.test/e\\n\\xa0/srv/ci/runs/{RUN_ID}/a'", f"'https://h.test/e\\n{RUN_ID}/a'"),
+ (f"https://ci.example.test/runs/{RUN_ID}/log", f"https://ci.example.test/runs/{RUN_ID}/log"),
+ ("https://h.test/?path=/home/alice/x", "https://h.test/?path=/home/alice/x"),
+ # A file name that starts with n, r or t and has no backslash after it
+ # reads as an escape, so the URL ends there and a path after it is masked.
+ (
+ f"http://localhost:8080/runs\\{RUN_ID}\\report.html?log=/home/alice/x",
+ f"http://localhost:8080/runs\\{RUN_ID}\\report.html?log=~/x",
+ ),
+ ],
+)
+def test_a_url_ends_where_a_path_after_it_can_start(text: str, expected: str) -> None:
+ scrub = _Scrubber.for_run(Path("/home/alice/runs") / RUN_ID, home=Path("/home/alice"))
+
+ assert scrub.paths(text) == expected
+
+
+ "text",
+ [
+ # JSON around repr text, or JSON or repr around JSON written with
+ # ensure_ascii=False: a doubled `\\n` or `\\t` before an escaped
+ # character such as `\u201c` or `\xa0` is two escapes, not a UNC
+ # server named n or t.
+ json.dumps({"message": "retry: " + repr(f"upload failed\n\u201c/srv/ci/bob/{RUN_ID}/result.json\u201d")}),
+ json.dumps(json.dumps({"m": f"run dir\n\u201c/srv/ci/bob/{RUN_ID}\u201d"}, ensure_ascii=False)),
+ json.dumps(json.dumps(f"x\n\U0001f4c1/srv/ci/bob/{RUN_ID}/a", ensure_ascii=False)),
+ json.dumps(repr(f"col1\t\u2022\\\\fs01\\ci\\bob\\{RUN_ID}")),
+ repr(json.dumps({"m": f"saved\n\xa0/srv/ci/bob/{RUN_ID}/out.json"}, ensure_ascii=False)),
+ json.dumps(repr(f"saved\n\xa0/srv/ci/bob/{RUN_ID}/out.json")),
+ repr(f"saved\n\xa0/srv/ci/bob/{RUN_ID}/out.json"),
+ repr(f"saved\n\u201c/srv/ci/bob/{RUN_ID}/out.json\u201d".encode()),
+ repr("saved\n" + "\xa0" * 9 + f"/srv/ci/bob/{RUN_ID}/out.json"),
+ ],
+)
+def test_a_copied_run_after_a_line_escape_and_an_escaped_character_is_masked(text: str) -> None:
+ scrub = _Scrubber.for_run(Path("/home/alice/runs") / RUN_ID, home=Path("/home/alice"))
+
+ masked = scrub.paths(text)
+
+ assert RUN_ID in masked
+ assert "bob" not in masked
+ assert "srv" not in masked
+
+
+ ("text", "expected"),
+ [
+ (
+ json.dumps({"stderr": f"/opt/app/a.py\r\x1b[K/opt/app/b.py\r\x1b[K/srv/ci/bob/{RUN_ID}/agent.log"}),
+ json.dumps({"stderr": f"/opt/app/a.py\r\x1b[K/opt/app/b.py\r\x1b[K{RUN_ID}/agent.log"}),
+ ),
+ (
+ repr(f"see https://h.test/e\n\u201c/srv/ci/runs/{RUN_ID}/a".encode()),
+ repr(f"see https://h.test/e\n{RUN_ID}/a".encode()),
+ ),
+ (repr(f"saved\n\xa0\xa0/srv/ci/bob/{RUN_ID}"), f"'saved\\n{RUN_ID}'"),
+ (repr(f"saved\n\u201c/srv/ci/bob/{RUN_ID}".encode()), f"b'saved\\n{RUN_ID}'"),
+ # A folder named n, r or t before a non-ASCII one, in JSON or ascii().
+ (json.dumps(f"C:\\Users\\bob\\t\\\u00e9cole\\{RUN_ID}"), json.dumps(RUN_ID)),
+ (ascii(f"D:\\data\\n\\\u00e9cole\\{RUN_ID}"), repr(RUN_ID)),
+ ],
+)
+def test_encoded_text_keeps_escapes_and_codes_around_a_masked_path(text: str, expected: str) -> None:
+ scrub = _Scrubber.for_run(Path("/home/alice/runs") / RUN_ID, home=Path("/home/alice"))
+
+ assert scrub.paths(text) == expected
+
+
+ "text",
+ [
+ # Folders named like escapes after a folder named n, r or t are
+ # folders when a name and as many backslashes follow the last one.
+ f"Saved to C:\\Users\\bob\\t\\x64\\x86\\{RUN_ID}",
+ json.dumps({"cwd": f"C:\\Users\\bob\\t\\x64\\x86\\{RUN_ID}"}),
+ repr({"cwd": f"C:\\Users\\bob\\t\\x64\\x86\\{RUN_ID}"}),
+ f"\\\\fs01\\builds\\bob\\r\\x64\\x64\\{RUN_ID}",
+ f"C:\\Users\\bob\\t\\x86_64\\x64\\{RUN_ID}\\a.log",
+ # A folder named like an escape may hold characters a name tail does not.
+ f"workspace D:\\ci\\bob\\n\\x64@2\\{RUN_ID}",
+ f"C:\\Users\\bob\\t\\x64+arm64\\{RUN_ID}",
+ f"C:\\Users\\bob\\t\\x64(1)\\{RUN_ID}",
+ ],
+)
+def test_escape_named_folders_after_a_folder_named_n_r_or_t_are_folders(text: str) -> None:
+ scrub = _Scrubber.for_run(PureWindowsPath(r"C:\Users\alice\runs") / RUN_ID)
+
+ masked = scrub.paths(text)
+
+ assert RUN_ID in masked
+ assert "bob" not in masked
+
+
+def test_this_machines_unc_run_dir_after_a_doubled_line_escape_is_masked() -> None:
+ scrub = _Scrubber.for_run(PureWindowsPath(r"\\NAS01\share\runs") / RUN_ID)
+ text = json.dumps(json.dumps({"m": f"run dir\n\u201c\\\\nas01\\share\\runs\\{RUN_ID}\u201d"}, ensure_ascii=False))
+
+ assert "nas01" not in scrub.paths(text)
+
+
+def test_url_matching_stays_linear_on_long_dotted_text() -> None:
+ # An unbounded scheme was rescanned from every word boundary, so 300,000
+ # characters of `a.a.a` took minutes. The regex holds the GIL, so a thread
+ # cannot time it out; a child process is killed instead. The budget is far
+ # above the linear time (well under a second).
+ import subprocess
+ import sys
+
+ code = (
+ "from pathlib import Path\n"
+ "from skillevaluator.evaluation.tier3_feedback_chat import _Scrubber\n"
+ "text = 'a.' * 150_000\n"
+ "assert _Scrubber.for_run(Path('/runs') / 'run-1').paths(text) == text\n"
+ )
+
+ subprocess.run([sys.executable, "-c", code], check=True, timeout=60)
+
+
+def test_path_masking_stays_linear_on_long_backslash_runs() -> None:
+ # A long run of backslashes, inside a URL or glued to a name before a
+ # copied run's ID, is scanned once, not again from each of its backslashes.
+ # See test_url_matching_stays_linear_on_long_dotted_text for the budget.
+ import subprocess
+ import sys
+
+ code = (
+ "from pathlib import Path\n"
+ "from skillevaluator.evaluation.tier3_feedback_chat import _Scrubber\n"
+ "scrub = _Scrubber.for_run(Path('/runs') / 'run-1')\n"
+ "text = 'https://h.test/a' + '\\\\' * 200_000 + 'x'\n"
+ "assert scrub.paths(text) == text\n"
+ "text = 'a' + '\\\\' * 200_000 + '\\\\run-1'\n"
+ "assert scrub.paths(text) == text\n"
+ "assert 'run-1' in scrub.paths('C:' + '\\\\t' * 50_000 + '\\\\run-1')\n"
+ "assert 'run-1' in scrub.paths('\\\\n' * 50_000 + '\\\\srv\\\\run-1')\n"
+ )
+
+ subprocess.run([sys.executable, "-c", code], check=True, timeout=60)
+
+
def test_context_redacts_credentials_but_keeps_measurements() -> None:
payload = {
"agents": {