Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(router): ignore shell operators inside quoted arguments in read detection (#4646)

HetCreep8cdce172ea5b
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index c43c85321..db567dcd0 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -880,9 +880,72 @@ def _command_segments(command: str) -> list[str]:
Splits on ``;``, ``&&`` and ``||`` — never on a single ``|``. Pipelines are kept
whole so the segment's own writes (``cat a.py | tee b.py``) stay visible; the
- reduction to the first stage happens in :func:`_segment_is_read`.
+ reduction to the first stage happens in :func:`_segment_is_read`. Separators inside
+ quotes (``sed -n '/a;b/p' foo.py``) are part of an argument, not a new command.
"""
- return [seg.strip() for seg in _CMD_SEPARATOR_RE.split(command) if seg.strip()]
+ masked = _mask_quoted(command)
+ segments: list[str] = []
+ start = 0
+ for m in _CMD_SEPARATOR_RE.finditer(masked):
+ segments.append(command[start : m.start()])
+ start = m.end()
+ segments.append(command[start:])
+ return [seg.strip() for seg in segments if seg.strip()]
+
+
+def _mask_quoted(command: str) -> str:
+ """Return ``command`` with quoted, escaped and commented characters replaced by ``_``.
+
+ The result has the same length, so match positions map back onto ``command``.
+ Shell operators inside quotes (``sed -n '/x >/p' foo.py``), after a backslash, or
+ inside a comment are not shell syntax, and a search over the masked string does
+ not mistake them for a redirect, pipe or command separator. The quote characters
+ themselves are kept.
+
+ Two shell rules keep word boundaries intact: a backslash-newline is a line
+ continuation, so both characters become spaces (``cat a.py \\<newline>> b.py``
+ still writes ``b.py``); and a ``#`` at the start of a word starts a comment that
+ runs to the end of the line, so quote marks inside it do not open a quote that
+ would hide the next line's separators.
+ """
+ out = list(command)
+ quote = ""
+ i = 0
+ n = len(command)
+ word_start = True
+ while i < n:
+ char = command[i]
+ if char == "\\" and quote != "'":
+ if i + 1 < n and command[i + 1] == "\n":
+ # Line continuation: the shell removes both characters.
+ out[i] = out[i + 1] = " "
+ word_start = True
+ else:
+ out[i] = "_"
+ if i + 1 < n:
+ out[i + 1] = "_"
+ word_start = False
+ i += 2
+ continue
+ if quote:
+ if char == quote:
+ quote = ""
+ else:
+ out[i] = "_"
+ elif char in {"'", '"'}:
+ quote = char
+ word_start = False
+ elif char == "#" and word_start:
+ # Comment to end of line; the newline itself stays visible.
+ while i < n and command[i] != "\n":
+ out[i] = "_"
+ i += 1
+ word_start = True
+ continue
+ else:
+ word_start = char.isspace() or char in ";&|()"
+ i += 1
+ return "".join(out)
def _segment_is_read(c: str) -> bool:
@@ -890,9 +953,15 @@ def _segment_is_read(c: str) -> bool:
# A redirect or `tee` in THIS segment means the segment writes a file rather than
# reading one (`cat a.py > copy.py`, `cat a.py | tee copy.py`). Checked on the whole
# segment — pipeline included — before reducing to the stage that touches the file.
- if re.search(r"(^|\s)(>>?|tee\b)", c):
+ # Both checks run on the quote-masked segment: a `>` or `|` inside a quoted sed
+ # script (`sed -n '/x >/p' a.py`) is part of the argument, not shell syntax.
+ masked = _mask_quoted(c)
+ if re.search(r"(^|\s)(>>?|tee\b)", masked):
return False
- c = c.split("|", 1)[0].strip()
+ pipe = masked.find("|")
+ if pipe != -1:
+ c = c[:pipe]
+ c = c.strip()
if not c:
return False
# Parse the real program with the SAME structural parser the search-fold uses
diff --git a/tests/test_transforms/test_read_command_detection.py b/tests/test_transforms/test_read_command_detection.py
index 7419a2c36..906ed2703 100644
--- a/tests/test_transforms/test_read_command_detection.py
+++ b/tests/test_transforms/test_read_command_detection.py
@@ -123,6 +123,50 @@ def test_non_reads_are_not_detected(command: str) -> None:
assert _is_read_command(command) is False
+ ("command", "expected"),
+ [
+ # Shell operators inside a quoted sed script are part of the argument (#4478).
+ ("sed -n '/x >/p' foo.py", True),
+ ("sed -n '/x >> y/p' foo.py", True),
+ ('sed -n "/a > b/p" foo.py', True),
+ ("sed -n '/a|b/p' foo.py", True),
+ ("sed -n '/a;b/p' foo.py", True),
+ ("sed -n '/a && b/p' foo.py", True),
+ ("sed -n '/ tee /p' foo.py", True),
+ ("cat 'a > b.py'", True),
+ # An escaped operator is a literal argument too.
+ (r"cat foo.py \> out", True),
+ # Real operators next to a quoted script still count.
+ ("sed -n '/x >/p' foo.py > out.txt", False),
+ ("sed -n '/a|b/p' foo.py | tee out.txt", False),
+ ("sed -n '/a;b/p' foo.py; echo done", True),
+ ("echo '>' && sed 's/a/b/' foo.py", False),
+ # The -c argument of a shell is quoted at the outer level; the inner
+ # command is checked on its own.
+ ('bash -lc "cat foo.py > copy.py"', False),
+ ('bash -lc "cat foo.py | tee copy.py"', False),
+ ('bash -lc "cat foo.py"', True),
+ # A backslash-newline is a line continuation: the write on the next line
+ # still counts (review of #4646).
+ ("cat foo.py \\\n> copy.py", False),
+ ("cat foo.py \\\n>> copy.py", False),
+ ("cat foo.py | \\\ntee copy.py", False),
+ ("sed -n '/x >/p' foo.py \\\n> out.txt", False),
+ ("sed -n '1,60p' \\\nfoo.py", True),
+ # A comment ends at the newline; its quote marks do not open a quote that
+ # would hide the next line's separators (review of #4646).
+ ('echo start # " unclosed in comment\nls; cat foo.py', True),
+ ("echo ok # author's note\ntrue; cat foo.py", True),
+ ("cat foo.py # > not a redirect", True),
+ # A hash inside a word is not a comment.
+ ("cat foo#bar.py > out.txt", False),
+ ],
+)
+def test_quoted_shell_operators_are_arguments(command: str, expected: bool) -> None:
+ assert _is_read_command(command) is expected
+
+
def test_heredoc_body_is_not_split_into_a_bogus_read() -> None:
"""A `;` inside a heredoc body must not produce a segment that looks like a
read — the command as a whole writes a file."""