"""Measure each chunk loop-claude finished, append the figures to a project's record, and say whether they rise. usage: reading-cost [--reset] [record] Run it inside a project checkout or one of its worktrees. record defaults to docs/reading-cost.md there, created when missing. It reads loop-claude's archive of the project, $LOOP_CLAUDE_TRANSCRIPTS/ (default ~/.claude/loop-claude-transcripts), being the checkout's path relative to ~/code, or to / outside it. For each finished chunk the record does not yet hold, it measures what the worker and its subagents read before the worker's first commit: their new input tokens (uncached and cache-written; cache reads excluded), 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 , finished " heading, in the order the chunks finished. --reset also appends a "## Reading cost reset, " heading: the trend then counts only figures of chunks that finished after it. It then compares the median tokens of the record'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, on unknown arguments, or when git cannot start or finds no checkout, the archive or the record cannot be read or written, or a figure in the record cannot be read back. """ import dataclasses import os import pathlib import subprocess import sys import time from reading_cost.measure import Checkout, measure, Reading from failure import Failure from reading_cost.figures import figure, merged, readings_of, RECORD, RESET, trend, unheld from transcript_archive.read import finished_chunks, read_threads from transcript_archive.location import project_archive from file_writes import replace_file from utc_stamp import utc @dataclasses.dataclass(frozen=True) class Updated: appended: int readings: list[Reading] def main(argv: list[str]) -> int: reset = argv[:1] == ["--reset"] given = argv[1:] if reset else argv if given in (["-h"], ["--help"]): print(__doc__.strip()) return 0 if len(given) > 1 or given[:1] and given[0].startswith("-"): print(f"unknown arguments {' '.join(given)}; usage: reading-cost [--reset] [record]", file=sys.stderr) return 1 checkout = located() if isinstance(checkout, Failure): return failed(checkout) home = pathlib.Path.home() archive = project_archive(checkout.main_root, home, os.environ) record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.current_root, RECORD) updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None) if isinstance(updated, Failure): return failed(updated) print(f"Appended {updated.appended} reading-cost figure{'' if updated.appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record}.") print(trend(updated.readings)) return 0 def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure: text = read_record(record) 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_record(record, text)): return unwritten return Updated(len(figures), readings) def new_figures(record: 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, record): 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_record(record: pathlib.Path, text: str) -> Failure | None: try: record.parent.mkdir(parents=True, exist_ok=True) except OSError as failure: return Failure(f"could not write {record}: {failure.strerror}") unwritten = replace_file(record, text.encode()) return Failure(f"could not write {record}: {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 main checkout's .git, whichever worktree runs this. return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.stdout.split("\0")))) def read_record(record: pathlib.Path) -> str | Failure: try: return record.read_text(encoding="utf-8") if record.exists() else "# Reading cost\n" except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {record}: {failure}")