Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(distill): shared shell lexer for the rewrite hook, wider safe pipe tails (#1070)

Raghav Chamadiyaa24a9ac83400
diff --git a/docs/agent/DISTILL.md b/docs/agent/DISTILL.md
index 45288b483..968c172e9 100644
--- a/docs/agent/DISTILL.md
+++ b/docs/agent/DISTILL.md
@@ -37,13 +37,15 @@ repowise saved # tokens & dollars saved so far
Runs the command (shell semantics preserved), captures stdout+stderr, picks a
filter by command shape (then by content sniff), and prints the compact
-rendering. Nine filters ship:
+rendering. Eleven filters ship:
| Filter | Commands | What it keeps |
|---|---|---|
| `test_output` | pytest, jest, vitest, cargo test, go test | failures + assertion details + summary; collapses pass parades |
| `build_output` | npm/tsc/cargo/go builds | errors and warnings grouped; strips progress/boilerplate |
| `lint_output` | eslint/biome, ruff/flake8/mypy, clippy, golangci-lint | errors verbatim; warnings grouped by rule id with counts + file:line anchors; fixable totals |
+| `install_output` | pip, uv, poetry, npm/pnpm/yarn install, cargo install, brew, bundle, composer | what actually changed + the final summary; drops resolver and download progress. An all-satisfied run collapses to `install: ok (no changes)` |
+| `infra_plan` | `terraform`/`tofu plan`, `helm diff`/`upgrade` | the `Plan: N to add…` summary and the resources that change; drops unchanged-resource dumps. A no-op collapses to `plan: no changes` |
| `git_status` | `git status` | porcelain-style compact status |
| `git_log` | `git log` | recent subjects + counts |
| `git_diff` | `git diff`/`show` | stat + the most relevant hunks |
@@ -114,9 +116,11 @@ The hook is deliberately conservative. It never rewrites:
- redirections, compound commands (`>`, `&&`, `;`, backticks, `$()`) and
almost all pipes. Two safe shapes are carved out: a trailing `2>&1`
(distill merges stderr into its capture anyway), and, on macOS/Linux only,
- a single pipe into bare `head`/`tail`, which runs unchanged inside
- distill's own shell (`pytest -q | head -50` →
- `repowise distill "pytest -q | head -50"`)
+ a single pipe into a bare stdin filter — `head`, `tail`, `grep`, `egrep`,
+ `fgrep`, `rg` — which runs unchanged inside distill's own shell
+ (`pytest -q | head -50` → `repowise distill "pytest -q | head -50"`).
+ The `grep`/`rg` pattern-file forms (`-f`, `--file`) are excluded: they read
+ a file as configuration rather than filtering stdin
- watch/follow modes (`--watch`, `tail -f`, …)
- anything on the trivial-command ignore-list, or already-prefixed commands
- PowerShell-native constructs: `Verb-Noun` cmdlets, `& "path"` invocations,
@@ -124,6 +128,15 @@ The hook is deliberately conservative. It never rewrites:
`find`, …) that don't mean what their unix namesakes mean
- commands in repos that have not opted into repowise (no `.repowise/` upward)
+These decisions are made by tokenizing the command, not by scanning it for
+punctuation, so on macOS/Linux a shell character sitting inside quotes is
+treated as the text it is: `pytest -k "a|b"` is a normal test run, not a
+pipeline, and is rewritten as one. On Windows the blunter rule stands — any
+`|`, `&`, `;`, `<`, `>` or backtick anywhere in the command, quoted or not,
+passes it through untouched — because `cmd.exe` re-parses metacharacters that
+the argv quoting Windows uses does not cover. The conservative answer always
+wins the ambiguity; an unrecognized shape is left alone.
+
**The allowlist trap.** A rewrite changes the command string, so a Claude Code
permission rule you already had — say `Bash(git diff:*)` — no longer matches
the rewritten `repowise distill git diff …`, and the permission prompt comes
@@ -353,6 +366,18 @@ the distilled test output — identical conclusion to the raw-output run.
Fixture-suite medians across the core filters: ≥60% reduction on
test/build/lint output with zero error-line loss (asserted in CI).
+Install and infra-plan logs compress harder, because they are mostly repeated
+boilerplate. Measured on real captures from this repository, one run each:
+
+| Command | Saved |
+|---|---:|
+| `npm ci` (1,344 packages) | **99.5%** |
+| `pip install` (everything already satisfied) | collapses to `install: ok (no changes)` |
+| `terraform plan` | **80.2%** |
+
+Every one of those still round-trips through `repowise expand`, and the error
+line in a failing install survives verbatim.
+
---
## Configuration
@@ -388,7 +413,7 @@ and whether the rewrite hook is installed.
| A filter eats a critical line | errors-first invariant + fixture tests + `expand` recovery + fallback-to-raw |
| Silent permission escalation | rewrites default to `ask`; the user sees the modified command. Codex has no ask primitive, so only families explicitly set to `allow` rewrite there |
| Marker with nothing behind it | content stored *before* the marker renders; store failure ⇒ raw output |
-| Compound-command semantics | pipes/redirects/`&&` are never rewritten |
+| Compound-command semantics | compound commands, substitution and redirects are never rewritten. The one pipe shape that is (a single stage into a bare stdin filter, macOS/Linux only) is passed through as one quoted token and runs verbatim in distill's shell; anything that could break out of that quoting bails |
| Unindexed or stale repo | filters work index-free; index only improves ranking |
| Store growth | TTL + size cap, pruned on write; `repowise doctor` reports size |
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index bfccefd2e..2167959e7 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -153,7 +153,9 @@ repowise hook rewrite uninstall
```
- Defaults to **`ask`**, so you approve every rewritten command before it runs.
-- Never rewrites pipes, compound commands, or watch modes.
+- Never rewrites compound commands, redirections, or watch modes. The one pipe
+ shape it handles (macOS/Linux) is a single stage into `head`, `tail`, `grep`
+ or `rg`, quoted whole so it runs unchanged inside distill's own shell.
- Installing also adds `Bash(repowise distill:*)` / `PowerShell(repowise distill:*)`
to `permissions.allow`, so an already-approved command family doesn't start
re-prompting just because its string changed.
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index bf0c0ffd5..1f343b2cb 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -141,8 +141,10 @@ distill:
- `permission: ask` (the default) means the agent's rewritten command is shown
for approval; `allow` auto-approves rewrites; `off` disables rewrites here.
- `families` keys are filter names (`test_output`, `build_output`,
- `lint_output`, `git_status`, `git_log`, `git_diff`, `search_results`,
- `file_listing`, `logs`) and accept `ask | allow | off | deny`.
+ `lint_output`, `install_output`, `infra_plan`, `git_status`, `git_log`,
+ `git_diff`, `search_results`, `file_listing`, `logs`) and accept
+ `ask | allow | off | deny`. `repowise doctor` validates these against the
+ live filter registry, so it always knows the current set.
- Declining the `repowise init` opt-in prompt writes
`commands.enabled: false`, so a rewrite hook installed globally from another
repo stays inert in this one.
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index ccd36440b..f5724979b 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -270,8 +270,9 @@ hook, which rewrites noisy commands automatically:
repowise hook rewrite install # or answer Yes at the init prompt
```
-It never rewrites pipes, compound commands or watch modes, and defaults to `ask`
-so you see every rewrite before it runs.
+It never rewrites compound commands, redirections or watch modes. The one pipe
+shape it does handle (on macOS/Linux) is a single stage into `head`, `tail`,
+`grep` or `rg`, which runs unchanged inside distill's own shell.
Track it with `repowise saved`, or the Costs page in the dashboard. Full guide:
[Distill](../agent/DISTILL.md).
diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.py
index 87fdc8cfa..bb4c3385c 100644
--- a/packages/cli/src/repowise/cli/rewrite_hook.py
+++ b/packages/cli/src/repowise/cli/rewrite_hook.py
@@ -8,8 +8,9 @@ uniformly across the main agent and every subagent. This is safe because
``classify`` only ever rewrites a closed set of recognized command families
(test/lint/build/git/search/listing/log) that survive the bailouts below —
no redirects, compound commands, substitution, or interactive commands,
-and the only pipe shape allowed is a single ``| head``/``| tail`` with no
-quoting to break out of. The rewrite is therefore always ``repowise distill
+and the only pipe shape allowed is a single stage into a bare stdin filter
+(``head``/``tail``/``grep``/``rg``) with no quoting to break out of. The
+rewrite is therefore always ``repowise distill
<one simple, recognized command>``, never an arbitrary command smuggled
behind the wrapper, so auto-allowing it is not a permission escalation. Users who want
to review every rewrite can set ``permission: ask`` in
@@ -29,10 +30,14 @@ Bailouts — commands never rewritten:
- redirections / compound commands (``> < && || ; &``), substitution
(backticks, ``$(``), multi-line commands: the wrapper would change
- shell semantics. Two safe tails are carved out: a trailing ``2>&1``
- (distill merges stderr into its capture anyway) and, on POSIX hosts,
- a single pipe into bare ``head``/``tail``; the whole pipeline is
- then quoted so it runs inside distill's own shell, unchanged;
+ shell semantics. ``shell_lexer`` decides this structurally, so an
+ operator that only *looks* like one because it sits inside quotes
+ (``git commit -m "fix a|b"``) is not a bailout. Two safe tails are
+ carved out: a trailing ``2>&1`` (distill merges stderr into its
+ capture anyway) and, on POSIX hosts, a single pipe into a bare stdin
+ filter (``head``/``tail``/``grep``/``egrep``/``fgrep``/``rg``); the
+ whole pipeline is then quoted so it runs inside distill's own shell,
+ unchanged;
- watch/follow modes (``--watch``, ``tail -f``): long-running,
interactive by design;
- the ignore-list of trivial or interactive commands (cd, echo, vim, …);
@@ -50,6 +55,7 @@ import tempfile
# import at module scope. (No pathlib: it costs double-digit milliseconds
# of interpreter startup, which this hook pays on every Bash call.)
from repowise.cli.agent_adapters.base import RewriteResult
+from repowise.cli.shell_lexer import analyze_pipeline
# ---------------------------------------------------------------------------
# Command normalization — a hot-path mirror of
@@ -191,65 +197,84 @@ IGNORED_FIRST_TOKENS = frozenset(
}
)
-# Shell syntax that changes meaning if the command is wrapped: pipes,
-# redirections, chaining, backgrounding, substitution, heredocs, newlines.
-# The same characters cover PowerShell's equivalents: `;` separators,
-# backtick line-continuation/escapes, `$(...)` subexpressions, pipelines,
-# and `& "path\to.exe"` call-operator invocations.
-_SHELL_SYNTAX_RE = re.compile(r"[|&;<>`\n]|\$\(")
-
# A stderr-merge suffix is the one redirection distill preserves for free:
# it captures both streams and interleaves them, so `cmd 2>&1` and
# `repowise distill cmd` (with the outer shell applying the now-vacuous
-# 2>&1 to distill's own empty stderr) see the same bytes.
+# 2>&1 to distill's own empty stderr) see the same bytes. Stripped before
+# the lexer runs so `pytest 2>&1 | grep FAIL` still classifies as pytest.
_STDERR_MERGE_RE = re.compile(r"\s+2>&1(?=\s|$)")
-# The only pipe tails safe to run inside distill's shell: bare head/tail
-# with at most a numeric count. Anything else (grep, awk, sort, xargs)
-# passes through untouched.
-_SAFE_PIPE_TAIL_RE = re.compile(r"^(?:head|tail)(?:\s+(?:-n\s*|-c\s*|-)\d+)?\s*$")
-
# Quoting the pipeline for distill's inner shell is only sound when nothing
-# in it can be re-expanded or break the quoting on the second pass.
+# in it can be re-expanded or break the quoting on the second pass. This
+# applies to the pipeline shape only: a command with no pipe is forwarded as
+# separate argv tokens, which distill re-quotes itself.
_PIPE_UNSAFE_CHARS = ('"', "'", "$", "\\")
-# distill executes via the system shell (cmd.exe on Windows, where head/tail
-# don't exist), so the safe-pipeline rewrite is POSIX-hosts-only. Module
-# constant so tests can pin both platforms' behavior.
+# distill executes via the system shell (cmd.exe on Windows, where
+# head/tail/grep don't exist), so the safe-pipeline rewrite is
+# POSIX-hosts-only. Module constant so tests can pin both platforms.
_POSIX_HOST = os.name == "posix"
+# Windows keeps the blunt character bail, quoted or not. Two reasons, both
+# downstream of this module:
+#
+# - distill rejoins its argv with ``subprocess.list2cmdline``, which quotes
+# for the C runtime's argv parser and not for cmd.exe. A token like
+# ``--grep=a&whoami`` holds no space, so it is emitted unquoted and
+# cmd.exe reads the ``&`` as a command separator. The lexer knows that
+# ``&`` was quoted text; the renderer downstream does not.
+# - PowerShell has no backslash escape, so a Windows path ending in ``\``
+# does not extend a quoted run the way the POSIX rules here assume.
+#
+# So the lexer's false-bail win is a POSIX win. On Windows it still buys the
+# structural bailouts, just not the widening.
+_WIN_SHELL_METACHAR_RE = re.compile(r"[|&;<>`^\n]|\$\(")
+
def _split_safe_tail(command: str) -> tuple[str, bool] | None:
"""Split *command* into (classifiable head, needs_inner_shell).
Returns None when the command carries shell syntax the wrapper can't
preserve. ``needs_inner_shell`` is True for the safe-pipeline shape
- (``cmd | head -N``): the caller must pass the whole command to
+ (``cmd | grep FAIL``): the caller must pass the whole command to
``repowise distill`` as one quoted token so the pipe executes inside
distill's own shell rather than binding to the wrapper.
+
+ The structural decisions (chaining, substitution, redirects, how many
+ stages, which tool ends the pipeline) come from ``shell_lexer``; what is
+ left here is the policy the lexer deliberately does not own — the
+ stderr-merge carve-out, the POSIX-host gate, and the quoting rules for
+ the one shape that gets re-quoted.
"""
- cmd = command.strip()
- # Classification always ignores stderr merges; `pytest 2>&1 | head`
- # still classifies as pytest.
- declawed = _STDERR_MERGE_RE.sub("", cmd)
- if not _SHELL_SYNTAX_RE.search(declawed):
- return declawed, False
- # One pipe into bare head/tail: run the pipeline inside distill.
- if not _POSIX_HOST:
- return None
- if any(ch in cmd for ch in _PIPE_UNSAFE_CHARS):
+ declawed = _STDERR_MERGE_RE.sub("", command.strip())
+ if not _POSIX_HOST and _WIN_SHELL_METACHAR_RE.search(declawed):
return None
- head_part, sep, tail_part = declawed.partition("|")
- if not sep or _SHELL_SYNTAX_RE.search(head_part) or _SHELL_SYNTAX_RE.search(tail_part):
+ pipeline = analyze_pipeline(declawed)
+ if pipeline is None or pipeline.redirects:
+ # Every redirect other than the stderr merge already stripped above
+ # would change what the wrapper captures.
return None
- if not _SAFE_PIPE_TAIL_RE.match(tail_part.strip()):
+ if pipeline.final_tool is None:
+ return pipeline.producer, False
+ # A pipeline is re-quoted as one token, so anything the inner shell would
+ # re-expand or that could break out of the quoting bails.
+ if not _POSIX_HOST or any(ch in command for ch in _PIPE_UNSAFE_CHARS):
return None
- return head_part.strip(), True
+ return pipeline.producer, True
# Watch/follow modes are long-running; wrapping them buffers forever.
_WATCH_RE = re.compile(r"--watch(?:all)?\b|--looponfail\b|(?:^|\s)-f\b.*\.log\b|--follow\b")
+# Every tool in the `logs` family can stream instead of returning, and the
+# flag that does it is bare `-f`/`-F` far more often than it is `--follow`.
+# `_WATCH_RE` only catches the `-f` form when a literal `.log` follows, which
+# misses `journalctl -f`, `docker logs -f web`, and `tail -f /var/log/syslog`.
+# Checking this per-family keeps `-f` meaning what it means elsewhere
+# (`make -f Makefile`, `docker compose -f x.yml` stay rewritable).
+_FOLLOW_FLAG_RE = re.compile(r"(?:^|\s)(?:-[a-z]*[fF]|--follow)(?:[\s=]|$)")
+_STREAMING_FAMILIES = frozenset({"logs"})
+
# PowerShell cmdlets all follow the Verb-Noun shape (Get-ChildItem,
# Select-Object, ForEach-Object, …), so a Verb-Noun first token is a safe
# fast bail — PS-native pipelines and object output don't survive wrapping
@@ -282,6 +307,8 @@ def _classify_head(head_command: str) -> str | None:
return None
for family, pattern in FAMILY_PATTERNS:
if pattern.match(normalized):
+ if family in _STREAMING_FAMILIES and _FOLLOW_FLAG_RE.search(normalized):
+ return None
return family
return None
@@ -309,9 +336,7 @@ def _find_repo_root(cwd: str) -> str | None:
# artifact (a tool that indexed with cwd=$TMP), never an opt-in, and
# it would otherwise capture every temp-dir cwd on the machine.
# Repos legitimately created UNDER either directory still match.
- if current not in (home, temp_root) and os.path.isdir(
- os.path.join(current, ".repowise")
- ):
+ if current not in (home, temp_root) and os.path.isdir(os.path.join(current, ".repowise")):
return current
parent = os.path.dirname(current)
if parent == current:
diff --git a/packages/cli/src/repowise/cli/shell_lexer.py b/packages/cli/src/repowise/cli/shell_lexer.py
new file mode 100644
index 000000000..fa48f0204
--- /dev/null
+++ b/packages/cli/src/repowise/cli/shell_lexer.py
@@ -0,0 +1,286 @@
+"""A single-pass shell tokenizer for the rewrite hot path.
+
+``rewrite_hook`` fires before every shell command an AI agent runs, so this
+module is stdlib-only and import-cheap by design: no ``repowise.core``, no
+third-party imports, no module-level work beyond building a few frozensets.
+``test_rewrite_perf`` pins both properties.
+
+It replaces the hook's older approach — a regex that bailed on *any* of
+``[|&;<>`]`` plus a blanket bail on any quote — with a state machine that
+knows where quoting starts and stops. Two payoffs:
+
+1. **Fewer false bails.** ``git commit -m "fix a|b"`` used to bail because it
+ contains both a quote and a pipe, even though the pipe is inside the
+ quotes. The lexer sees one segment and no operator.
+2. **Structural pipeline analysis.** A single pipe into a stdin-consuming
+ filter (``grep``/``rg``/``head``/``tail``) is recognized by shape rather
+ than by a bespoke regex per tail shape, so the producer stage can be
+ classified while the pipeline still runs verbatim.
+
+Nothing here decides policy about *executing* a command; it reports
+structure. The hook owns the platform gate and the quoting rules.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+__all__ = [
+ "SAFE_FINAL_TOOLS",
+ "Pipeline",
+ "Token",
+ "analyze_pipeline",
+ "render",
+ "tokenize",
+]
+
+
+@dataclass(frozen=True, slots=True)
+class Token:
+ """One lexed piece of a command line.
+
+ ``kind`` is one of ``"arg"`` (a word, with any quoting preserved
+ verbatim), ``"op"`` (something that ends a simple command: ``&&``,
+ ``||``, ``;``, ``&``, a newline, a backtick, ``$(``), ``"pipe"``
+ (``|`` or the stderr-pipe ``|&``), or ``"redirect"`` (``>``, ``>>``,
+ ``<``, ``2>&1``, …).
+ """
+
+ kind: str
+ text: str
+
+
+def tokenize(command: str) -> list[Token]:
+ """Split *command* into structural tokens in a single left-to-right pass.
+
+ Quotes and backslash escapes bind their contents into the surrounding
+ argument (and are kept verbatim, so ``" ".join`` of the argument texts
+ round-trips a normally-spaced command). Operators, pipes, and redirects
+ split arguments apart.
+ """
+ tokens: list[Token] = []
+ buffer: list[str] = []
+ index, length = 0, len(command)
+
+ def flush() -> None:
+ if buffer:
+ tokens.append(Token("arg", "".join(buffer)))
+ buffer.clear()
+
+ while index < length:
+ char = command[index]
+ if char in " \t":
+ flush()
+ index += 1
+ elif char in "\r\n":
+ # A newline separates commands exactly like ``;`` does; treating
+ # it as whitespace would silently merge two commands into one.
+ flush()
+ tokens.append(Token("op", "\n"))
+ index += 2 if command[index : index + 2] == "\r\n" else 1
+ elif char == "\\" and index + 1 < length:
+ if command[index + 1] in "\r\n":
+ # Line continuation: the command spans lines, which callers
+ # are told is a bailout. Surface it as one rather than
+ # hiding the newline inside an argument.
+ flush()
+ tokens.append(Token("op", "\\\n"))
+ index += 2
+ continue
+ buffer.append(command[index : index + 2])
+ index += 2
+ elif char in "\"'":
+ # Copy the quoted run verbatim, quotes included.
+ quote = char
+ end = index + 1
+ while end < length and command[end] != quote:
+ if command[end] == "\\" and quote == '"' and end + 1 < length:
+ end += 2
+ continue
+ end += 1
+ if end >= length:
+ # Unterminated: everything after the opening quote is
+ # unparseable, so no structural claim about it is honest.
+ # Emit an operator and let every caller bail.
+ flush()
+ tokens.append(Token("op", quote))
+ break
+ buffer.append(command[index : end + 1])
+ index = end + 1
+ elif char == "|":
+ flush()
+ following = command[index + 1] if index + 1 < length else ""
+ if following == "|":
+ tokens.append(Token("op", "||"))
+ index += 2
+ elif following == "&":
+ tokens.append(Token("pipe", "|&"))
+ index += 2
+ else:
+ tokens.append(Token("pipe", "|"))
+ index += 1
+ elif char in "&;":
+ flush()
+ if char == "&" and command[index + 1 : index + 2] == "&":
+ tokens.append(Token("op", "&&"))
+ index += 2
+ else:
+ tokens.append(Token("op", char))
+ index += 1
+ elif char in "<>":
+ # A leading file-descriptor digit (the ``2`` in ``2>&1``) abuts
+ # the operator with no space, so it is sitting in the buffer as
+ # its own word — pull it back into the redirect token. Without
+ # this the command re-renders as ``cmd 2 >&1``, which is a
+ # different (and broken) command.
+ descriptor = ""
+ pending = "".join(buffer)
+ if pending.isdigit():
+ descriptor = pending
+ buffer.clear()
+ flush()
+ end = index
+ while end < length and command[end] in "<>":
+ end += 1
+ # ``>&2`` / ``>&-`` duplicate or close a descriptor; a bare ``&``
+ # after the operator is the background operator instead, and must
+ # stay its own token (``cmd 2>&1 &`` is two things, not one).
+ target = command[end + 1 : end + 2]
+ if command[end : end + 1] == "&" and target and target in "-0123456789":
+ end += 2
+ while end < length and command[end].isdigit():
+ end += 1
+ tokens.append(Token("redirect", descriptor + command[index:end]))
+ index = end
+ elif char == "`":
+ flush()
+ tokens.append(Token("op", "`"))
+ index += 1
+ elif char == "$" and command[index + 1 : index + 2] == "(":
+ flush()
+ tokens.append(Token("op", "$("))
+ index += 2
+ else:
+ buffer.append(char)
+ index += 1
+ flush()
+ return tokens
+
+
+def render(tokens: list[Token]) -> str:
+ """Re-render *tokens* as a command string with single-space separation.
+
+ Argument text keeps its original quoting and redirects keep their file
+ descriptor (``2>&1`` never becomes ``2 >&1``), so the result means what
+ the original meant. It is not a byte round-trip: runs of whitespace
+ collapse to one space, and a redirect written flush against its target
+ (``2>/dev/null``) gains a space before it.
+ """
+ return " ".join(token.text for token in tokens).strip()
+
+
+#: Final pipeline stages whose only job is to filter stdin, so the stage
+#: before them still owns the interesting output. The pattern-file forms of
+#: grep/rg (``-f``/``--file``) are excluded by ``analyze_pipeline``: they read
+#: a file as config, which changes what the stage consumes.
+SAFE_FINAL_TOOLS = frozenset({"grep", "egrep", "fgrep", "rg", "head", "tail"})
+
+
+@dataclass(frozen=True, slots=True)
+class Pipeline:
+ """Structure of a command that is at most one plain ``|`` pipeline.
+
+ ``producer`` is the re-rendered first stage (the whole command when
+ there is no pipe), ``final_tool`` is the bare tool name of the filtering
+ stage or None when there is no pipe, and ``redirects`` collects every
+ redirect token seen in any stage so callers can apply their own policy.
+ """
+
+ producer: str
+ final_tool: str | None
+ redirects: tuple[str, ...]
+
+
+def _basename(word: str) -> str:
+ """Bare tool name from an argument, ignoring quoting and any path."""
+ return word.strip("\"'").rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
+
+
+def _short_cluster(arg: str) -> str:
+ """The bundled short flags in *arg*, or "" if it is not a short group."""
+ if len(arg) > 1 and arg[0] == "-" and arg[1] != "-":
+ return arg[1:]
+ return ""
+
+
+def _disqualifies_final_stage(tool: str, args: list[str]) -> bool:
+ """True if *args* stop *tool* from being a plain one-shot stdin filter.
+
+ Two different reasons, so the check is tool-aware rather than a shared
+ flag blocklist (``-F`` means "fixed strings" to grep and "follow" to
+ tail; blocking it for both would cost real coverage):
+
+ - ``head``/``tail`` in follow mode never close the pipe, so the producer
+ is never signalled and the capture never returns.
+ - ``grep``/``rg`` given ``-f``/``--file`` read a file as their pattern
+ list, which is a different command than the one being reasoned about.
+ """
+ if tool in ("head", "tail"):
+ for arg in args:
+ if arg == "--follow" or arg.startswith("--follow="):
+ return True
+ cluster = _short_cluster(arg)
+ if "f" in cluster or "F" in cluster:
+ return True
+ return False
+ for arg in args:
+ if arg in ("-f", "--file") or arg.startswith("--file="):
+ return True
+ # ``-f`` takes a value, so in a bundle it is always last (``-if x``)
+ # or carries the value attached (``-fx``).
+ if "f" in _short_cluster(arg):
+ return True
+ return False
+
+
+def analyze_pipeline(command: str) -> Pipeline | None:
+ """Describe *command* as a simple pipeline, or return None to bail.
+
+ None means the command carries structure a wrapper cannot preserve:
+ chaining or backgrounding (``&&``, ``||``, ``;``, ``&``, newline),
+ substitution (backticks, ``$(``), a stderr pipe (``|&``), three or more
+ stages, or a final stage that is not one of ``SAFE_FINAL_TOOLS``.
+ Redirects are *reported*, not rejected, since which ones are tolerable
+ depends on the caller.
+ """
+ tokens = tokenize(command)
+ if any(token.kind == "op" for token in tokens):
+ return None
+
+ segments: list[list[Token]] = [[]]
+ for token in tokens:
+ if token.kind == "pipe":
+ if token.text != "|":
+ return None # ``|&`` also pipes stderr: not a plain filter
+ segments.append([])
+ else:
+ segments[-1].append(token)
+
+ redirects = tuple(t.text for t in tokens if t.kind == "redirect")
+ if len(segments) == 1:
+ producer = render(segments[0])
+ return Pipeline(producer, None, redirects) if producer else None
+ if len(segments) != 2:
+ return None # 3+ stages: not worth the hot-path complexity
+
+ producer_tokens, final_tokens = segments
+ final_args = [t.text for t in final_tokens if t.kind == "arg"]
+ if not final_args:
+ return None
+ tool = _basename(final_args[0])
+ if tool not in SAFE_FINAL_TOOLS or _disqualifies_final_stage(tool, final_args[1:]):
+ return None
+ producer = render(producer_tokens)
+ if not producer:
+ return None
+ return Pipeline(producer, tool, redirects)
diff --git a/tests/unit/distill/test_cli.py b/tests/unit/distill/test_cli.py
index 644b02d0c..570f5fb6c 100644
--- a/tests/unit/distill/test_cli.py
+++ b/tests/unit/distill/test_cli.py
@@ -2,13 +2,15 @@
from __future__ import annotations
+import os
+import shlex
import sys
from pathlib import Path
import pytest
from click.testing import CliRunner
-from repowise.cli.commands.distill_cmd import distill_command
+from repowise.cli.commands.distill_cmd import _render_command, distill_command
from repowise.cli.commands.expand_cmd import expand_command
from repowise.core.distill.markers import parse_marker_refs
from repowise.core.distill.store import OmissionStore
@@ -57,6 +59,54 @@ def test_distill_failing_git_command_keeps_exit_code(repo_cwd: Path) -> None:
assert result.exit_code != 0
[email protected](os.name != "posix", reason="cmd.exe has no grep")
+def test_distill_runs_a_pipeline_passed_as_one_token(repo_cwd: Path) -> None:
+ """One argv token containing a pipe must execute AS a pipeline.
+
+ This is the execution model the rewrite hook's safe-pipeline shape
+ depends on: the hook quotes the whole pipeline so the pipe binds inside
+ distill's own shell. The producer prints a line only grep can remove, so
+ the assertion fails if the pipe silently did not run.
+ """
+ script = (
+ "for i in range(40): "
+ "print('Requirement already satisfied: pkg%d in /venv/site-packages' % i)\n"
+ "print('ZZZDROPME')\n"
+ "print('Successfully installed flask-3.1.0')"
+ )
+ pipeline = f"{shlex.quote(sys.executable)} -c {shlex.quote(script)} | grep -v ZZZDROPME"
+
+ result = CliRunner().invoke(distill_command, [pipeline])
+
+ assert result.exit_code == 0
+ # Proof the pipe ran: only grep could have dropped this line.
+ assert "ZZZDROPME" not in result.output
+ # Proof distill still distilled what came back out of it.
+ assert "Successfully installed flask-3.1.0" in result.output
+ refs = parse_marker_refs(result.output)
+ assert refs, f"no recoverable marker in:\n{result.output}"
+ assert CliRunner().invoke(expand_command, [refs[0]]).exit_code == 0
+
+
+def test_render_command_quotes_shell_metacharacters() -> None:
+ """argv tokens must not turn into shell syntax when distill rejoins them.
+
+ The rewrite hook leans on this for every non-pipe command it forwards as
+ separate tokens: ``pytest -k "a|b"`` must run as one command, not a
+ pipeline. POSIX ``shlex.join`` gets it right. Windows
+ ``list2cmdline`` quotes for the C runtime's argv parser rather than for
+ cmd.exe, so a metacharacter with no surrounding space rides through
+ unquoted — which is exactly why the hook refuses those commands outright
+ on non-POSIX hosts (see
+ ``test_rewrite_hook.py::test_quoted_metacharacters_still_bail_on_windows``).
+ """
+ rendered = _render_command(("git", "log", "--grep=a&&b"))
+ if os.name == "posix":
+ assert rendered == "git log '--grep=a&&b'"
+ else:
+ assert rendered == "git log --grep=a&&b"
+
+
def test_distill_and_expand_roundtrip(repo_cwd: Path, fixtures_dir: Path) -> None:
raw = (fixtures_dir / "distill" / "git_log_full.txt").read_text(encoding="utf-8-sig")
from repowise.core.distill import distill_output
diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.py
index 73473d5f2..716ee7966 100644
--- a/tests/unit/distill/test_rewrite_hook.py
+++ b/tests/unit/distill/test_rewrite_hook.py
@@ -106,7 +106,7 @@ class TestClassify:
"python script.py",
"node server.js",
# compound / pipes / redirections / substitution
- "pytest | grep FAIL",
+ "pytest | awk '{print $1}'",
"pytest && echo done",
"pytest || true",
"git status; ls",
@@ -183,11 +183,12 @@ class TestClassify:
class TestSafeTails:
- """The two shell-syntax carve-outs: trailing ``2>&1`` and ``| head/tail``.
+ """The two shell-syntax carve-outs: trailing ``2>&1`` and one pipe into
+ a bare stdin filter (head/tail/grep/egrep/fgrep/rg).
``2>&1`` is platform-neutral (distill merges stderr into its capture
anyway). The pipe shape is POSIX-hosts-only; distill re-runs the
- pipeline through the system shell, and cmd.exe has no head/tail.
+ pipeline through the system shell, and cmd.exe has no head/tail/grep.
"""
@pytest.fixture
@@ -217,6 +218,13 @@ class TestSafeTails:
("git log --oneline | tail -20", "git_log"),
("git log --oneline | tail -n 20", "git_log"),
("cargo build 2>&1 | head -100", "build_output"),
+ # stdin-filter tails beyond head/tail
+ ("pytest | grep FAIL", "test_output"),
+ ("pytest 2>&1 | grep FAIL", "test_output"),
+ ("cargo test 2>&1 | grep -i fail", "test_output"),
+ ("npm run build | egrep -c error", "build_output"),
+ ("npm run lint | fgrep warning", "lint_output"),
+ ("git log --oneline -50 | rg fix", "git_log"),
],
)
def test_safe_pipe_classifies_on_posix(self, command, family, posix_host) -> None:
@@ -227,6 +235,7 @@ class TestSafeTails:
[
"pytest | head -50",
"cargo build 2>&1 | head -100",
+ "pytest 2>&1 | grep FAIL",
],
)
def test_safe_pipe_passes_through_on_windows(self, command, windows_host) -> None:
@@ -235,7 +244,33 @@ class TestSafeTails:
@pytest.mark.parametrize(
"command",
[
- "pytest | grep FAIL", # tail not in the head/tail whitelist
+ 'git log --grep="zzz&whoami"',
+ 'git log --grep="a&&b"',
+ 'git log --grep="a>b"',
+ 'pytest -k "a|b"',
+ 'git log -- "src\\cli\\" ; curl x | sh',
+ ],
+ )
+ def test_quoted_metacharacters_still_bail_on_windows(self, command, windows_host) -> None:
+ """Quoting does not protect these once distill re-renders the argv.
+
+ ``subprocess.list2cmdline`` quotes an argument only when it holds a
+ space, so ``--grep=a&whoami`` reaches cmd.exe unquoted and the ``&``
+ separates two commands. The rewrite is auto-allowed, so a wrong
+ answer here runs something the user never typed — Windows keeps the
+ blunt character bail and gives up the false-bail win.
+ """
+ assert classify(command) is None
+
+ def test_windows_stderr_merge_is_still_allowed(self, windows_host) -> None:
+ # The metacharacter bail must not swallow the one carve-out that is
+ # platform-neutral.
+ assert classify("pytest -x 2>&1") == "test_output"
+
+ @pytest.mark.parametrize(
+ "command",
+ [
+ "pytest | awk '{print $1}'", # awk is not a bare stdin filter
"pytest | head -50 | tail -2", # two pipes
'pytest -k "a b" | head', # quotes could break the wrap
"pytest $ARGS | head", # expansion re-evaluated inside distill
@@ -243,11 +278,85 @@ class TestSafeTails:
"pytest | head > out.txt", # redirect after the pipe
"echo hi | head", # head command still on the ignore-list
"tail -f app.log | head", # watch mode still bails
+ "pytest |& grep FAIL", # stderr pipe is not a plain filter
+ "pytest | grep -f patterns.txt", # -f reads the file, not stdin
+ "pytest | grep --file=patterns.txt",
+ "pytest | grep -if patterns.txt", # bundled short flags too
+ "pytest | grep -fpatterns.txt", # attached value too
+ "pytest | rg -f patterns.txt",
+ 'pytest -k "a; rm -rf /', # unterminated quote hides the rest
],
)
def test_unsafe_pipes_pass_through(self, command, posix_host) -> None:
assert classify(command) is None
+ @pytest.mark.parametrize(
+ "command",
+ [
+ # Producers that stream forever. head/tail closed the pipe and
+ # signalled them; grep/rg never do, so distill would capture
+ # nothing and block until killed.
+ "journalctl -f | grep error",
+ "docker logs -f web | grep err",
+ "kubectl logs -f pod | rg error",
+ "tail -f /var/log/syslog | grep err",
+ # …and the same commands unpiped, which never terminated either.
+ "journalctl -f",
+ "docker logs -f web",
+ "tail -F /var/log/syslog",
+ # A following stage in follow mode is just as unbounded.
+ "npm test | tail -F",
+ "npm test | tail --follow",
+ ],
+ )
+ def test_follow_modes_never_rewrite(self, command, posix_host) -> None:
+ assert classify(command) is None
+
+ @pytest.mark.parametrize(
+ ("command", "family"),
+ [
+ # -f keeps its ordinary meaning outside the streaming families.
+ ("make -f Makefile", "build_output"),
+ ("tail -n 100 app.log", "logs"),
+ ("cat server.log", "logs"),
+ ],
+ )
+ def test_follow_check_does_not_overreach(self, command, family, posix_host) -> None:
+ assert classify(command) == family
+
+ @pytest.mark.parametrize(
+ "command",
+ [
+ 'git commit -m "fix a|b"',
+ "git commit -m 'refactor: a && b'",
+ 'echo "a; b"',
+ ],
+ )
+ def test_quoted_operators_are_not_bailouts(self, command, posix_host) -> None:
+ """An operator inside quotes is text, so these classify normally.
+
+ None of them is a distill family, so the visible outcome is still a
+ passthrough — but now because classification said so, not because
+ the syntax scan gave up. ``analyze_pipeline`` is the assertion that
+ distinguishes the two.
+ """
+ from repowise.cli.shell_lexer import analyze_pipeline
+
+ analysis = analyze_pipeline(command)
+ assert analysis is not None
+ assert analysis.final_tool is None
+ assert classify(command) is None
+
+ def test_quoted_operator_in_a_family_command_rewrites(self, repo, posix_host) -> None:
+ """The false-bail fix is visible on a family command: a quoted ``|``
+ no longer stops ``pytest -k`` from being recognized."""
+ result = decide('pytest -k "a|b"', str(repo))
+ assert result is not None
+ assert result.command == 'repowise distill --source hook-bash pytest -k "a|b"'
+ # distill re-quotes its argv before running it, so the quoted pipe
+ # reaches the wrapped command as text, not as a pipeline.
+ assert decide('pytest -k "a or b" -m "not slow"', str(repo)) is not None
+
def test_decide_keeps_stderr_merge_unquoted(self, repo) -> None:
result = decide("pytest -x 2>&1", str(repo))
assert result is not None
@@ -261,6 +370,15 @@ class TestSafeTails:
)
assert result.permission == "allow"
+ def test_decide_quotes_grep_pipeline(self, repo, posix_host) -> None:
+ # The whole pipeline stays one token, so grep still filters distill's
+ # rendering inside distill's own shell and the omission marker it
+ # emits survives to the agent.
+ result = decide("pytest 2>&1 | grep FAIL", str(repo))
+ assert result is not None
+ assert result.command == ('repowise distill --source hook-bash "pytest 2>&1 | grep FAIL"')
+ assert "repowise expand" in result.reason
+
# ---------------------------------------------------------------------------
# decide() — repo gating + permission config
@@ -501,25 +619,19 @@ class TestNonRepoRoots:
(fake_tmp / ".repowise").mkdir(parents=True)
cwd = fake_tmp / "work" / "sub"
cwd.mkdir(parents=True)
- monkeypatch.setattr(
- rewrite_hook.tempfile, "gettempdir", lambda: str(fake_tmp)
- )
+ monkeypatch.setattr(rewrite_hook.tempfile, "gettempdir", lambda: str(fake_tmp))
# Ancestors of tmp_path on the host may legitimately match, so pin
# only the guard: the walk must never return the temp root itself.
import os
found = rewrite_hook._find_repo_root(str(cwd))
- assert found is None or os.path.realpath(found) != os.path.realpath(
- str(fake_tmp)
- )
+ assert found is None or os.path.realpath(found) != os.path.realpath(str(fake_tmp))
def test_repo_under_temp_root_still_matches(self, tmp_path, monkeypatch) -> None:
fake_tmp = tmp_path / "faketmp"
repo = fake_tmp / "checkout"
(repo / ".repowise").mkdir(parents=True)
- monkeypatch.setattr(
- rewrite_hook.tempfile, "gettempdir", lambda: str(fake_tmp)
- )
+ monkeypatch.setattr(rewrite_hook.tempfile, "gettempdir", lambda: str(fake_tmp))
import os
found = rewrite_hook._find_repo_root(str(repo))
diff --git a/tests/unit/distill/test_rewrite_perf.py b/tests/unit/distill/test_rewrite_perf.py
index b89c60a25..3cdbb8438 100644
--- a/tests/unit/distill/test_rewrite_perf.py
+++ b/tests/unit/distill/test_rewrite_perf.py
@@ -20,6 +20,8 @@ import sys
import time
from pathlib import Path
+import pytest
+
_HEAVY_PREFIXES = (
"click",
"sqlalchemy",
@@ -61,29 +63,65 @@ def _hook_invocation() -> list[str]:
return [sys.executable, "-c", "from repowise.cli.rewrite_hook import main; main()"]
-def test_p95_under_150ms(tmp_path: Path) -> None:
- (tmp_path / ".repowise").mkdir()
- payload = json.dumps(
+def _payload(command: str, cwd: Path) -> str:
+ return json.dumps(
{
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
- "tool_input": {"command": "pytest -x"},
- "cwd": str(tmp_path),
+ "tool_input": {"command": command},
+ "cwd": str(cwd),
}
)
- cmd = _hook_invocation()
- # Warmup: first run pays one-off filesystem cache costs.
- subprocess.run(cmd, input=payload, capture_output=True, text=True)
+def _p95(cmd: list[str], payload: str) -> tuple[float, list[str]]:
+ """Wall-clock p95 over 12 invocations, plus every stdout seen."""
timings: list[float] = []
+ outputs: list[str] = []
for _ in range(12):
start = time.perf_counter()
result = subprocess.run(cmd, input=payload, capture_output=True, text=True)
timings.append((time.perf_counter() - start) * 1000)
assert result.returncode == 0
- assert "repowise distill --source hook-bash pytest -x" in result.stdout
-
+ outputs.append(result.stdout)
timings.sort()
- p95 = timings[int(len(timings) * 0.95) - 1]
- assert p95 < 150, f"repowise-rewrite p95 {p95:.1f} ms >= 150 ms (all: {timings})"
+ return timings[int(len(timings) * 0.95) - 1], outputs
+
+
+#: Command shapes the hook must answer within budget. The pipeline and
+#: quoted-operator rows are the ones that exercise the shell lexer end to
+#: end: they are the shapes that used to short-circuit on a character scan
+#: and now walk every token.
+_PERF_COMMANDS = (
+ "pytest 2>&1 | grep FAIL",
+ "git log --oneline -50 | rg fix",
+ 'git commit -m "fix a|b"',
+ "npm run build --workspace packages/web -- --sourcemap --minify=false",
+)
+
+
+def test_p95_under_150ms(tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ cmd = _hook_invocation()
+
+ # Warmup: first run pays one-off filesystem cache costs.
+ subprocess.run(cmd, input=_payload("pytest -x", tmp_path), capture_output=True, text=True)
+
+ p95, outputs = _p95(cmd, _payload("pytest -x", tmp_path))
+ assert all("repowise distill --source hook-bash pytest -x" in out for out in outputs)
+ assert p95 < 150, f"repowise-rewrite p95 {p95:.1f} ms >= 150 ms"
+
+
[email protected]("command", _PERF_COMMANDS)
+def test_lexer_shapes_stay_under_budget(tmp_path: Path, command: str) -> None:
+ """No command shape may blow the budget, whatever the lexer walks.
+
+ Only the timing is asserted here; whether a given shape rewrites is the
+ decision table's business (and is platform-dependent for pipelines).
+ """
+ (tmp_path / ".repowise").mkdir()
+ cmd = _hook_invocation()
+ subprocess.run(cmd, input=_payload(command, tmp_path), capture_output=True, text=True)
+
+ p95, _ = _p95(cmd, _payload(command, tmp_path))
+ assert p95 < 150, f"{command!r} p95 {p95:.1f} ms >= 150 ms"
diff --git a/tests/unit/distill/test_shell_lexer.py b/tests/unit/distill/test_shell_lexer.py
new file mode 100644
index 000000000..15685a83b
--- /dev/null
+++ b/tests/unit/distill/test_shell_lexer.py
@@ -0,0 +1,238 @@
+"""The shared shell lexer behind the rewrite hook's bailouts.
+
+The hook fires before every agent shell command, so this module carries two
+contracts: it must describe command structure correctly (quoting, operators,
+redirects, pipeline stages) and it must stay stdlib-only. The structural
+cases live here; the import-graph guard lives in ``test_rewrite_perf``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.cli import rewrite_hook
+from repowise.cli.shell_lexer import (
+ SAFE_FINAL_TOOLS,
+ analyze_pipeline,
+ render,
+ tokenize,
+)
+
+
+def _kinds(command: str) -> list[tuple[str, str]]:
+ return [(t.kind, t.text) for t in tokenize(command)]
+
+
+class TestTokenize:
+ def test_plain_command(self) -> None:
+ assert _kinds("pytest -q") == [("arg", "pytest"), ("arg", "-q")]
+
+ def test_runs_of_whitespace_collapse(self) -> None:
+ assert render(tokenize(" pytest \t -q ")) == "pytest -q"
+
+ @pytest.mark.parametrize(
+ ("command", "last_arg"),
+ [
+ ('git commit -m "fix a|b"', '"fix a|b"'),
+ ("git commit -m 'a && b'", "'a && b'"),
+ ('pytest -k "a b"', '"a b"'),
+ ],
+ )
+ def test_operators_inside_quotes_stay_in_the_argument(self, command, last_arg) -> None:
+ tokens = tokenize(command)
+ assert all(t.kind == "arg" for t in tokens)
+ assert tokens[-1].text == last_arg
+
+ def test_escaped_quote_does_not_end_the_run(self) -> None:
+ assert _kinds(r'echo "a\"b"') == [("arg", "echo"), ("arg", r'"a\"b"')]
+
+ @pytest.mark.parametrize("command", ['echo "a | b', "echo 'a ; b", 'pytest -k "a; rm -rf /'])
+ def test_unterminated_quote_is_an_operator(self, command) -> None:
+ """Everything after an unterminated quote is unparseable.
+
+ Consuming it into one argument would let a real ``;`` or ``|`` hide
+ there, so the quote itself becomes an operator and callers bail.
+ """
+ assert any(t.kind == "op" for t in tokenize(command))
+ assert analyze_pipeline(command) is None
+
+ @pytest.mark.parametrize(
+ ("command", "operator"),
+ [
+ ("a && b", "&&"),
+ ("a || b", "||"),
+ ("a ; b", ";"),
+ ("a &", "&"),
+ ("echo `date`", "`"),
+ ("cat $(cfg)", "$("),
+ ("pytest -x\ngit status", "\n"),
+ ("pytest -x\r\ngit status", "\n"),
+ ("pytest \\\n -x", "\\\n"), # line continuation is still multi-line
+ ],
+ )
+ def test_operators_are_their_own_tokens(self, command, operator) -> None:
+ assert any(t.kind == "op" and t.text == operator for t in tokenize(command))
+
+ def test_crlf_is_one_operator(self) -> None:
+ assert [t.text for t in tokenize("a\r\nb") if t.kind == "op"] == ["\n"]
+
+ def test_pipe_kinds(self) -> None:
+ assert [t.text for t in tokenize("a | b") if t.kind == "pipe"] == ["|"]
+ assert [t.text for t in tokenize("a |& b") if t.kind == "pipe"] == ["|&"]
+
+
+class TestRedirects:
+ """A leading fd digit belongs to the redirect, not to the command.
+
+ Without this, ``cargo test 2>&1`` re-renders as ``cargo test 2 >&1`` —
+ a different command that fails when it runs.
+ """
+
+ @pytest.mark.parametrize(
+ ("command", "redirect"),
+ [
+ ("cargo test 2>&1", "2>&1"),
+ ("pytest > out.txt", ">"),
+ ("pytest >> out.txt", ">>"),
+ ("pytest < input.txt", "<"),
+ ("make 2>/dev/null", "2>"),
+ ],
+ )
+ def test_fd_digit_binds_to_the_redirect(self, command, redirect) -> None:
+ redirects = [t.text for t in tokenize(command) if t.kind == "redirect"]
+ assert redirects == [redirect]
+
+ @pytest.mark.parametrize(
+ "command",
+ [
+ "cargo test 2>&1",
+ "pytest -q > out.txt",
+ "cargo test 2>&1 | grep fail",
+ "pytest --maxfail 2 2>&1",
+ ],
+ )
+ def test_render_round_trips_when_spacing_is_already_canonical(self, command) -> None:
+ assert render(tokenize(command)) == command
+
+ @pytest.mark.parametrize(
+ ("command", "rendered"),
+ [
+ ("make 2>/dev/null", "make 2> /dev/null"),
+ ("pytest>out", "pytest > out"),
+ ("pytest -q", "pytest -q"),
+ ],
+ )
+ def test_render_normalizes_spacing_without_changing_meaning(self, command, rendered) -> None:
+ """render() is not a byte round-trip, and does not claim to be."""
+ assert render(tokenize(command)) == rendered
+
+ def test_background_operator_is_not_swallowed_by_a_redirect(self) -> None:
+ # `2>&1&` must be a redirect plus the background operator, not one
+ # redirect token that happens to end in `&`.
+ tokens = tokenize("cargo test 2>&1&")
+ assert [(t.kind, t.text) for t in tokens[-2:]] == [("redirect", "2>&1"), ("op", "&")]
+ assert analyze_pipeline("cargo test 2>&1&") is None
+
+ def test_analysis_reports_redirects(self) -> None:
+ analysis = analyze_pipeline("cargo test 2>&1 | grep fail")
+ assert analysis is not None
+ assert analysis.producer == "cargo test 2>&1"
+ assert analysis.final_tool == "grep"
+ assert analysis.redirects == ("2>&1",)
+
+
+class TestAnalyzePipeline:
+ @pytest.mark.parametrize(
+ ("command", "producer", "tool"),
+ [
+ ("pytest -q", "pytest -q", None),
+ ('git commit -m "fix a|b"', 'git commit -m "fix a|b"', None),
+ ("pytest | tail -20", "pytest", "tail"),
+ ("rg TODO | head -5", "rg TODO", "head"),
+ ("cargo test | grep -i fail", "cargo test", "grep"),
+ ("npm test | egrep -c error", "npm test", "egrep"),
+ ("npm test | fgrep warning", "npm test", "fgrep"),
+ ("git log --oneline | rg fix", "git log --oneline", "rg"),
+ ("pytest | /usr/bin/grep FAIL", "pytest", "grep"),
+ # -F means "fixed strings" to grep, so it must NOT be read as the
+ # follow flag it is for tail. The check is tool-aware.
+ ("pytest | grep -F FAIL", "pytest", "grep"),
+ ],
+ )
+ def test_recognized_shapes(self, command, producer, tool) -> None:
+ analysis = analyze_pipeline(command)
+ assert analysis is not None
+ assert (analysis.producer, analysis.final_tool) == (producer, tool)
+
+ @pytest.mark.parametrize(
+ "command",
+ [
+ "ls && rm -rf x",
+ "ls || true",
+ "git status; ls",
+ "pytest -x &",
+ "cat $(cfg)",
+ "echo `date`",
+ "pytest -x\ngit status",
+ "a | b | c", # 3+ stages
+ "make 2>&1 |& grep err", # stderr pipe
+ "npm test | grep -f patterns.txt", # -f reads a config file
+ "npm test | grep --file=patterns.txt",
+ "npm test | grep -if patterns.txt",
+ "npm test | grep -fpatterns.txt", # attached value
+ "npm test | tail -F", # follow never closes the pipe
+ "npm test | tail --follow",
+ "npm test | head -f",
+ "pytest | awk '{print $1}'", # not a bare stdin filter
+ "pytest | xargs rm",
+ "pytest |", # nothing after the pipe
+ "| head", # nothing before it
+ "",
+ ],
+ )
+ def test_bailouts(self, command) -> None:
+ assert analyze_pipeline(command) is None
+
+ def test_safe_final_tools_are_stdin_filters(self) -> None:
+ assert sorted(SAFE_FINAL_TOOLS) == ["egrep", "fgrep", "grep", "head", "rg", "tail"]
+
+
+class TestPowerShellEdgeCases:
+ """PowerShell shapes the hook used to reject via an ad-hoc character
+ scan now reject structurally, for the reason named in each case."""
+
+ @pytest.mark.parametrize(
+ "command",
+ [
+ "git status; git log --oneline -5", # statement separator
+ "git log --oneline `\n -20", # backtick continuation
+ "git diff $(git merge-base main HEAD)", # subexpression
+ '& "C:\\Program Files\\Git\\bin\\git.exe" status', # call operator
+ "$env:FOO='1'; pytest -x", # assignment then separator
+ "Get-ChildItem | Select-Object -First 5", # object pipeline
+ ],
+ )
+ def test_still_bail(self, command) -> None:
+ assert analyze_pipeline(command) is None
+ assert rewrite_hook.classify(command) is None
+
+
+class TestSharedWithTheHook:
+ """One implementation, not a mirrored copy.
+
+ ``_normalize`` is duplicated in the hook on purpose (importing core's
+ router would pull the heavy stack); the lexer needs no such copy because
+ it is already stdlib-only, so the hook must use this very object.
+ """
+
+ def test_hook_uses_this_module(self) -> None:
+ assert rewrite_hook.analyze_pipeline is analyze_pipeline
+
+ def test_module_has_no_repowise_dependencies(self) -> None:
+ import inspect
+
+ from repowise.cli import shell_lexer
+
+ source = inspect.getsource(shell_lexer)
+ assert "import repowise" not in source
+ assert "from repowise" not in source