Answer architecture round 2: list an override by its branch or by a commit the default branch lacks, so an amend or a rebase hides none, split main into reading, judging and answering, move the hook input into call.py, strip comments with one pattern, and log overrides only once each can be
This commit is contained in:
+79
-45
@@ -19,8 +19,8 @@ A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
|
||||
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
|
||||
written or the command's first line. An override outside any git checkout is not logged.
|
||||
`rule-hook overrides` prints the lines whose commit the current branch holds, from where it left
|
||||
the default branch on.
|
||||
`rule-hook overrides` prints the lines logged on the current branch, and those whose commit the
|
||||
default branch does not hold.
|
||||
|
||||
Run with no arguments in a terminal, it prints this help.
|
||||
|
||||
@@ -28,14 +28,18 @@ Exit 2 with the rule, why it holds and how to override it, when a rule blocks th
|
||||
override cannot be logged; 0 otherwise. Exit 1, a non-blocking error to Claude Code, on input it
|
||||
cannot read.
|
||||
"""
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from rule_hook.rules import applied, Breach, command_breaches, commits, file_breaches, FILE_TOOLS, parsed_call, rules_help, text, verdict
|
||||
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, rules_help, verdict, Verdict
|
||||
from failure import Failure
|
||||
import rank_todo
|
||||
from shell_command import simple_commands
|
||||
@@ -60,31 +64,37 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
if isinstance(call, Failure):
|
||||
print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
|
||||
return 1
|
||||
home = os.path.expanduser("~")
|
||||
bash = call.tool == "Bash"
|
||||
found = breaches_of(call, os.path.expanduser("~"))
|
||||
return answer(verdict(found[2], found[0], text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), found[1], time.time()) if found else 0
|
||||
|
||||
|
||||
def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None:
|
||||
"""The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks."""
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
|
||||
path = text(call.given, "file_path")
|
||||
if bash:
|
||||
written = text(call.given, "command")
|
||||
breaches = bash_breaches(written, call.cwd, home)
|
||||
what = written.split("\n", 1)[0]
|
||||
elif call.tool in FILE_TOOLS and path:
|
||||
before = read(path)
|
||||
written, after = applied(call, before)
|
||||
breaches = file_breaches(path, before, written, after)
|
||||
what = path
|
||||
else:
|
||||
return 0
|
||||
judged = verdict(breaches, written, path.endswith(".md"), bash)
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
before = read(path)
|
||||
added, after = applied(call, before)
|
||||
return added, path, file_breaches(path, before, added, after)
|
||||
|
||||
|
||||
def answer(judged: Verdict, what: str, now: float) -> int:
|
||||
for message in judged.messages:
|
||||
print(message, file=sys.stderr)
|
||||
if judged.blocked:
|
||||
return 2
|
||||
for breach, reason in judged.overridden:
|
||||
unlogged = log_override(breach, reason, what, time.time())
|
||||
if unlogged:
|
||||
print(f"rule-hook cannot log the override of {breach.rule}, so it would escape review: {unlogged.reason}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
|
||||
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
|
||||
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
|
||||
for breach, reason, log in logs if not unloggable else []:
|
||||
unwritten = write_override(log, breach, reason, what, now) if isinstance(log, Log) else None
|
||||
unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else []
|
||||
for unlogged in unloggable:
|
||||
print(f"rule-hook cannot log the override of {unlogged}; unlogged, it would escape review.", file=sys.stderr)
|
||||
return 2 if unloggable else 0
|
||||
|
||||
|
||||
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
|
||||
@@ -96,15 +106,30 @@ def todo_breaches(directory: str) -> list[Breach]:
|
||||
top = git(directory, "rev-parse", "--show-toplevel")
|
||||
if isinstance(top, Failure) 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.
|
||||
changed = git(top, "status", "--porcelain", "--", "todo.md")
|
||||
if isinstance(changed, Failure):
|
||||
return [Breach("todo-rank-check", changed.reason, top)]
|
||||
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")] if changed else []
|
||||
todo = pathlib.Path(top) / "todo.md"
|
||||
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(todo)] if changed(top, todo) else []
|
||||
|
||||
|
||||
def log_override(breach: Breach, reason: str, what: str, now: float) -> Failure | None:
|
||||
directory = existing(breach.directory)
|
||||
def changed(top: str, todo: pathlib.Path) -> bool:
|
||||
"""Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command."""
|
||||
# Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed.
|
||||
staged, committed = git(top, "rev-parse", ":todo.md"), git(top, "rev-parse", "HEAD:todo.md")
|
||||
algorithm = git(top, "rev-parse", "--show-object-format")
|
||||
content = todo.read_bytes()
|
||||
worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest()
|
||||
return isinstance(staged, Failure) or staged != worktree or staged != committed
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Log:
|
||||
path: pathlib.Path
|
||||
branch: str
|
||||
head: str
|
||||
|
||||
|
||||
def log_path(directory: str) -> Log | Failure | None:
|
||||
"""Where an override in this directory is logged; None outside any git checkout."""
|
||||
directory = existing(directory)
|
||||
if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]):
|
||||
return None
|
||||
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
@@ -114,11 +139,24 @@ def log_override(breach: Breach, reason: str, what: str, now: float) -> Failure
|
||||
return found
|
||||
# Empty on a branch with no commit yet.
|
||||
head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD")
|
||||
return Log(pathlib.Path(str(common)) / LOG, " ".join(str(branch).split()) or "HEAD", "" if isinstance(head, Failure) else head)
|
||||
|
||||
|
||||
def write_override(log: Log, breach: Breach, reason: str, what: str, now: float) -> Failure | None:
|
||||
line = "\t".join([utc(now), log.branch, log.head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n"
|
||||
try:
|
||||
with open(pathlib.Path(str(common)) / LOG, "a", encoding="utf-8") as log:
|
||||
log.write("\t".join([utc(now), str(branch) or "HEAD", "" if isinstance(head, Failure) else head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n")
|
||||
# No symlink: the checkout, and so its git directory, may come from anyone.
|
||||
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure))
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
|
||||
return Failure(f"{log.path} is no regular file")
|
||||
os.write(descriptor, line.encode("utf-8"))
|
||||
except OSError as failure:
|
||||
return Failure(str(failure))
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
return None
|
||||
|
||||
|
||||
@@ -127,27 +165,23 @@ def print_overrides(directory: str) -> int:
|
||||
if isinstance(common, Failure):
|
||||
print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
|
||||
return 1
|
||||
start = branch_start(directory)
|
||||
branch = git(directory, "branch", "--show-current")
|
||||
default = default_branch(directory)
|
||||
log = pathlib.Path(common) / LOG
|
||||
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
|
||||
for line in lines:
|
||||
commit = line.split("\t")[2:3]
|
||||
if commit == [""] or commit and holds(directory, "HEAD", commit[0]) and (start is None or holds(directory, commit[0], start)):
|
||||
for line in log.read_text(encoding="utf-8").splitlines() if log.is_file() else []:
|
||||
fields = line.split("\t")
|
||||
# Too many beats too few: the overrides pass skips a line whose breach the branch no longer holds, while an amend or a rebase leaves a line's commit off HEAD.
|
||||
if fields[1:2] == [branch] or default is None or not holds(directory, default, fields[2] if len(fields) > 2 else ""):
|
||||
print(line)
|
||||
return 0
|
||||
|
||||
|
||||
def branch_start(directory: str) -> str | None:
|
||||
"""Where HEAD left the default branch, None when no default branch is known."""
|
||||
for default in ("origin/HEAD", "main", "master"):
|
||||
start = git(directory, "merge-base", "HEAD", default)
|
||||
if not isinstance(start, Failure):
|
||||
return start
|
||||
return None
|
||||
def default_branch(directory: str) -> str | None:
|
||||
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
|
||||
|
||||
|
||||
def holds(directory: str, descendant: str, ancestor: str) -> bool:
|
||||
return not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
|
||||
return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
|
||||
|
||||
|
||||
def git(directory: str, *args: str) -> str | Failure:
|
||||
|
||||
Reference in New Issue
Block a user