Answer architecture round 1: 2 🔴, 2 🟡 (0 misread); move transcript parsing into claude_code and keep repeat_read pure
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import dataclasses
|
||||
import posixpath
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from claude_code.session import subagent_transcript
|
||||
|
||||
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
|
||||
|
||||
@@ -27,8 +27,8 @@ def parsed_call(hook_input: object) -> Call | Failure:
|
||||
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")
|
||||
# Inside a subagent, transcript_path still names the session's transcript.
|
||||
transcript = subagent_transcript(transcript, agent_id)
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript)
|
||||
|
||||
|
||||
|
||||
+13
-3
@@ -37,11 +37,12 @@ import time
|
||||
import typing
|
||||
|
||||
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.repeat_read import asked_lines, file_lines, repeat_breaches
|
||||
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_command import commits
|
||||
from claude_code.transcript import current_thread, read_transcript
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.repeat_read import repeat_breaches
|
||||
from rule_hook.reviewer_report import report_breaches
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from shell_command import simple_commands
|
||||
@@ -77,9 +78,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) + repeat_breaches(call, home)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), repeat_breaches(call, home)
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
@@ -110,6 +111,15 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
|
||||
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
|
||||
|
||||
|
||||
def read_breaches(call: Call, home: str) -> list[Breach]:
|
||||
"""The repeat-read breaches of a call, read from the asked file and the calling agent's transcript; none where either cannot be read."""
|
||||
asked = asked_lines(call.tool, call.given, call.cwd, home)
|
||||
entries = read_transcript(call.transcript) if asked and call.transcript else []
|
||||
if asked is None or isinstance(entries, Failure) or not entries:
|
||||
return []
|
||||
return repeat_breaches(asked, file_lines(read(asked.path)), current_thread(entries), call.cwd, home)
|
||||
|
||||
|
||||
def read(path: str) -> str:
|
||||
try:
|
||||
return pathlib.Path(path).read_text(encoding="utf-8")
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
@@ -10,14 +10,13 @@ import unittest.mock
|
||||
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.main import breaches_of, read_breaches
|
||||
from rule_hook.call import Call, parsed_call
|
||||
from git_command import Commit, commit_message, commits
|
||||
from test_rank_todo import DECISIONS, README, TODO
|
||||
from test_env import isolated_env
|
||||
from model_routing import ladder
|
||||
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
|
||||
from rule_hook.repeat_read import repeat_breaches
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from rule_hook.git import git as rule_hook_git
|
||||
from model_routing.ladder import Rung
|
||||
@@ -359,7 +358,7 @@ class RepeatRead(unittest.TestCase):
|
||||
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")
|
||||
return read_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)
|
||||
@@ -425,11 +424,11 @@ class RepeatRead(unittest.TestCase):
|
||||
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"])
|
||||
self.assertEqual(read_breaches(subagent, "/h"), [], "the parent's reads are not in the subagent's context")
|
||||
self.assertEqual(rules(read_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"), [])
|
||||
self.assertEqual(read_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), [])
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user