94 lines
4.8 KiB
Python
94 lines
4.8 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.
|
|
main.py reads the file and the transcript; this module only decides."""
|
|
import dataclasses
|
|
import re
|
|
|
|
from rule_hook.rules import Breach
|
|
from claude_code.entries import parts, tool_call, tool_result, tool_use_id
|
|
from shell_command import resolved, simple_commands
|
|
from rule_hook.call import text
|
|
|
|
# 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(asked: Asked, lines: list[str], thread: list[dict], cwd: str, home: str) -> list[Breach]:
|
|
"""thread is the calling agent's transcript thread since its last compaction, and lines the asked file's lines now."""
|
|
last = len(lines) if asked.last is None else min(asked.last, len(lines))
|
|
if not in_context(asked.first, last, lines, shown_lines(thread, asked.path, home)):
|
|
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", cwd)]
|
|
|
|
|
|
def in_context(first: int, last: int, lines: list[str], shown: dict[int, str]) -> bool:
|
|
return first <= last and all(shown.get(number) == lines[number - 1] for number in range(first, last + 1))
|
|
|
|
|
|
def file_lines(content: str) -> list[str]:
|
|
return content.removesuffix("\n").split("\n") if content else []
|
|
|
|
|
|
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
|
|
return read_asked(given, cwd, home) if tool == "Read" else shell_asked(text(given, "command"), cwd, home) if tool == "Bash" else None
|
|
|
|
|
|
def read_asked(given: dict, cwd: str, home: str) -> Asked | None:
|
|
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
|
|
|
|
|
|
# reading_cost/shell_reads.py parses a shell read too, loosely: a measure of reading counts any file a reader names, while a rule that blocks must match only a read whose lines it knows exactly.
|
|
def shell_asked(command: str, cwd: str, home: str) -> Asked | None:
|
|
simples = simple_commands(command, cwd, home) if 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])):
|
|
start, end = ranged.groups()
|
|
return Asked(path, int(start), None if end == "$" else int(end or start))
|
|
return None
|
|
|
|
|
|
def shown_lines(thread: list[dict], path: str, home: str) -> dict[int, str]:
|
|
"""Each line number of path that a successful read in the thread showed, with the line its latest read showed."""
|
|
reads: dict[str, tuple[object, Asked]] = {}
|
|
shown: dict[int, str] = {}
|
|
for entry in thread:
|
|
for part in parts(entry):
|
|
if (call := tool_call(part)) and (called := tool_use_id(part)) and (asked := asked_lines(*call, str(entry.get("cwd", "")), home)) and asked.path == path:
|
|
reads[called] = (call[0], asked)
|
|
elif (result := tool_result(part)) and not result.failed and (read := reads.get(result.tool_use_id)):
|
|
shown |= result_lines(*read, result.text)
|
|
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}
|