159 lines
6.4 KiB
Python
159 lines
6.4 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 `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 is sorted; a blank line or comment ends a block
|
|
image-pin a Dockerfile FROM or YAML `image:` names a full patch version 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
|
|
|
|
A call overrides a rule with `# rule-override <rule>: <reason>`: in a Bash command, 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. `rule-hook overrides` prints the lines for the current branch.
|
|
|
|
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 failure import Failure
|
|
import rank_todo
|
|
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, overrides, RULES
|
|
from utc_stamp import utc
|
|
|
|
LOG = "rule-overrides.tsv"
|
|
|
|
|
|
def main(argv: list[str], stdin: str) -> int:
|
|
if argv in (["-h"], ["--help"]):
|
|
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"]
|
|
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
|
|
granted = overrides(text)
|
|
for breach in breaches:
|
|
if breach.rule in granted:
|
|
log_override(directory, breach.rule, granted[breach.rule])
|
|
blocking = [breach for breach in breaches if breach.rule not in granted]
|
|
if not blocking:
|
|
return 0
|
|
where = "the command, as a trailing comment" if tool == "Bash" else "the text you write, as a comment line"
|
|
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 = given.get("command", "")
|
|
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory, commit.all)]
|
|
return command, cwd, command_breaches(command, cwd) + todo
|
|
path = given.get("file_path", "")
|
|
if tool not in ("Edit", "MultiEdit", "Write") or not path:
|
|
return None
|
|
before = read(path)
|
|
edits = [given] if tool == "Edit" else given.get("edits", [])
|
|
if tool == "Write":
|
|
added = after = given.get("content", "")
|
|
else:
|
|
after = before
|
|
for edit in edits:
|
|
old, new = edit.get("old_string", ""), edit.get("new_string", "")
|
|
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
|
|
added = "\n".join(edit.get("new_string", "") for edit in edits)
|
|
return added, os.path.dirname(path), file_breaches(path, before, added, after)
|
|
|
|
|
|
def todo_breaches(directory: str, staged_all: bool) -> 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:
|
|
return []
|
|
todo = pathlib.Path(top) / "todo.md"
|
|
texts = rank_todo.read_all(todo)
|
|
if isinstance(texts, Failure):
|
|
return [Breach("todo-rank-check", texts.reason)]
|
|
ranked = rank_todo.rank(*texts)
|
|
if isinstance(ranked, Failure):
|
|
return [Breach("todo-rank-check", ranked.reason)]
|
|
if ranked.text != texts[0]:
|
|
return [Breach("todo-rank-check", f"{todo} is not ranked")]
|
|
return [Breach("todo-rank-check", line) for line in ranked.under_bar]
|
|
|
|
|
|
def log_override(directory: str, rule: str, reason: 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())]) + "\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 ""
|