Read the script
#!/usr/bin/env python3
"""
pipe_guard_hook.py — PreToolUse hook: stop a test run whose exit status would lie.
The claim-check Stop hook (tool/both mode) already refuses to CREDIT a run like
`pytest -q | tail -3`: without `pipefail`, the shell reports tail's exit status, so a
failing suite looks green. But that refusal arrives at turn end, after the agent has read
the wrong status and moved on. This hook catches the same line BEFORE it runs, says why,
and gives the fix, so the agent reruns it in a form the harness records honestly.
It denies a Bash command when an allowlisted verification command (the same list as
claim-check: pytest, npm test, cargo test, ... or CLAIM_CHECK_VERIFY_COMMANDS) is
- piped into anything (`|` or `|&`) with no `set -o pipefail` earlier in the command, or
- followed by `||`, directly or later in the same `&&`/`||` chain (`pytest || true`,
`pytest && echo ok || true`). The line's status is then the handler's, not the test's.
Everything else is allowed, including `set -o pipefail; pytest | tail -3`, a bare run,
`pytest > out.txt`, `pytest; echo $?` and `pytest --help | head`. Commands it cannot
tokenize are allowed: the Stop hook still withholds credit from them.
What it does NOT see (it allows these): a verification inside `bash -c "..."`, `$(...)`,
a script, a Makefile target or an alias; a group piped as a whole (`{ pytest; } | tail`,
`(pytest) | tail`); a `set -o pipefail` that runs in a subshell or may be skipped
(`(set -o pipefail); ...`, `false && set -o pipefail; ...`); a wrapper option it does not
know that takes a value (`uv run --some-new-flag X pytest`). Heredoc bodies are skipped as
data, including an unquoted one whose `$(...)` the shell would run. A deny costs one rerun.
Config:
ANDON_PIPE_GUARD=on enable (default: off). `1`, `true` and `yes` also enable it,
in any case; any other value, or none, leaves it off.
CLAIM_CHECK_VERIFY_COMMANDS="pytest,make test" overrides the command list
Input: the PreToolUse JSON on stdin. Output: a deny decision on stdout, or nothing.
Never fails closed: any error allows the call.
"""
from __future__ import annotations
import json
import os
import re
import shlex
import sys
from pathlib import Path
_HERE = Path(__file__).resolve().parent
_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
_OPS = ("<<<", "<<-", "||", "|&", "&&", ";;", ">>", ">&", "&>", "<<", ">|", "<&",
"|", "&", ";", "\n", "(", ")", "<", ">")
_LIST_OPS = ("||", "&&", ";;", "&", ";", "\n")
_PIPE_OPS = ("|", "|&")
_GROUPING = ("(", ")")
_KEYWORDS = frozenset(("if", "then", "elif", "else", "while", "until", "do", "!", "{", "}",
"fi", "done"))
# Wrappers that run a later word as the command, with the options that take a separate
# value (`timeout -s TERM 300 pytest`, `env -u PYTHONPATH pytest`). The command is the
# first word after the wrapper's options (and env's VAR=value, timeout's duration).
_WRAP_VALUE_OPTS = {
"env": {"-u", "--unset", "-C", "--chdir", "-S", "--split-string"},
"time": set(), "nohup": set(), "command": set(),
"nice": {"-n", "--adjustment"},
"exec": {"-a"},
"timeout": {"-s", "--signal", "-k", "--kill-after"},
"gtimeout": {"-s", "--signal", "-k", "--kill-after"},
"stdbuf": {"-i", "-o", "-e", "--input", "--output", "--error"},
"caffeinate": {"-t", "-w"},
}
_WRAP_RUN = frozenset(("uv", "poetry", "pipenv", "hatch", "pdm", "rye")) # `X run ...`
_RUN_VALUE_OPTS = frozenset((
"--with", "--with-editable", "--with-requirements", "--python", "-p", "--project",
"--directory", "--extra", "--group", "--only-group", "--package", "--env-file",
"--index", "--default-index", "--index-url", "-i", "--extra-index-url", "-C", "-P",
"-w", "-e", "--env"))
_INFO_ARGS = frozenset(("--help", "-h", "--version", "-V")) # prints, runs no tests
_PLAIN_WORD = re.compile(r"[A-Za-z0-9_@%+=:,./~-]+")
def _tokens(s):
"""Split a command line into [("w", word) | ("op", op)], the way bash reads it for
this purpose: quotes make one word (so a quoted `|` is not a pipe), a `#` at the start
of a word comments to end of line (the newline stays), backslash-newline joins lines,
and a heredoc body (`<<EOF` ... `EOF`) is skipped: it is data, not commands.
Raises ValueError on an unclosed quote."""
out, cur, have, i, n = [], [], False, 0, len(s)
want_delim, heredocs = None, [] # (delimiter, strip leading tabs) for each pending body
def flush():
nonlocal cur, have, want_delim
if have:
out.append(("w", "".join(cur)))
if want_delim is not None:
heredocs.append(("".join(cur), want_delim))
want_delim = None
cur, have = [], False
while i < n:
c = s[i]
if c == "\\":
if s[i + 1:i + 2] == "\n":
i += 2 # line continuation
continue
cur.append(s[i + 1:i + 2])
have, i = True, i + 2
elif c in " \t\r":
flush()
i += 1
elif c == "#" and not have:
j = s.find("\n", i)
i = n if j < 0 else j
elif c == "'":
j = s.find("'", i + 1)
if j < 0:
raise ValueError("unclosed '")
cur.append(s[i + 1:j])
have, i = True, j + 1
elif c == '"':
j, buf = i + 1, []
while j < n and s[j] != '"':
if s[j] == "\\" and j + 1 < n:
j += 1
buf.append(s[j])
j += 1
if j >= n:
raise ValueError('unclosed "')
cur.append("".join(buf))
have, i = True, j + 1
elif c in "|&;<>()\n":
flush()
op = next(o for o in _OPS if s.startswith(o, i))
if not (op == "\n" and out and out[-1][0] == "op"
and out[-1][1] in ("|", "|&", "&&", "||")):
out.appen