Files
claude-config/bin/rule_hook/reviewer_rung.py
T

108 lines
6.0 KiB
Python

"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out on the project's ladder from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
import pathlib
import typing
from rule_hook.rules import Breach
from rule_hook.call import Call, text
from failure import Failure
from git_cli import git_repo
from rule_hook.git import guarded_git
from model_routing.worker_rungs import handed, hands_rungs
from model_routing.ladder import Ladder, ReviewKind, Rung
from model_routing.ladder_file import project_ladder
from review_rules.review_passes import prose, REVIEWERS
from claude_code.transcript import read_transcript
from claude_code.entries import UserText
# The pass each agent under agents/ reviews.
PASS_OF = {agent: kind for kind, agent in REVIEWERS.items()}
# The opening of every comprehension seat's prompt: skills/comprehension-panel/seat-prompts.md → "Opening".
SEAT = "You are one seat of a comprehension panel."
# The opening of the security pass's prompt: skills/larv-review/SKILL.md → "Security".
SECURITY_OPENER = "You are the security pass for this chunk."
SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "the security pass's subagent"}
# The skills that run the security pass, by their names with any plugin prefix cut.
SECURITY_SKILLS = {"claude-security", "security-review"}
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
kind = review_kind(call.given)
if kind is None or not hands_rungs(environ):
return []
ladder = project_ladder(call.cwd, pathlib.Path(home))
if isinstance(ladder, Failure):
return [unread(ladder, call.cwd)]
project, worker, escape_and_impact = handed(environ, ladder)
if project is None or worker is None:
return []
required = ladder.review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
named = named_rung(call.given, worker, ladder)
if ladder.position(named) >= ladder.position(required):
return []
subject = SUBJECTS.get(kind) or text(call.given, "subagent_type")
return [Breach("reviewer-rung", f"{subject} would run on {named}, below {required}: launch it with {required.agent_args()}", call.cwd)]
def unread(ladder: Failure, cwd: str) -> Breach:
"""The breach of a review launched where loop-claude handed rungs and the project's ladder cannot be read, so nothing tells which rung the review needs."""
return Breach("reviewer-rung", f"the rung this review needs cannot be worked out: {ladder.reason}", cwd)
def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
"""The breach of a Skill call that runs the security pass below the project's rung; none where loop-claude handed no rungs.
The skill runs on its caller's rung. A subagent launched as the security pass was held to the project's rung by reviewer_breaches. The worker's own rung is known, so its call is refused only below the project's rung. Any other subagent's rung is unknown, so its call is refused."""
skill = text(call.given, "skill").lstrip("/").rsplit(":", 1)[-1]
if skill not in SECURITY_SKILLS or not hands_rungs(environ) or opening_prompt(call.transcript).startswith(SECURITY_OPENER):
return []
ladder = project_ladder(call.cwd, pathlib.Path(home))
if isinstance(ladder, Failure):
return [unread(ladder, call.cwd)]
project, worker, _ = handed(environ, ladder)
if project is None or worker is None:
return []
if not call.subagent and ladder.position(worker) >= ladder.position(project):
return []
runs_on = "on a rung rule-hook cannot see" if call.subagent else f"in this context on {worker}, below {project}"
return [Breach("reviewer-rung", f"{skill} would run {runs_on}: invoke it from a subagent launched with {project.agent_args()}, its prompt opening with `{SECURITY_OPENER}`", call.cwd)]
def opening_prompt(transcript: str) -> str:
"""The prompt a transcript opens with, such as a subagent's from its Agent call; empty where it cannot be read."""
entries = read_transcript(transcript) if transcript else []
first = entries[0] if isinstance(entries, list) and entries else None
return first.text.lstrip() if isinstance(first, UserText) else ""
def review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
"""What a launch reviews, a reviewer's pass, a comprehension seat or the security pass; None for any other subagent."""
if pass_reviewed := PASS_OF.get(text(given, "subagent_type")):
return pass_reviewed
opening = text(given, "prompt").lstrip()
if opening.startswith(SEAT):
return "seat"
if opening.startswith(SECURITY_OPENER):
return "security"
return None
def named_rung(given: dict[str, typing.Any], worker: Rung, ladder: Ladder) -> Rung:
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung on ladder."""
model, effort = text(given, "model"), text(given, "effort")
if not model:
return Rung(worker.model, effort or worker.effort)
return ladder.from_agent(model, effort)
def markdown_only(directory: str) -> bool:
"""Whether every file the branch in directory changes, against the default branch as last fetched, is Markdown that no agent follows, counting uncommitted and untracked files; False where it changes none or git cannot say."""
default = git_repo.default_ref(directory, guarded=True)
base = default if isinstance(default, Failure) else guarded_git(directory, "merge-base", default, "HEAD")
changed = base if isinstance(base, Failure) else guarded_git(directory, "diff", "--name-only", base)
untracked = guarded_git(directory, "ls-files", "--others", "--exclude-standard")
if isinstance(changed, Failure) or isinstance(untracked, Failure):
return False
paths = [*changed.splitlines(), *untracked.splitlines()]
return bool(paths) and all(prose(path) for path in paths)