161 lines
6.8 KiB
Python
161 lines
6.8 KiB
Python
"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule.
|
|
|
|
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
|
rule-hook overrides (prints this branch's overrides)
|
|
|
|
settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
|
|
subagent. The rules:
|
|
|
|
action-pin a workflow's or action.yml's `uses:` names a semver tag, such as @v3 or @v3.1.2
|
|
commit-one-line git commit takes its message as one -m with no newline
|
|
ignorefile-sorted each block of a .*ignore file that an edit leaves unsorted is sorted; a blank
|
|
line or comment ends a block
|
|
image-pin a Dockerfile FROM or COPY --from, or a compose or workflow `image:` or
|
|
`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 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, 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.
|
|
"""
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import typing
|
|
|
|
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, overrides, RULES
|
|
import rank_todo
|
|
from utc_stamp import utc
|
|
|
|
LOG = "rule-overrides.tsv"
|
|
|
|
|
|
def main(argv: list[str], stdin: str) -> int:
|
|
if argv in (["-h"], ["--help"]) or not argv and not stdin:
|
|
print(__doc__.strip())
|
|
return 0
|
|
if argv == ["overrides"]:
|
|
return print_overrides(os.getcwd())
|
|
if argv:
|
|
print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr)
|
|
return 1
|
|
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
|
|
checked = checked_call(tool, given, cwd)
|
|
if checked is None:
|
|
return 0
|
|
text, directory, breaches = checked
|
|
what = text.split("\n", 1)[0] if tool == "Bash" else str(given.get("file_path"))
|
|
granted = overrides(text)
|
|
for breach in breaches:
|
|
if breach.rule in granted:
|
|
log_override(directory, breach.rule, granted[breach.rule], what)
|
|
blocking = [breach for breach in breaches if breach.rule not in granted]
|
|
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)
|
|
return 2
|
|
|
|
|
|
def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str, str, list[Breach]] | None:
|
|
"""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)]
|
|
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:
|
|
return None
|
|
before = read(path)
|
|
edits = [given] if tool == "Edit" else [edit for edit in given.get("edits") or [] if isinstance(edit, dict)]
|
|
if tool == "Write":
|
|
added = after = str(given.get("content") or "")
|
|
else:
|
|
after = before
|
|
for edit in edits:
|
|
old, new = str(edit.get("old_string") or ""), str(edit.get("new_string") or "")
|
|
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
|
|
added = "\n".join(str(edit.get("new_string") or "") for edit in edits)
|
|
return added, os.path.dirname(path), file_breaches(path, before, added, after)
|
|
|
|
|
|
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 []
|
|
# 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")]
|
|
|
|
|
|
def log_override(directory: str, rule: str, reason: str, what: str) -> None:
|
|
common = git(existing(directory), "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
if not common:
|
|
return
|
|
branch = git(existing(directory), "branch", "--show-current") or "HEAD"
|
|
with open(pathlib.Path(common) / LOG, "a", encoding="utf-8") as log:
|
|
log.write("\t".join([utc(time.time()), branch, rule, " ".join(reason.split()), " ".join(what.split())]) + "\n")
|
|
|
|
|
|
def print_overrides(directory: str) -> int:
|
|
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
branch = git(directory, "branch", "--show-current")
|
|
if not common or not branch:
|
|
print("rule-hook overrides runs on a branch of a git checkout", file=sys.stderr)
|
|
return 1
|
|
log = pathlib.Path(common) / LOG
|
|
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
|
|
for line in lines:
|
|
if line.split("\t")[1:2] == [branch]:
|
|
print(line)
|
|
return 0
|
|
|
|
|
|
def git(directory: str, *args: str) -> str:
|
|
try:
|
|
ran = subprocess.run(["git", "-C", directory, *args], capture_output=True, text=True)
|
|
except OSError:
|
|
return ""
|
|
return ran.stdout.strip() if ran.returncode == 0 else ""
|
|
|
|
|
|
def existing(directory: str) -> str:
|
|
path = pathlib.Path(directory or ".").absolute()
|
|
while not path.is_dir():
|
|
path = path.parent
|
|
return str(path)
|
|
|
|
|
|
def read(path: str) -> str:
|
|
try:
|
|
return pathlib.Path(path).read_text(encoding="utf-8")
|
|
except (OSError, UnicodeDecodeError):
|
|
return ""
|