Files
claude-config/bin/loop_claude/cycle/reading_cost.py
T

182 lines
6.9 KiB
Python

import collections
import dataclasses
import os
import pathlib
import posixpath
import re
import shlex
import time
from failure import Failure
from file_writes import make_private, replace_file
from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call
from loop_claude.cycle.archive import chunk_of
from loop_claude.paths import Paths
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
# Each reads the files it names; for these, the first operand is a pattern or a program unless -e or -f gives it.
READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"}
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
PLACES_KEPT = 10
HEADING = "## Reading cost, chunk "
TOKENS = re.compile(r"^(\d+) tokens read before the first commit\.$", re.MULTILINE)
@dataclasses.dataclass(frozen=True)
class Reading:
"""What the worker and its subagents took in before the worker's first commit."""
tokens: int
places: collections.Counter[str]
def record_reading(project_key: str, transcript: str, at: float, paths: Paths) -> Failure | None:
try:
raw = pathlib.Path(transcript).read_bytes()
subagents = [path.read_bytes() for path in sorted(pathlib.Path(transcript.removesuffix(".jsonl"), "subagents").glob("*.jsonl"))]
except OSError as failure:
return Failure(f"could not measure the reading cost: {failure.filename}: {failure.strerror}")
reading = measure(raw, subagents)
if reading is None:
return None
return keep_reading(pending_file(project_key, paths), entry(chunk_of(raw)[:12], time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)), reading))
def pending_file(project_key: str, paths: Paths) -> pathlib.Path:
return paths.transcript_archive / project_key / "reading-cost.md"
def measure(transcript: bytes, subagents: list[bytes]) -> Reading | None:
worker = entries_of(transcript)
commit = next((entry.get("timestamp", "") for entry in worker if any(commits(part) for part in assistant_parts(entry))), None)
if commit is None:
return None
tokens = 0
places: collections.Counter[str] = collections.Counter()
for thread in (worker, *map(entries_of, subagents)):
# Claude Code writes one entry per content block of a message, each with the message's usage.
counted: set[str] = set()
for entry in thread:
if entry.get("type") != "assistant" or entry.get("timestamp", "") >= commit:
continue
message = entry.get("message") or {}
if (key := str(message.get("id") or entry.get("uuid"))) not in counted:
counted.add(key)
usage = message.get("usage") or {}
tokens += int(usage.get("input_tokens") or 0) + int(usage.get("cache_creation_input_tokens") or 0)
for part in assistant_parts(entry):
places.update(read_paths(part, entry.get("cwd") or ""))
return Reading(tokens, places)
def entries_of(raw: bytes) -> list[dict]:
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
def arguments_of(part: object) -> tuple[object, dict]:
call = tool_call(part)
return (call[0], call[1]) if call and isinstance(call[1], dict) else (None, {})
def commits(part: object) -> bool:
name, arguments = arguments_of(part)
return name == "Bash" and bool(COMMIT.search(str(arguments.get("command", ""))))
def read_paths(part: object, cwd: str) -> list[str]:
name, arguments = arguments_of(part)
if name == "Read":
return place(str(arguments.get("file_path", "")), cwd, cwd)
if name == "Grep" and arguments.get("path"):
return place(str(arguments["path"]), cwd, cwd)
if name == "Bash":
return bash_reads(str(arguments.get("command", "")), cwd)
return []
def bash_reads(command: str, cwd: str) -> list[str]:
found = []
base = cwd
lines = iter(command.splitlines())
for line in lines:
try:
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
tokens = list(lexer)
except ValueError:
continue
for words in segments(tokens):
if words[0] == "cd" and len(words) == 2:
base = posixpath.normpath(posixpath.join(base, os.path.expanduser(words[1])))
found += [kept for path in operands(words) for kept in place(path, base, cwd)]
if "<<" in tokens or "<<-" in tokens:
marker = tokens[tokens.index("<<" if "<<" in tokens else "<<-") + 1:][:1]
for body in lines:
if marker and body.strip() == marker[0]:
break
return found
def segments(tokens: list[str]) -> list[list[str]]:
found: list[list[str]] = [[]]
skip = False
for token in tokens:
if skip:
skip = False
elif token and all(char in "();<>|&" for char in token):
# A redirect's target is written or fed, not read by the command.
skip = "<" in token or ">" in token
found.append([])
else:
found[-1].append(token)
return [words for words in found if words]
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)):
return []
given = [word for word in words[1:] if not word.startswith("-")]
if program in PATTERN_FIRST and not any(word in ("-e", "-f") for word in words):
given = given[1:]
return [word for word in given if ("/" in word or re.search(r"\.[A-Za-z0-9]+$", word)) and not NOT_A_PATH.search(word)]
# Relative to the folder it was read in, a worktree or the checkout, so both name a file alike; a file outside both is no place of the project.
def place(path: str, base: str, cwd: str) -> list[str]:
full = posixpath.normpath(posixpath.join(base, os.path.expanduser(path)))
roots = [root.rstrip("/") + "/" for root in (base, cwd) if root]
return next(([full.removeprefix(root)] for root in roots if full.startswith(root)), [])
def entry(chunk: str, finished: str, reading: Reading) -> str:
places = "".join(f"- `{path}` {count}\n" for path, count in sorted(reading.places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT])
return f"{HEADING}{chunk}, finished {finished}\n\n{reading.tokens} tokens read before the first commit.\n" + (f"\nRead most:\n\n{places}" if places else "")
def keep_reading(pending: pathlib.Path, block: str) -> Failure | None:
try:
make_private(pending.parent)
kept = pending.read_text(encoding="utf-8") if pending.exists() else ""
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not keep the reading cost in {pending}: {failure}")
if block.splitlines()[0] in kept.splitlines():
return None
if unwritten := replace_file(pending, (kept + ("\n" if kept else "") + block).encode()):
return Failure(f"could not keep the reading cost in {pending}: {unwritten.reason}")
return None
def blocks(text: str) -> list[str]:
"""The reading-cost entries of a markdown file, in order, each from its heading to the next heading."""
found = []
for section in re.split(r"(?m)^(?=## )", text):
if section.startswith(HEADING):
found.append(section.rstrip("\n") + "\n")
return found
def tokens_of(block: str) -> int:
match = TOKENS.search(block)
return int(match.group(1)) if match else 0