Answer architecture round 2: split reading_cost's main, reset the trend when the reading-cost item ships, order figures by finish time, share the archive's stamp format

This commit is contained in:
2026-10-08 16:31:37 +02:00
parent 471350d388
commit aa062da0bd
8 changed files with 82 additions and 38 deletions
+56 -28
View File
@@ -1,7 +1,7 @@
#!/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 [history]
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
@@ -13,7 +13,11 @@ file git tracks in the checkout. A chunk whose worker never committed is not mea
figure is appended under a "## Reading cost, chunk <id>, finished <UTC time>" heading, in the
order the chunks finished.
It then compares the mean tokens of the history's last 5 figures with the 5 before them, and prints
--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 mean 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 means. Rising, it lists the files the last 5 chunks read most.
With fewer than 10 figures, it says so.
@@ -27,12 +31,13 @@ import pathlib
import re
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
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
@@ -43,6 +48,7 @@ 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
@@ -62,42 +68,59 @@ class Checkout:
def main(argv: list[str]) -> int:
helped = argv[:1] in (["-h"], ["--help"])
if helped or len(argv) > 1:
reset = argv[:1] == ["--reset"]
given = argv[1:] if reset else argv
helped = given[:1] in (["-h"], ["--help"])
if helped or len(given) > 1:
print(__doc__.strip(), file=sys.stdout if helped else sys.stderr)
return 0 if helped else 1
home = pathlib.Path.home()
paths = paths_from(home, os.environ)
checkout = located()
if isinstance(checkout, Failure):
return failed(checkout)
history = pathlib.Path(argv[0]) if argv else pathlib.Path(checkout.top, "docs", "comprehension-history.md")
history = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "comprehension-history.md")
text = read_history(history)
chunks = finished_chunks(paths.transcript_archive / project_key(checkout.root, paths.code))
if isinstance(text, Failure):
return failed(text)
if isinstance(chunks, Failure):
return failed(chunks)
figures = []
for chunk in unheld(chunks, text):
threads = read_threads(chunk)
if isinstance(threads, Failure):
return failed(threads)
if reading := measure(threads, checkout, str(home)):
figures.append(figure(chunk, reading))
if figures:
text = merged(text, figures)
history.parent.mkdir(parents=True, exist_ok=True)
if unwritten := replace_file(history, text.encode()):
return failed(Failure(f"could not write {history}: {unwritten.reason}"))
figures = new_figures(text, checkout, home)
if isinstance(figures, Failure):
return failed(figures)
marks = [*figures, f"## {RESET}{utc(time.time())}\n"] if reset else figures
text = merged(text, marks) if marks else text
readings = readings_of(text)
if isinstance(readings, Failure):
return failed(readings)
print(f"Appended {len(figures)} reading-cost figures to {history}.")
if marks and (unwritten := write_history(history, text)):
return failed(unwritten)
print(f"Appended {len(figures)} reading-cost figures{' and a reset' if reset else ''} to {history}.")
print(trend(readings))
return 0
def new_figures(history: str, checkout: Checkout, home: pathlib.Path) -> list[str] | Failure:
paths = paths_from(home, os.environ)
chunks = finished_chunks(paths.transcript_archive / project_key(checkout.root, paths.code))
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, str(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
@@ -173,6 +196,7 @@ def tokens_in(entries: list[dict]) -> int:
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
@@ -202,16 +226,20 @@ def figure(chunk: FinishedChunk, reading: Reading) -> str:
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:
readings = []
dated = []
resets = [""]
for heading, bodies in sections(history).items():
if heading.startswith(HEADING):
lines = bodies[0].splitlines()
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")
readings.append(Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := PLACE.match(line))})))
return readings
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]]: