import dataclasses import posixpath import re import typing from shell_command import resolved, Simple RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"] @dataclasses.dataclass(frozen=True) class Rule: holds: str checked: str RULES: dict[RuleName, Rule] = { "action-pin": Rule( "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA only in a pipeline that tests our own specific builds", "`uses:` in a .github or .gitea workflow, or in action.yml", ), "commit-one-line": Rule( "a commit message is one line, prefixed with the ticket ID when the work has one", "git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked", ), "ignorefile-sorted": Rule( "each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, 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", "a .*ignore file; a block already unsorted before the edit is left alone", ), "image-pin": Rule( "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; an image that publishes no three-part tag, such as postgres:16.4, takes an override", "a Dockerfile's FROM and COPY --from, and `image:` and `container:` in a compose file or workflow", ), "no-ai-attribution": Rule( "no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line", "a git, gh or tea command, and any file written", ), "todo-rank-check": Rule( "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it", "a git commit in a checkout whose todo.md has changes", ), } OVERRIDE = re.compile(r"(?:#|").strip()) for rule, reason in OVERRIDE.findall(written)] granted = {rule: reason for rule, reason in given if rule in RULES and reason} return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted] def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Verdict: granted, malformed = overrides(written) blocking = [breach for breach in breaches if breach.rule not in granted] messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else [] where = "the command" if 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) marker = f"" if markdown else f"# rule-override {rule}: " messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.") return Verdict(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted]) def commits(simples: list[Simple], home: str) -> list[Commit]: found = [] for simple in simples: invoked = git_subcommand(simple.words, simple.directory, home) if invoked and invoked[0] == "commit": found.append(Commit(invoked[2], *commit_message(invoked[1]))) return found def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None: """A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C.""" if words[:1] != ["git"]: return None args = iter(words[1:]) for word in args: if word in GIT_VALUED: value = next(args, "") directory = resolved(directory, value, home) if word == "-C" else directory elif not word.startswith("-"): return word, list(args), directory return None def commit_message(args: list[str]) -> tuple[list[str], bool]: """git commit's messages, and whether it reads one from a file.""" messages = [] from_file = False words = iter(args) for word in words: if word == "--": break name, equals, value = word.partition("=") if name in ("--message", "--file"): given = value if equals else next(words, "") elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]): # A cluster such as -am: the valued flag takes the rest of the word, or else the next word. name = "--message" if flags[0] == "m" else "--file" given = word[word.index(flags[0]) + 1:] or next(words, "") else: continue messages += [given] if name == "--message" else [] from_file = from_file or name == "--file" return messages, from_file def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]: breaches = [] found = commits(simples, home) publishing = [simple for simple in simples if simple.words[0] in ("gh", "git", "tea")] if publishing and ATTRIBUTION.search(command): breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory)) for commit in found: if commit.from_file: breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file", commit.directory)) elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages): breaches.append(Breach("commit-one-line", "pass the message as one -m '', with no heredoc, second -m or newline", commit.directory)) return breaches def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]: """Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves.""" breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else [] return breaches + image_breaches(path, before, added, after) + action_breaches(path, added) + ignore_breaches(path, before, after) def image_breaches(path: str, before: str, added: str, after: str) -> list[Breach]: name = posixpath.basename(path) if name.startswith(("Dockerfile", "Containerfile")) or name.endswith((".dockerfile", ".Dockerfile", ".containerfile")): stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} | {"scratch"} images = [image for image, _ in FROM.findall(added) if image.lower() not in stages] + [image for image in COPIED.findall(added) if image.lower() not in stages and not image.isdigit()] elif "compose" in name and name.endswith((".yml", ".yaml")) or workflow(path): images = IMAGE.findall(added) else: images = [] return [Breach("image-pin", f"{path}: {image}", posixpath.dirname(path)) for image in images if not pinned(image)] def action_breaches(path: str, added: str) -> list[Breach]: actions = USES.findall(added) if workflow(path) else [] return [Breach("action-pin", f"{path}: uses: {action}", posixpath.dirname(path)) for action in actions if not tagged(action)] def ignore_breaches(path: str, before: str, after: str) -> list[Breach]: name = posixpath.basename(path) if not (name.startswith(".") and name.endswith("ignore")): return [] already = [block for block in blocks(before) if block != sorted(block)] return [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} as {', '.join(sorted(block))}", posixpath.dirname(path)) for block in blocks(after) if block != sorted(block) and block not in already] def workflow(path: str) -> bool: return any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or posixpath.basename(path) in ("action.yml", "action.yaml") def pinned(image: str) -> bool: if "$" in image or "{{" in image or "@sha256:" in image: return True tail = image.rsplit("/", 1)[-1] return ":" in tail and PATCH.fullmatch(tail.split(":", 1)[1]) is not None def tagged(action: str) -> bool: if action.startswith(("./", "docker://")) or "$" in action or "{{" in action: return True return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None def blocks(written: str) -> list[list[str]]: """An ignore file's runs of patterns, split at each blank line and comment.""" runs: list[list[str]] = [[]] for line in written.splitlines(): if line.strip() and not line.startswith("#"): runs[-1].append(line) elif runs[-1]: runs.append([]) return [run for run in runs if run] def rules_help() -> str: return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." for name, rule in RULES.items())