Files
claude-config/bin/reading_cost/measure.py
T

71 lines
3.4 KiB
Python

import collections
import dataclasses
import re
from claude_code.entries import AssistantTurn, Entry, messages, parse_entry, tool_calls, ToolCall, usage_count
from git_cli.git_command import commits
from reading_cost.shell_reads import Reads, shell_reads
from command_lines.shell_command import resolved, simple_commands
from project_config import templates
@dataclasses.dataclass(frozen=True)
class Reading:
"""What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout."""
tokens: int
files: collections.Counter[str]
@dataclasses.dataclass(frozen=True)
class Checkout:
"""main_root is the main checkout, whose path keys the archive; current_root is the checkout or worktree this runs in."""
current_root: str
main_root: str
tracked: frozenset[str]
# The project's `branch` template, which names each item's worktree.
branch: str
def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None:
worker, *subagents = [entries_of(thread) for thread in threads]
commit = commit_time(worker, home)
if commit is None:
return None
before = [[entry for entry in thread if isinstance(entry, AssistantTurn) and entry.timestamp < commit] for thread in (worker, *subagents)]
reads = [reads_of(call, turn.cwd or "/", home) for thread in before for turn, call in tool_calls(thread)]
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
files = collections.Counter(file for found in reads for path in found.read if (file := relative(in_main_checkout(path, checkout), roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), files)
def entries_of(raw: bytes) -> list[Entry]:
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
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, home), home)), None)
def tokens_in(turns: list[AssistantTurn]) -> int:
return sum(usage_count(first.usage, "input_tokens") + usage_count(first.usage, "cache_creation_input_tokens") for first, *_ in messages(turns))
def reads_of(call: ToolCall, cwd: str, home: str) -> Reads:
path = call.input.get("file_path") if call.name == "Read" else call.input.get("path") if call.name == "Grep" else None
if path:
return Reads([resolved(cwd, str(path), home)], [])
return shell_reads(str(call.input.get("command", "")), cwd, home) if call.name == "Bash" else Reads([], [])
# chunk-preflight adds each item's worktree beside the checkout as <checkout>-<branch>, each / of the branch a dash, which no transcript command names.
def in_main_checkout(path: str, checkout: Checkout) -> str:
main_root = checkout.main_root.rstrip("/")
worktree = re.escape(f"{main_root}-{checkout.branch.replace('/', '-')}").replace(re.escape(templates.ID), r"\d+")
return re.sub(f"^{worktree}(?=/)", lambda _: main_root, path, count=1)
# Relative to the deepest root holding it, so the checkout and each worktree name a file alike.
def relative(path: str, roots: list[str]) -> str | None:
holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")]
return path[len(max(holding, key=len).rstrip("/")) + 1:] if holding else None