diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index ed4ad26d..3f3f0372 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -68,7 +68,7 @@ class AssistantTurn(Entry): @dataclasses.dataclass(frozen=True, kw_only=True) class ToolResults(Entry): - """A "user" entry in which Claude Code returns tool results.""" + """The tool results Claude Code returns in a "user" entry, or logs again with the API request that sent them.""" results: tuple[ToolResult, ...] @@ -94,6 +94,9 @@ def entry_from(found: dict) -> Entry: return user_entry(found, carried) case "cost-state": return cost_state(found, carried) + # Claude Code logs each API request's last message again, its tool results too, some held nowhere else, so their text counts here: {"type": "api-request-blob", "hash": "…", "message": {"role": "user", "content": [{"type": "tool_result", …}, {"type": "text", …}]}} + case "api-request-blob": + return ToolResults(**carried, results=results_in(found)) if (queued := queued_human_text(found)) is not None: return HumanTurn(**carried, text=queued) return Entry(**carried) @@ -117,7 +120,7 @@ def assistant_turn(found: dict, carried: Carried) -> AssistantTurn: def user_entry(found: dict, carried: Carried) -> UserText | ToolResults: - if results := tuple(result for block in blocks(found) if (result := tool_result(block))): + if results := results_in(found): return ToolResults(**carried, results=results) said = content(found) text = said if isinstance(said, str) else "".join(part_text(block) or "" for block in blocks(found)) @@ -127,6 +130,10 @@ def user_entry(found: dict, carried: Carried) -> UserText | ToolResults: return HumanTurn(**carried, text=text) if written_by_human(found) else InjectedText(**carried, text=text) +def results_in(found: dict) -> tuple[ToolResult, ...]: + return tuple(result for block in blocks(found) if (result := tool_result(block))) + + # {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...} def cost_state(found: dict, carried: Carried) -> CostState: by_model = found["modelUsage"] if isinstance(found.get("modelUsage"), dict) else {} diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index a8834bf9..f20a1c93 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -156,11 +156,29 @@ class EntryKinds(unittest.TestCase): self.assertEqual(entries.entry_from(cost_state), entries.CostState(costs={"claude-opus-5-5": 40.1, "claude-haiku-5-5": 1})) self.assertEqual(entries.entry_from({"type": "cost-state", "modelUsage": []}), entries.CostState(costs={})) + def test_the_api_request_claude_code_logs_yields_its_tool_results_and_none_of_its_text(self): + blob = {"type": "api-request-blob", "hash": "h", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "hi"}, {"type": "text", "text": "the request again"}]}} + self.assertEqual(entries.entry_from(blob), entries.ToolResults(results=(entries.ToolResult("toolu_1", "hi", False),))) + self.assertEqual(entries.entry_from({"type": "api-request-blob", "message": {"role": "user", "content": [{"type": "text", "text": "do it"}]}}), entries.ToolResults(results=())) + + def test_mixed_blocks_join_only_their_text(self): + self.assertEqual(entries.entry_from(human([{"type": "text", "text": "see "}, {"type": "image", "source": {}}, {"type": "text", "text": "this"}])), entries.InjectedText(text="see this")) + def test_every_kind_carries_where_and_when_it_was_written(self): - self.assertEqual( - entries.entry_from({"type": "summary", "uuid": "b", "parentUuid": "a", "timestamp": "2026-10-15T00:00:00.123Z", "cwd": "/r", "gitBranch": "item-1"}), - entries.Entry(uuid="b", parent_uuid="a", timestamp="2026-10-15T00:00:00.123Z", cwd="/r", git_branch="item-1"), - ) + where = {"uuid": "b", "parentUuid": "a", "timestamp": "2026-10-15T00:00:00.123Z", "cwd": "/r", "gitBranch": "item-1"} + carried = {"uuid": "b", "parent_uuid": "a", "timestamp": "2026-10-15T00:00:00.123Z", "cwd": "/r", "git_branch": "item-1"} + for found, kind in [ + ({"type": "summary"}, entries.Entry(**carried)), + (human("typed"), entries.HumanTurn(**carried, text="typed")), + (queued("typed while claude worked", "human"), entries.HumanTurn(**carried, text="typed while claude worked")), + ({**human("Continue."), "promptSource": "sdk"}, entries.LoopPrompt(**carried, text="Continue.")), + (human("/model"), entries.InjectedText(**carried, text="/model")), + (human([{"type": "tool_result", "tool_use_id": "toolu_1", "content": "hi"}]), entries.ToolResults(**carried, results=(entries.ToolResult("toolu_1", "hi", False),))), + (assistant(), entries.AssistantTurn(**carried)), + ({"type": "cost-state", "modelUsage": {}}, entries.CostState(**carried, costs={})), + ]: + with self.subTest(kind=type(kind).__name__): + self.assertEqual(entries.entry_from({**found, **where}), kind) self.assertEqual(entries.entry_from({"type": "summary", "uuid": 1, "parentUuid": None}), entries.Entry()) diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 60038c71..4f436df0 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -42,7 +42,7 @@ def entries_of(raw: bytes) -> list[Entry]: def commit_time(worker: list[Entry], home: str) -> str | None: - return next((turn.timestamp for turn, call in tool_calls(worker) if call.name == "Bash" and commits(simple_commands(str(call.input.get("command", "")), turn.cwd or "/", home), home)), None) + return next((turn.timestamp for turn, call in tool_calls(worker) if call.name == "Bash" and commits(simple_commands(str(call.input.get("command", "")), turn.cwd, home), home)), None) def tokens_in(turns: list[AssistantTurn]) -> int: diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index 6415f1bb..11a87f12 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -65,6 +65,15 @@ class Measure(unittest.TestCase): checkout = Checkout("/c/w", "/c/p", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"})) self.assertEqual(measure.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1}))) + def test_counts_only_reads_and_greps_by_their_path_and_a_command_without_a_cwd_from_the_root(self): + worker = [ + said("1", "m1", name="Edit", input={"file_path": "/c/p/a.py"}), + said("2", "m2", name="Glob", input={"path": "/c/p/a.py"}), + said("3", "m3", command="cat c/p/b.py", cwd=""), + said("4", "m4", command="git commit -m x"), + ] + self.assertEqual(measure.measure([jsonl(worker)], Checkout("/c/p", "/c/p", frozenset({"a.py", "b.py"})), "/h").files, collections.Counter({"b.py": 1})) + def test_counts_a_file_read_in_the_worktree_chunk_preflight_made_as_the_checkout_s(self): worker = [said("1", "m1", tokens=10, name="Read", input={"file_path": "/c/p-item-7/README.md"}), said("2", "m2", command="git commit -m x")] checkout = Checkout("/c/p-item-7", "/c/p", frozenset({"README.md"})) diff --git a/bin/routing_figures/chunk.py b/bin/routing_figures/chunk.py index bfb02c13..76fc6c85 100644 --- a/bin/routing_figures/chunk.py +++ b/bin/routing_figures/chunk.py @@ -171,5 +171,5 @@ def commit_titles(worker: list[Entry], home: str) -> list[str]: return list(dict.fromkeys( commit.messages[0].split("\n", 1)[0] for turn, call in tool_calls(worker) if call.name == "Bash" - for commit in commits(simple_commands(str(call.input.get("command", "")), turn.cwd or "/", home), home) if commit.messages + for commit in commits(simple_commands(str(call.input.get("command", "")), turn.cwd, home), home) if commit.messages )) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 4bab0f0f..2ba01338 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -305,7 +305,7 @@ class ReviewerRung(unittest.TestCase): def test_a_claude_loop_claude_did_not_start_is_not_checked(self): self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, {}), []) - def skill_refused(self, given: dict, environ: dict[str, str] = ENVIRON, subagent_prompt: str | None = None) -> list[Breach]: + def skill_refused(self, given: dict, environ: dict[str, str] = ENVIRON, subagent_prompt: str | list | None = None) -> list[Breach]: transcript = "" if subagent_prompt is not None: transcript = os.path.join(tempfile.mkdtemp(), "agent-a1.jsonl") @@ -327,7 +327,9 @@ class ReviewerRung(unittest.TestCase): self.assertEqual(rules(self.skill_refused({"skill": "security-review", "model": "opus", "effort": "medium"})), ["reviewer-rung"]) def test_a_security_skill_passes_only_in_a_subagent_launched_as_the_security_pass(self): - self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ENVIRON, "You are the security pass for this chunk. Invoke /security-review.")), []) + for prompt in ("You are the security pass for this chunk. Invoke /security-review.", "\n You are the security pass for this chunk.", [{"type": "text", "text": "You are the security pass for this chunk."}, {"type": "image", "source": {}}]): + with self.subTest(prompt=prompt): + self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ENVIRON, prompt)), []) self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ABOVE, "Invoke /security-review.")), ["reviewer-rung"], "a subagent's rung is unknown, whatever the worker's") unreadable = skill_breaches(Call("Skill", {"skill": "security-review"}, "/r", "general-purpose", "/nonexistent/agent-a1.jsonl", True), self.ENVIRON) self.assertEqual(rules(unreadable), ["reviewer-rung"])