Answer architecture round 1: 2 🔴, 2 🟡 (0 misread); move transcript parsing into claude_code and keep repeat_read pure

This commit is contained in:
2026-10-28 12:51:24 +01:00
parent 1d2f3d14d2
commit 248e46f616
10 changed files with 110 additions and 86 deletions
+36 -58
View File
@@ -1,14 +1,15 @@
"""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."""
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 rule_hook.call import Call, text
from claude_code.entries import parse_entry, part_text, parts
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
@@ -26,28 +27,38 @@ class Asked:
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 []
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))
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)):
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", call.cwd)]
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
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 []
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
@@ -62,43 +73,16 @@ def asked_lines(tool: object, given: object, cwd: str, home: str) -> Asked | Non
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]] = {}
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 entries:
for entry in thread:
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")))
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
@@ -107,9 +91,3 @@ def result_lines(tool: object, asked: Asked, result: str) -> dict[int, str]:
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 ""