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

116 lines
5.4 KiB
Python

"""Whether a read asks for lines of a file already in the agent's context, for the `repeat-read` rule.
A read is a Read call, or a Bash command that is one `cat <file>`, `head [-n <N> | -<N>] <file>` or `sed -n '<A>[,<B>]p' <file>`, with no pipe or redirect.
Lines are in context when earlier reads' results show each of them, as the file holds it now and at its line number now, in the transcript's thread since its last compaction."""
import dataclasses
import re
from claude_code.entries import parse_entry, part_text, parts
from rule_hook.call import Call, text
from rule_hook.rules import Breach
from shell_command import resolved, simple_commands
# The lines a Read without a limit returns.
READ_LIMIT = 2000
# A line of a Read result: its number, then a tab, or an arrow in older Claude Code versions.
NUMBERED = re.compile(r" *(\d+)[\t→](.*)", re.DOTALL)
HEAD_COUNT = re.compile(r"-(?:n ?)?(\d+)")
SED_RANGE = re.compile(r"(\d+)(?:,(\d+|\$))?p")
@dataclasses.dataclass(frozen=True)
class Asked:
path: str
first: int
# None: to the file's end.
last: int | None
def repeat_breaches(call: Call, home: str) -> list[Breach]:
asked = asked_lines(call.tool, call.given, call.cwd, home)
lines = file_lines(asked.path) if asked and call.transcript else None
if asked is None or lines is None:
return []
last = len(lines) if asked.last is None else min(asked.last, len(lines))
shown = shown_lines(thread(call.transcript), asked.path, home)
if asked.first > last or any(shown.get(number) != lines[number - 1] for number in range(asked.first, last + 1)):
return []
return [Breach("repeat-read", f"lines {asked.first}-{last} of {asked.path} are in your context, unchanged since you read them; read them there", call.cwd)]
def asked_lines(tool: object, given: object, cwd: str, home: str) -> Asked | None:
"""The lines a tool call reads; None for a call that is no read, or whose output goes elsewhere than the agent's context."""
if not isinstance(given, dict):
return None
if tool == "Read":
path, offset, limit = text(given, "file_path"), given.get("offset"), given.get("limit")
first = offset if isinstance(offset, int) and offset > 0 else 1
return Asked(resolved(cwd, path, home), first, first + (limit if isinstance(limit, int) and limit > 0 else READ_LIMIT) - 1) if path else None
command = text(given, "command")
simples = simple_commands(command, cwd, home) if tool == "Bash" and not set("|<>") & set(command) else []
if len(simples) != 1 or len(simples[0].words) < 2 or simples[0].words[-1].startswith("-"):
return None
(name, *options, path), directory = simples[0].words, simples[0].directory
path = resolved(directory, path, home)
if name == "cat" and not options:
return Asked(path, 1, None)
if name == "head" and (counted := HEAD_COUNT.fullmatch(" ".join(options) or "-10")):
return Asked(path, 1, int(counted.group(1)))
if name == "sed" and len(options) == 2 and options[0] == "-n" and (ranged := SED_RANGE.fullmatch(options[1])):
first, last = ranged.groups()
return Asked(path, int(first), None if last == "$" else int(last or first))
return None
def file_lines(path: str) -> list[str] | None:
try:
with open(path, encoding="utf-8") as handle:
content = handle.read()
except (OSError, UnicodeDecodeError):
return None
return content.removesuffix("\n").split("\n") if content else []
def thread(path: str) -> list[dict]:
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry and its ancestors, which leaves out a branch the session rewound."""
try:
with open(path, "rb") as handle:
entries = [entry for raw in handle if (entry := parse_entry(raw)) and isinstance(entry.get("uuid"), str)]
except OSError:
return []
by_uuid = {entry["uuid"]: entry for entry in entries}
found: list[dict] = []
entry = entries[-1] if entries else None
while entry is not None and entry.get("subtype") != "compact_boundary" and len(found) < len(entries):
found.append(entry)
entry = by_uuid.get(entry.get("parentUuid"))
return found[::-1]
def shown_lines(entries: list[dict], path: str, home: str) -> dict[int, str]:
"""Each line number of path that a successful read in the entries showed, with the line its latest read showed."""
reads: dict[object, tuple[object, Asked]] = {}
shown: dict[int, str] = {}
for entry in entries:
for part in parts(entry):
if not isinstance(part, dict):
continue
if part.get("type") == "tool_use" and (asked := asked_lines(part.get("name"), part.get("input"), str(entry.get("cwd", "")), home)) and asked.path == path:
reads[part.get("id")] = (part.get("name"), asked)
elif part.get("type") == "tool_result" and not part.get("is_error") and (read := reads.get(part.get("tool_use_id"))):
shown |= result_lines(read[0], read[1], result_text(part.get("content")))
return shown
def result_lines(tool: object, asked: Asked, result: str) -> dict[int, str]:
if tool == "Read":
return {int(numbered.group(1)): numbered.group(2) for line in result.split("\n") if (numbered := NUMBERED.fullmatch(line))}
# A Bash output Claude Code cut short shows a note in place of the lines it left out, so those lines differ from the file's and count as unread.
return {number: line for number, line in enumerate(result.split("\n"), asked.first) if asked.last is None or number <= asked.last}
def result_text(content: object) -> str:
if isinstance(content, str):
return content
return "\n".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""