Block a read of file lines already in the agent's context, unless a compaction dropped them or the file changed
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import dataclasses
|
||||
import posixpath
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
@@ -13,6 +14,8 @@ class Call:
|
||||
cwd: str
|
||||
# The subagent the call comes from, such as prose-reviewer; empty for the session's own agent.
|
||||
agent: str = ""
|
||||
# The transcript of the agent that makes the call: a subagent's own, not its session's.
|
||||
transcript: str = ""
|
||||
|
||||
|
||||
def parsed_call(hook_input: object) -> Call | Failure:
|
||||
@@ -21,8 +24,12 @@ def parsed_call(hook_input: object) -> Call | Failure:
|
||||
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
|
||||
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
|
||||
return Failure("the hook input has no string tool_name and cwd and object tool_input")
|
||||
agent = hook_input.get("agent_type")
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "")
|
||||
agent, agent_id, transcript = hook_input.get("agent_type"), hook_input.get("agent_id"), hook_input.get("transcript_path")
|
||||
transcript = transcript if isinstance(transcript, str) else ""
|
||||
if isinstance(agent_id, str) and transcript:
|
||||
# Inside a subagent, transcript_path still names the session's transcript; the subagent's own sits beside it.
|
||||
transcript = posixpath.join(posixpath.splitext(transcript)[0], "subagents", f"agent-{agent_id}.jsonl")
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript)
|
||||
|
||||
|
||||
def text(given: dict[str, typing.Any], key: str) -> str:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
||||
rule-hook overrides (prints this chunk's overrides)
|
||||
|
||||
settings.json runs it before each Bash, Edit, MultiEdit, Write and Agent call, in every session and
|
||||
settings.json runs it before each Bash, Edit, MultiEdit, Write, Agent and Read call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
@@ -40,6 +40,7 @@ from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_command import commits
|
||||
from failure import Failure
|
||||
from rule_hook.repeat_read import repeat_breaches
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.reviewer_report import report_breaches
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
@@ -76,7 +77,9 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + repeat_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), repeat_breaches(call, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""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 ""
|
||||
@@ -10,7 +10,7 @@ from shell_command import launched, Simple, tool_name
|
||||
from review_folder import REPORTS
|
||||
from docker_command import unlimited
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -46,6 +46,12 @@ RULES: dict[RuleName, 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",
|
||||
),
|
||||
# A Read carries no text for a marker, and a misjudged read has a way through that the message names, so no marker waives it.
|
||||
"repeat-read": Rule(
|
||||
"an agent reads no lines of a file that its context already holds unchanged, since each read pays for them again; where the context lacks them although the transcript shows them, as after Claude Code cleared old tool results, read them with another command, such as `grep -n ''`",
|
||||
"a Read call, and 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, against the reads in the calling agent's own transcript since its last compaction",
|
||||
overridable=False,
|
||||
),
|
||||
# A reviewer only reports, so no marker waives it.
|
||||
"reviewer-report": Rule(
|
||||
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
|
||||
|
||||
@@ -11,7 +11,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
|
||||
from rule_hook.main import breaches_of
|
||||
from rule_hook.call import Call
|
||||
from rule_hook.call import Call, parsed_call
|
||||
from rule_hook.repeat_read import repeat_breaches
|
||||
from git_command import Commit, commit_message, commits
|
||||
from test_rank_todo import DECISIONS, README, TODO
|
||||
from test_env import isolated_env
|
||||
@@ -328,6 +329,109 @@ class ReviewerReport(unittest.TestCase):
|
||||
self.assertEqual(self.breached("Write", "/r/README.md", "general-purpose"), [])
|
||||
|
||||
|
||||
class RepeatRead(unittest.TestCase):
|
||||
LINES = [f"line {n}" for n in range(1, 31)]
|
||||
|
||||
def setUp(self):
|
||||
self.folder = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", self.folder])
|
||||
self.file = f"{self.folder}/f.txt"
|
||||
pathlib.Path(self.file).write_text("\n".join(self.LINES) + "\n")
|
||||
self.transcript = f"{self.folder}/s.jsonl"
|
||||
self.entries: list[dict] = []
|
||||
|
||||
def add(self, entry: dict, parent: str | None = "last") -> str:
|
||||
uuid = f"u{len(self.entries)}"
|
||||
parent = (self.entries[-1]["uuid"] if self.entries else None) if parent == "last" else parent
|
||||
self.entries.append({"uuid": uuid, "parentUuid": parent, "cwd": self.folder} | entry)
|
||||
pathlib.Path(self.transcript).write_text("\n".join(json.dumps(entry) for entry in self.entries) + "\n")
|
||||
return uuid
|
||||
|
||||
def used(self, tool: str, given: dict, result: str, error: bool = False) -> None:
|
||||
tool_id = f"toolu_{len(self.entries)}"
|
||||
self.add({"type": "assistant", "message": {"content": [{"type": "tool_use", "id": tool_id, "name": tool, "input": given}]}})
|
||||
self.add({"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": result, "is_error": error}]}})
|
||||
|
||||
def read(self, start: int, end: int) -> None:
|
||||
self.used("Read", {"file_path": self.file, "offset": start, "limit": end - start + 1}, "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(start, end + 1)))
|
||||
|
||||
def shown(self, start: int, end: int) -> str:
|
||||
return "\n".join(self.LINES[start - 1:end])
|
||||
|
||||
def found(self, tool: str, given: dict, agent: str = "") -> list[Breach]:
|
||||
return repeat_breaches(Call(tool, given, self.folder, agent, self.transcript), "/h")
|
||||
|
||||
def test_a_read_of_lines_already_read_is_blocked_with_a_note(self):
|
||||
self.read(1, 10)
|
||||
found = self.found("Read", {"file_path": self.file, "offset": 2, "limit": 5})
|
||||
self.assertEqual(rules(found), ["repeat-read"])
|
||||
self.assertIn(f"lines 2-6 of {self.file} are in your context", found[0].detail)
|
||||
|
||||
def test_lines_read_in_two_reads_are_in_context(self):
|
||||
self.read(1, 10)
|
||||
self.read(11, 20)
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10})), ["repeat-read"])
|
||||
|
||||
def test_a_read_past_what_was_read_goes_through(self):
|
||||
self.read(1, 10)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10}), [])
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file}), [], "a Read without a limit asks for the whole file")
|
||||
|
||||
def test_a_compaction_lets_the_read_through(self):
|
||||
self.read(1, 10)
|
||||
self.add({"type": "system", "subtype": "compact_boundary"}, parent=None)
|
||||
self.add({"type": "user", "message": {"content": "This session is being continued"}})
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_a_changed_file_lets_the_read_through(self):
|
||||
self.read(1, 10)
|
||||
pathlib.Path(self.file).write_text("changed\n" + "\n".join(self.LINES[1:]) + "\n")
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 2, "limit": 9})), ["repeat-read"], "the lines that did not change are still in context")
|
||||
|
||||
def test_a_failed_read_holds_no_lines(self):
|
||||
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(1, 11)), error=True)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_a_read_on_a_branch_the_session_left_holds_no_lines(self):
|
||||
start = self.add({"type": "user", "message": {"content": "go"}})
|
||||
self.read(1, 10)
|
||||
self.add({"type": "user", "message": {"content": "go again"}}, parent=start)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_cat_head_and_sed_count_as_reads_both_ways(self):
|
||||
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
|
||||
for command in [f"head -n 5 {self.file}", f"head -5 {self.file}", f"head {self.file}", "sed -n '3,8p' f.txt", "sed -n 7p f.txt"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(rules(self.found("Bash", {"command": command})), ["repeat-read"])
|
||||
self.assertEqual(self.found("Bash", {"command": f"cat {self.file}"}), [], "only 20 of the 30 lines were read")
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3})), ["repeat-read"])
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
|
||||
self.assertEqual(rules(self.found("Bash", {"command": "sed -n '25,$p' f.txt"})), ["repeat-read"])
|
||||
|
||||
def test_a_read_whose_output_goes_elsewhere_is_not_checked(self):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
|
||||
for command in [f"cat {self.file} > copy", f"cat {self.file} | wc -l", f"cat {self.file} {self.file}", f"head -c 5 {self.file}", f"sed 's/a/b/' {self.file}"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.found("Bash", {"command": command}), [])
|
||||
|
||||
def test_a_truncated_output_holds_only_the_lines_it_shows(self):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 5) + "\n... [25 lines truncated] ...")
|
||||
self.assertEqual(self.found("Bash", {"command": f"head -n 10 {self.file}"}), [])
|
||||
self.assertEqual(rules(self.found("Bash", {"command": f"head -n 5 {self.file}"})), ["repeat-read"])
|
||||
|
||||
def test_a_subagent_is_judged_on_its_own_transcript(self):
|
||||
self.read(1, 10)
|
||||
given = {"cwd": self.folder, "tool_name": "Read", "tool_input": {"file_path": self.file, "offset": 1, "limit": 10}, "transcript_path": self.transcript}
|
||||
subagent = parsed_call(given | {"agent_id": "a1", "agent_type": "Explore"})
|
||||
self.assertEqual(subagent.transcript, f"{self.folder}/s/subagents/agent-a1.jsonl")
|
||||
self.assertEqual(repeat_breaches(subagent, "/h"), [], "the parent's reads are not in the subagent's context")
|
||||
self.assertEqual(rules(repeat_breaches(parsed_call(given), "/h")), ["repeat-read"])
|
||||
|
||||
def test_a_missing_transcript_blocks_nothing(self):
|
||||
self.assertEqual(repeat_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), [])
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.repo = tempfile.mkdtemp()
|
||||
@@ -477,7 +581,7 @@ class Hook(unittest.TestCase):
|
||||
|
||||
def test_help_lists_every_rule(self):
|
||||
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
|
||||
for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]:
|
||||
for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]:
|
||||
self.assertIn(f" {rule}\n The rule: ", helped)
|
||||
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
|
||||
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
|
||||
|
||||
Reference in New Issue
Block a user