Files
claude-config/bin/reading_cost.py
T

281 lines
12 KiB
Python

#!/usr/bin/env python3
"""Measure each chunk loop-claude finished, append the figures to a project's history, and say whether they rise.
usage: reading_cost.py [--reset] [history]
Run it inside a project checkout or one of its worktrees. history defaults to
docs/comprehension-history.md there, created when missing. It reads loop-claude's archive of the
project, $LOOP_CLAUDE_TRANSCRIPTS/<key> (default ~/.claude/loop-claude-transcripts), <key> being
the checkout's path relative to ~/code, or to / outside it. For each chunk the judge ruled
finished, under a UTC time, that history does not hold, it measures what the worker and its subagents read before
the worker's first commit: the tokens they took in, and how often they opened or searched each
file git tracks in the checkout. A chunk whose worker never committed is not measured. Each
figure is appended under a "## Reading cost, chunk <id>, finished <UTC time>" heading, in the
order the chunks finished.
--reset also appends a "## Reading cost reset, <UTC time>" heading: the trend then counts only
figures of chunks that finished after it.
It then compares the median tokens of the history's last 5 figures with the 5 before them, in
the order their chunks finished, and prints "Rising:" or "Not rising:" with both medians. Rising, it
lists the files the last 5 chunks read most. With fewer than 10 figures, it says so.
Exit 1, saying why, when git cannot start or finds no checkout, the archive or the history cannot
be read or written, or a figure in the history cannot be read back.
"""
import collections
import dataclasses
import os
import pathlib
import re
import statistics
import subprocess
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call
from failure import Failure
from loop_claude.transcript_archive import finished_chunks, FinishedChunk, utc
from loop_claude.paths import paths_from
from loop_claude.project.checkout import project_key
from shell_reads import Reads, resolved, shell_reads
from file_writes import replace_file
from markdown_sections import sections
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
HEADING = "Reading cost, chunk "
PLACE = re.compile(r"^- `(.+)` (\d+)$")
PLACES_KEPT = 10
RESET = "Reading cost reset, "
TOKENS = re.compile(r"^(\d+) tokens read before the first commit\.$")
WINDOW = 5
@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]
@dataclasses.dataclass(frozen=True)
class Checkout:
root: str
top: str
tracked: frozenset[str]
def main(argv: list[str]) -> int:
reset = argv[:1] == ["--reset"]
given = argv[1:] if reset else argv
if given[:1] in (["-h"], ["--help"]) or len(given) > 1 or given[:1] and given[0].startswith("-"):
helped = given[:1] in (["-h"], ["--help"]) and len(given) == 1
print(__doc__.strip(), file=sys.stdout if helped else sys.stderr)
return 0 if helped else 1
checkout = located()
if isinstance(checkout, Failure):
return failed(checkout)
home = pathlib.Path.home()
paths = paths_from(home, os.environ)
archive = paths.transcript_archive / project_key(checkout.root, paths.code)
history = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "comprehension-history.md")
updated = update(history, archive, checkout, str(home), utc(time.time()) if reset else None)
if isinstance(updated, Failure):
return failed(updated)
appended, readings = updated
print(f"Appended {appended} reading-cost figures from {archive}{' and a reset' if reset else ''} to {history}.")
print(trend(readings))
return 0
def update(history: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> tuple[int, list[Reading]] | Failure:
"""How many figures it appended, and the readings the trend counts."""
text = read_history(history)
if isinstance(text, Failure):
return text
figures = new_figures(text, archive, checkout, home)
if isinstance(figures, Failure):
return figures
marks = [*figures, f"## {RESET}{reset_at}\n"] if reset_at else figures
text = merged(text, marks) if marks else text
readings = readings_of(text)
if isinstance(readings, Failure):
return readings
if marks and (unwritten := write_history(history, text)):
return unwritten
return len(figures), readings
def new_figures(history: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure:
chunks = finished_chunks(archive)
if isinstance(chunks, Failure):
return chunks
figures = []
for chunk in unheld(chunks, history):
threads = read_threads(chunk)
if isinstance(threads, Failure):
return threads
if reading := measure(threads, checkout, home):
figures.append(figure(chunk, reading))
return figures
def write_history(history: pathlib.Path, text: str) -> Failure | None:
try:
history.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"could not write {history}: {failure.strerror}")
unwritten = replace_file(history, text.encode())
return Failure(f"could not write {history}: {unwritten.reason}") if unwritten else None
def failed(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
def located() -> Checkout | Failure:
try:
found = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], capture_output=True, text=True)
if found.returncode != 0:
return Failure(found.stderr.strip())
top, common = found.stdout.splitlines()
listed = subprocess.run(["git", "ls-files", "-z"], capture_output=True, cwd=top, text=True)
except (OSError, ValueError) as failure:
return Failure(f"could not find the checkout: {failure}")
if listed.returncode != 0:
return Failure(listed.stderr.strip())
# The common dir is the checkout's .git, whichever worktree runs this.
return Checkout(str(pathlib.Path(common).parent), top, frozenset(filter(None, listed.stdout.split("\0"))))
def read_history(history: pathlib.Path) -> str | Failure:
try:
return history.read_text(encoding="utf-8") if history.exists() else "# Comprehension history\n"
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure:
"""The worker's transcript, then each subagent's."""
try:
return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)]
except OSError as failure:
return Failure(f"could not read {failure.filename}: {failure.strerror}")
def unheld(chunks: list[FinishedChunk], history: str) -> list[FinishedChunk]:
held = {heading.removeprefix(HEADING).split(",")[0] for heading in sections(history) if heading.startswith(HEADING)}
return [chunk for chunk in chunks if chunk_id(chunk) not in held]
def chunk_id(chunk: FinishedChunk) -> str:
return chunk.folder[:12]
def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None:
worker, *subagents = [entries_of(thread) for thread in threads]
commit = commit_time(worker)
if commit is None:
return None
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
roots = [checkout.root, *(added for found in reads for added in found.added)]
places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), places)
def entries_of(raw: bytes) -> list[dict]:
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
def commit_time(worker: list[dict]) -> str | None:
for entry in worker:
for part in assistant_parts(entry):
name, arguments = call_of(part)
if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))):
return str(entry.get("timestamp", ""))
return None
def tokens_in(entries: list[dict]) -> int:
# Claude Code writes one entry per content block of a message, each with the message's usage.
usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)}
return sum(count(usage, "input_tokens") + count(usage, "cache_creation_input_tokens") for usage in usages.values() if isinstance(usage, dict))
# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of the figure standing.
def count(usage: dict, field: str) -> int:
value = usage.get(field)
return value if isinstance(value, int) else 0
def call_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 reads_of(part: object, cwd: str, home: str) -> Reads:
name, arguments = call_of(part)
path = arguments.get("file_path") if name == "Read" else arguments.get("path") if name == "Grep" else None
if path:
return Reads([resolved(cwd, str(path), home)], [])
return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], [])
# 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
def figure(chunk: FinishedChunk, reading: Reading) -> str:
places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places))
return f"## {HEADING}{chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} tokens read before the first commit.\n" + (f"\nRead most:\n\n{places}" if places else "")
# The figures after the last reset, in the order their chunks finished: each machine appends its own archive's chunks.
def readings_of(history: str) -> list[Reading] | Failure:
dated = []
resets = [""]
for heading, bodies in sections(history).items():
if heading.startswith(RESET):
resets.append(heading.removeprefix(RESET))
elif heading.startswith(HEADING):
lines = bodies[0].splitlines() if bodies else []
tokens = [int(match.group(1)) for line in lines if (match := TOKENS.match(line))]
if len(tokens) != 1:
return Failure(f"the figure under \"## {heading}\" holds no single tokens line; restore it from git history")
dated.append((heading.rsplit(", finished ", 1)[-1], Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := PLACE.match(line))}))))
return [reading for finished, reading in sorted(dated, key=lambda item: item[0]) if finished > max(resets)]
def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]:
return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT]
def merged(history: str, figures: list[str]) -> str:
return history.rstrip("\n") + "\n\n" + "\n".join(figures)
# Medians, so one chunk that ran a panel of readers or waited out a usage limit does not decide the trend alone.
def trend(readings: list[Reading]) -> str:
if len(readings) < 2 * WINDOW:
return f"{len(readings)} chunks measured; the trend needs {2 * WINDOW}."
last, earlier = middle(readings[-WINDOW:]), middle(readings[-2 * WINDOW:-WINDOW])
medians = f"the last {WINDOW} chunks' median is {last} tokens read before their first commit, the {WINDOW} before them {earlier}."
if last <= earlier:
return f"Not rising: {medians}"
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter())))
return f"Rising: {medians}\n\nRead most over the last {WINDOW}:\n{read_most}"
def middle(readings: list[Reading]) -> int:
return round(statistics.median(reading.tokens for reading in readings))
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))