diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 7bbfee5c..f02ffae7 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -1,5 +1,6 @@ """Entries of Claude Code's transcripts and of its stream-json and json output.""" import json +import typing def parse_entry(raw: str | bytes) -> dict | None: @@ -87,11 +88,35 @@ def part_text(part: object) -> str | None: return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None -# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}} +# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}} def tool_call(part: object) -> tuple[object, object] | None: return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None +def tool_use_id(part: object) -> str | None: + return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None + + +class ToolResult(typing.NamedTuple): + tool_use_id: str + text: str + failed: bool + + +# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed +def tool_result(part: object) -> ToolResult | None: + if not isinstance(part, dict) or part.get("type") != "tool_result": + return None + return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error"))) + + +def result_text(content: object) -> str: + if isinstance(content, str): + return content + # Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them. + return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else "" + + # stream-json's last line: {"type": "result", "subtype": "success", ...} def ends_stream(event: dict) -> bool: return event.get("type") == "result" diff --git a/bin/claude_code/session.py b/bin/claude_code/session.py index 3eba8910..0f8774da 100644 --- a/bin/claude_code/session.py +++ b/bin/claude_code/session.py @@ -37,6 +37,11 @@ def session_files(transcript: str) -> list[str]: return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")) +# /subagents/agent-.jsonl, beside .jsonl +def subagent_transcript(session_transcript: str, agent_id: str) -> str: + return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl") + + def delete_session(session: Session) -> Failure | None: path = transcript_file(session) if path is None: diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 8c068b7d..cb09e6fa 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -21,6 +21,19 @@ def read_transcript(path: str) -> list[dict] | Failure: return Failure(f"could not read the transcript {path}: {failure.strerror}") +def current_thread(entries: list[dict]) -> list[dict]: + """The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid, which leaves out a branch the session rewound.""" + chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)] + by_uuid = {entry["uuid"]: entry for entry in chained} + found: list[dict] = [] + entry = chained[-1] if chained else None + # {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...} starts the thread anew after a compaction; the length check stops a parent cycle. + while entry is not None and entry.get("subtype") != "compact_boundary" and len(found) < len(chained): + found.append(entry) + entry = by_uuid.get(entry.get("parentUuid")) + return found[::-1] + + # The lines before it, such as the session's title, are the same for every chunk of a project. def first_timestamped_line(raw: bytes) -> bytes: lines = raw.splitlines() diff --git a/bin/reading_cost/shell_reads.py b/bin/reading_cost/shell_reads.py index 69593060..958c147f 100644 --- a/bin/reading_cost/shell_reads.py +++ b/bin/reading_cost/shell_reads.py @@ -27,6 +27,7 @@ def shell_reads(command: str, cwd: str, home: str) -> Reads: return Reads(read, added) +# rule_hook/repeat_read.py parses a shell read too, strictly: 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 operands(words: list[str]) -> list[str]: program = posixpath.basename(words[0]) if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)): diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index 67b24ea6..291aff0a 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -5,7 +5,7 @@ import re import statistics import typing -from claude_code.entries import assistant_parts, parts, tool_call +from claude_code.entries import assistant_parts, parts, tool_call, tool_result from git_command import commits from model_routing.route import ESCALATION_MARKER, route_from from routing_figures.prices import listed @@ -204,19 +204,7 @@ def messages(entries: list[dict]) -> list[Message]: def results(entries: list[dict]) -> dict[str, str]: """Each tool result's text by the id of the call it answers.""" - found = {} - for entry in entries: - for part in parts(entry): - if isinstance(part, dict) and part.get("type") == "tool_result": - found[str(part.get("tool_use_id"))] = result_text(part.get("content")) - return found - - -# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]} -def result_text(body: object) -> str: - if isinstance(body, str): - return body - return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else "" + return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))} def rounds_past_first(worker: list[dict], home: str) -> int: diff --git a/bin/rule_hook/call.py b/bin/rule_hook/call.py index f8e69cc1..afd5d1e7 100644 --- a/bin/rule_hook/call.py +++ b/bin/rule_hook/call.py @@ -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) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 66c758d4..e3103df4 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -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") diff --git a/bin/rule_hook/repeat_read.py b/bin/rule_hook/repeat_read.py index a810619a..00e996e1 100644 --- a/bin/rule_hook/repeat_read.py +++ b/bin/rule_hook/repeat_read.py @@ -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 `, `head [-n | -] ` or `sed -n '[,]p' `, 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 "" diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index fa72c52d..01a922e2 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -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): diff --git a/todo.md b/todo.md index 90a57ecf..7628c4cb 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 246` +`Next ID = 247` ## Items @@ -15,6 +15,7 @@ | 244 | 0.4.0 | | owner | **Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`.** | 2 | 2 | 1 | 3 | 3 | 1.5 by 2 | 1.9 | | 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 | | 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 | +| 246 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 | | 235 | 0.5.0 | | decision | **Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, πŸ”΄, 🟑 and misread findings, dollars and hours per chunk, and file an item where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 | | 167 | 0.5.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 | | 6 | 0.5.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 | @@ -98,6 +99,10 @@ Bench the app's command name and how it shows a question with readers seated as Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, `python3 -m mutmut run`, `sudo docker build .`, `docker image build .` and `docker compose up --build` pass the rule, which `docs/decisions.md` β†’ `machine load: …` and `RULES["run-heavy"]` describe as blocking docker builds and mutation runs. The rule's own text says a gate script isn't checked since no program can tell it from a light one, so the human decides where the line sits. Say what the rule's "checked" text promises either way. Where the answer widens the rule, the change touches `heavy` in `bin/rule_hook/heavy_command.py`, which the comprehension seats found hard: make it easier to read. +### 246. Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason. + +Filed from PR #387's architecture round 1. The decision's 2026-10-16 addendum says `reviewer-rung` is the one rule no marker overrides. `reviewer-report` already took no marker, and PR #387 adds `repeat-read`, so three rules take none, each with its reason only in a comment above it in `bin/rule_hook/rules.py`. A reader of the decision, the judge included, believes every other rule takes an override. The fix rewords the title and the addendum to name all three; it changes a decision, so it is lilleman's. + ### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, πŸ”΄, 🟑 and misread findings, dollars and hours per chunk, and file an item where any rose. `docs/decisions.md` β†’ `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the πŸ”΄, 🟑 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged.