Answer stability round 2: keep the line break that ends a heredoc, read a run of separators as one, check every untagged compose image, and reject a non-object tool input
This commit is contained in:
+1
-1
@@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from rule_hook import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] else sys.stdin.read()))
|
||||
sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] or sys.stdin.isatty() else sys.stdin.read()))
|
||||
|
||||
+19
-11
@@ -14,14 +14,18 @@ subagent. The rules:
|
||||
`container:`, names a full patch version, a date stamp or a digest
|
||||
no-ai-attribution no Claude or Anthropic co-author or generated-with line, in a file written or
|
||||
in a git, gh or tea command
|
||||
todo-rank-check a commit that stages todo.md, or commits with -a while todo.md has changes,
|
||||
needs rank_todo.py --check to pass on it
|
||||
todo-rank-check a git commit while todo.md has changes, staged or not, needs
|
||||
rank_todo.py --check to pass on it
|
||||
|
||||
The file rules see what an Edit, MultiEdit or Write call writes, not a file a Bash command writes.
|
||||
|
||||
A call overrides a rule with `# rule-override <rule>: <reason>`: anywhere in a Bash command, such as
|
||||
a trailing comment; in a file, as a comment line in the text the edit writes. Each override that
|
||||
let a call through is appended to rule-overrides.tsv in the checkout's git directory: UTC time,
|
||||
branch, rule, reason, and the file written or the command's first line. `rule-hook overrides`
|
||||
prints the lines for the current branch.
|
||||
a trailing comment; in a file, as a comment line in the text the edit writes, or in Markdown as
|
||||
`<!-- rule-override <rule>: <reason> -->`. Each override that let a call through is appended to
|
||||
rule-overrides.tsv in the checkout's git directory: UTC time, branch, rule, reason, and the file
|
||||
written or the command's first line. `rule-hook overrides` prints the lines for the current branch.
|
||||
|
||||
Run with no arguments in a terminal, it prints this help.
|
||||
|
||||
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call; 0 otherwise.
|
||||
Exit 1, a non-blocking error to Claude Code, on input it cannot read.
|
||||
@@ -42,7 +46,7 @@ LOG = "rule-overrides.tsv"
|
||||
|
||||
|
||||
def main(argv: list[str], stdin: str) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
if argv in (["-h"], ["--help"]) or not argv and not stdin:
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if argv == ["overrides"]:
|
||||
@@ -53,6 +57,8 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
try:
|
||||
call = json.loads(stdin)
|
||||
tool, given, cwd = call["tool_name"], call["tool_input"], call["cwd"]
|
||||
if not isinstance(given, dict):
|
||||
raise TypeError("tool_input is no object")
|
||||
except (json.JSONDecodeError, KeyError, TypeError) as failure:
|
||||
print(f"rule-hook cannot read the hook input: {failure}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -69,6 +75,8 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
if not blocking:
|
||||
return 0
|
||||
where = "the command" if tool == "Bash" else "the text you write, as a comment line"
|
||||
if "rule-override" in text and not granted:
|
||||
print("The rule-override in this call names no rule below, or gives no reason.", file=sys.stderr)
|
||||
for rule in sorted({breach.rule for breach in blocking}):
|
||||
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
|
||||
print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `# rule-override {rule}: <reason>` to {where}; larv-review's judge rules on the reason.", file=sys.stderr)
|
||||
@@ -79,7 +87,7 @@ def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str
|
||||
"""The text that may carry an override, the directory whose checkout logs it, and the call's breaches."""
|
||||
if tool == "Bash":
|
||||
command = str(given.get("command") or "")
|
||||
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory, commit.all)]
|
||||
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory)]
|
||||
return command, cwd, command_breaches(command, cwd) + todo
|
||||
path = str(given.get("file_path") or "")
|
||||
if tool not in ("Edit", "MultiEdit", "Write") or not path:
|
||||
@@ -97,12 +105,12 @@ def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str
|
||||
return added, os.path.dirname(path), file_breaches(path, before, added, after)
|
||||
|
||||
|
||||
def todo_breaches(directory: str, staged_all: bool) -> list[Breach]:
|
||||
def todo_breaches(directory: str) -> list[Breach]:
|
||||
top = git(directory, "rev-parse", "--show-toplevel")
|
||||
if not top or not (pathlib.Path(top) / "todo.md").is_file():
|
||||
return []
|
||||
changed = git(top, "diff", "--cached", "--name-only", "--", "todo.md") or (staged_all and git(top, "diff", "--name-only", "--", "todo.md"))
|
||||
if not changed:
|
||||
# Any change, staged or not: the hook runs before a `git add` earlier in the same command.
|
||||
if not git(top, "status", "--porcelain", "--", "todo.md"):
|
||||
return []
|
||||
return [Breach("todo-rank-check", line) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")]
|
||||
|
||||
|
||||
+14
-19
@@ -8,11 +8,11 @@ RULES = {
|
||||
"action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never a commit SHA or a branch; SHA-pin only in a pipeline that tests our own specific builds",
|
||||
"commit-one-line": "a commit message is one line, prefixed with the ticket ID when the work has one",
|
||||
"ignorefile-sorted": "each block of an ignore file is sorted, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
|
||||
"image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs",
|
||||
"image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs. An image that publishes no three-part tag, such as postgres:16.4, takes an override",
|
||||
"no-ai-attribution": "no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
|
||||
"todo-rank-check": "a committed todo.md passes ~/.claude/bin/rank_todo.py --check",
|
||||
}
|
||||
OVERRIDE = re.compile(r"#\s*rule-override ([a-z-]+):[ \t]*(\S[^\n]*)")
|
||||
OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*)")
|
||||
# [-] keeps this file from matching itself.
|
||||
ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE)
|
||||
SEMVER = re.compile(r"v?\d+(?:\.\d+){0,2}")
|
||||
@@ -21,11 +21,10 @@ PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?|.*\d{8}.*")
|
||||
FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
|
||||
COPIED = re.compile(r"^[ \t]*COPY[ \t].*?--from=(\S+)", re.IGNORECASE | re.MULTILINE)
|
||||
IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"'#{]+)", re.MULTILINE)
|
||||
BUILD = re.compile(r"^[ \t]*build:", re.MULTILINE)
|
||||
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)(\w+)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
|
||||
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
|
||||
USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE)
|
||||
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
|
||||
SEPARATORS = {"\n", "&&", "||", ";", "|", "&", "(", ")", ";;", "|&"}
|
||||
SEPARATING = set("\n();&|")
|
||||
# git's global options that take a value as the next word.
|
||||
GIT_VALUED = {"-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
|
||||
|
||||
@@ -38,20 +37,20 @@ class Breach:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Commit:
|
||||
"""A `git commit` in a command: the directory it runs in, its messages and whether it stages tracked changes."""
|
||||
"""A `git commit` in a command: the directory it runs in, and its messages."""
|
||||
directory: str
|
||||
messages: list[str]
|
||||
from_file: bool
|
||||
all: bool
|
||||
|
||||
|
||||
def overrides(text: str) -> dict[str, str]:
|
||||
return {rule: reason.strip() for rule, reason in OVERRIDE.findall(text) if rule in RULES}
|
||||
given = {rule: reason.strip().removesuffix("-->").strip() for rule, reason in OVERRIDE.findall(text)}
|
||||
return {rule: reason for rule, reason in given.items() if rule in RULES and reason}
|
||||
|
||||
|
||||
def segments(command: str) -> list[list[str]] | None:
|
||||
"""The command's simple commands as words, each heredoc's body cut to a line break, or None when it does not parse."""
|
||||
lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0] + "\n", command), posix=True, punctuation_chars="();<>|&\n")
|
||||
lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n")
|
||||
lexer.whitespace = " \t\r"
|
||||
lexer.whitespace_split = True
|
||||
# shlex also ends a word at a # inside it, as in fix#2, which bash does not; after lexing, a quoted # cannot be told apart.
|
||||
@@ -61,7 +60,8 @@ def segments(command: str) -> list[list[str]] | None:
|
||||
return None
|
||||
split: list[list[str]] = [[]]
|
||||
for word in words:
|
||||
if word in SEPARATORS:
|
||||
# Unquoted, a run such as "&&\n" lexes as one word.
|
||||
if set(word) <= SEPARATING:
|
||||
split.append([])
|
||||
else:
|
||||
split[-1].append(word)
|
||||
@@ -91,7 +91,7 @@ def git_commit(args: list[str], directory: str) -> Commit | None:
|
||||
if args[at:at + 1] != ["commit"]:
|
||||
return None
|
||||
messages: list[str] = []
|
||||
from_file = staged_all = False
|
||||
from_file = False
|
||||
rest = args[at + 1:]
|
||||
at = 0
|
||||
while at < len(rest):
|
||||
@@ -107,8 +107,6 @@ def git_commit(args: list[str], directory: str) -> Commit | None:
|
||||
messages.append(word.removeprefix("--message="))
|
||||
elif word.startswith("--file="):
|
||||
from_file = True
|
||||
elif word == "--all":
|
||||
staged_all = True
|
||||
elif word.startswith("-") and not word.startswith("--"):
|
||||
# A cluster such as -am: a valued flag takes the rest of the word, or else the next word.
|
||||
for place, flag in enumerate(word[1:], 1):
|
||||
@@ -120,9 +118,8 @@ def git_commit(args: list[str], directory: str) -> Commit | None:
|
||||
messages += [value] if flag == "m" else []
|
||||
from_file = from_file or flag == "F"
|
||||
break
|
||||
staged_all = staged_all or flag == "a"
|
||||
at += 1
|
||||
return Commit(directory, messages, from_file, staged_all)
|
||||
return Commit(directory, messages, from_file)
|
||||
|
||||
|
||||
def command_breaches(command: str, cwd: str) -> list[Breach]:
|
||||
@@ -151,14 +148,12 @@ def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach
|
||||
breaches += [Breach("image-pin", f"{path}: {image}") for image in images if image.lower() not in stages | {"scratch"} and not image.isdigit() and not pinned(image)]
|
||||
workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml")
|
||||
if "compose" in name and name.endswith((".yml", ".yaml")) or workflow:
|
||||
# A compose service that builds names its own image with image:, untagged.
|
||||
built = "compose" in name and BUILD.search(after) is not None
|
||||
breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image) and not (built and ":" not in image)]
|
||||
breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image)]
|
||||
if workflow:
|
||||
breaches += [Breach("action-pin", f"{path}: uses: {action}") for action in USES.findall(added) if not tagged(action)]
|
||||
if name.startswith(".") and name.endswith("ignore"):
|
||||
already = [block for block in blocks(before) if block != sorted(block)]
|
||||
breaches += [Breach("ignorefile-sorted", f"{path}: {block[0]!r} through {block[-1]!r} are out of order") for block in blocks(after) if block != sorted(block) and block not in already]
|
||||
breaches += [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} in code-point order, as LC_ALL=C sort does: {', '.join(sorted(block))}") for block in blocks(after) if block != sorted(block) and block not in already]
|
||||
return breaches
|
||||
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ def git(cwd: str, *args: str) -> str:
|
||||
|
||||
class Commits(unittest.TestCase):
|
||||
def test_cd_and_dash_capital_c_move_the_commit(self):
|
||||
self.assertEqual(commits("cd a && git -C b commit -am 'x'", "/r"), [Commit("/r/a/b", ["x"], False, True)])
|
||||
self.assertEqual(commits("cd a && git -C b commit -am 'x'", "/r"), [Commit("/r/a/b", ["x"], False)])
|
||||
|
||||
def test_each_message_spelling_is_read(self):
|
||||
self.assertEqual(commits("git commit --message=a -m b=c --message c -mz", "/r")[0].messages, ["a", "b=c", "c", "z"])
|
||||
@@ -41,8 +41,15 @@ class Commits(unittest.TestCase):
|
||||
def test_other_git_commands_are_no_commit(self):
|
||||
self.assertEqual(commits("git log --grep commit; echo git commit", "/r"), [])
|
||||
|
||||
def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self):
|
||||
self.assertEqual(len(commits("cat <<EOF > notes\nhello\nEOF\ngit commit -m a", "/r")), 1)
|
||||
self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1)
|
||||
|
||||
def test_an_arithmetic_shift_is_no_heredoc(self):
|
||||
self.assertEqual(len(commits("echo $((1<<2))\ngit commit -m a\n2", "/r")), 1)
|
||||
|
||||
def test_a_line_break_separates_commands(self):
|
||||
self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False, False)])
|
||||
self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False)])
|
||||
|
||||
|
||||
class CommandBreaches(unittest.TestCase):
|
||||
@@ -78,10 +85,8 @@ class FileBreaches(unittest.TestCase):
|
||||
added = " container: node:24\n image: mysql:8.4\n - image: 'mysql:8.4.7'\n - uses: actions/checkout@v4\n - uses: a/b@0123456789abcdef0123456789abcdef01234567\n - uses: ./local\n"
|
||||
self.assertEqual(rules(file_breaches("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"])
|
||||
|
||||
def test_a_compose_file_checks_its_images_but_not_the_one_it_builds(self):
|
||||
def test_a_compose_file_checks_its_images(self):
|
||||
self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"])
|
||||
after = " app:\n build: .\n image: myapp\n"
|
||||
self.assertEqual(file_breaches("docker-compose.yml", "", after, after), [])
|
||||
|
||||
def test_other_yaml_is_not_checked(self):
|
||||
added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n"
|
||||
@@ -103,6 +108,9 @@ class Overrides(unittest.TestCase):
|
||||
def test_a_marker_names_a_known_rule_and_a_reason(self):
|
||||
self.assertEqual(overrides("x # rule-override image-pin: vendor ships floating tags only\n# rule-override nope: x\n# rule-override action-pin:"), {"image-pin": "vendor ships floating tags only"})
|
||||
|
||||
def test_markdown_takes_an_html_comment(self):
|
||||
self.assertEqual(overrides("<!-- rule-override no-ai-attribution: quotes the banned line -->"), {"no-ai-attribution": "quotes the banned line"})
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -128,23 +136,29 @@ class Hook(unittest.TestCase):
|
||||
call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"}
|
||||
self.assertEqual(hook(call, self.repo).returncode, 2)
|
||||
|
||||
def test_a_commit_staging_an_unranked_todo_is_blocked(self):
|
||||
def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
|
||||
pathlib.Path(self.repo, "docs").mkdir()
|
||||
for name, text in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
|
||||
pathlib.Path(self.repo, name).write_text(text)
|
||||
git(self.repo, "add", "README.md")
|
||||
call = {"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}
|
||||
self.assertEqual(hook(call, self.repo).returncode, 0)
|
||||
self.assertEqual(hook({**call, "tool_input": {"command": "git commit -am x"}}, self.repo).returncode, 0, "-a stages tracked files only")
|
||||
git(self.repo, "add", "todo.md")
|
||||
git(self.repo, "add", "README.md", "docs", "todo.md")
|
||||
git(self.repo, "commit", "-qm", "x", "--no-verify")
|
||||
call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"}
|
||||
self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged")
|
||||
pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n")
|
||||
ran = hook(call, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("todo.md: not ranked", ran.stderr)
|
||||
|
||||
def test_a_malformed_override_is_named(self):
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m a -m b # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo)
|
||||
self.assertIn("names no rule below, or gives no reason", ran.stderr)
|
||||
|
||||
def test_a_missing_field_breaks_nothing(self):
|
||||
for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}]:
|
||||
for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": "Write" if "content" in given else "Bash"}, self.repo).returncode, 0)
|
||||
tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit"
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0)
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": None, "tool_name": "Bash"}, self.repo).returncode, 1)
|
||||
|
||||
def test_unreadable_input_does_not_block(self):
|
||||
ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True)
|
||||
|
||||
Reference in New Issue
Block a user