Measure each chunk's reading cost from its transcript and keep it in the comprehension history
This commit is contained in:
Executable
+90
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move loop-claude's reading-cost figures into a project's history, and say whether they rise.
|
||||
|
||||
usage: reading_cost.py [history]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. history defaults to
|
||||
docs/comprehension-history.md there, created when missing. When loop-claude finishes a chunk, it
|
||||
measures what the worker and its subagents read before the worker's first commit: the tokens they
|
||||
took in, and the project's files they opened or searched, with how often. It keeps each figure in
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<key>/reading-cost.md (default ~/.claude/loop-claude-transcripts), <key>
|
||||
being the checkout's path relative to ~/code, or to / outside it. This appends to history each
|
||||
figure it does not yet hold, under a "## Reading cost, chunk <id>, finished <UTC time>" heading.
|
||||
|
||||
It then compares the mean tokens of the history's last 5 figures with the 5 before them, 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.
|
||||
|
||||
Exit 1, saying why, when git finds no checkout, or the figures or the history cannot be read or
|
||||
written.
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_claude.cycle.reading_cost import blocks, pending_file, PLACES_KEPT, tokens_of
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude.project.checkout import project_key
|
||||
from file_writes import replace_file
|
||||
|
||||
WINDOW = 5
|
||||
PLACE = re.compile(r"^- `(.+)` (\d+)$", re.MULTILINE)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]) or len(argv) > 1:
|
||||
print(__doc__.strip(), file=sys.stdout if argv[:1] in (["-h"], ["--help"]) else sys.stderr)
|
||||
return 0 if argv[:1] in (["-h"], ["--help"]) else 1
|
||||
found = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], capture_output=True, text=True)
|
||||
if found.returncode != 0:
|
||||
print(found.stderr.strip(), file=sys.stderr)
|
||||
return 1
|
||||
top, common = found.stdout.splitlines()
|
||||
paths = paths_from(pathlib.Path.home(), os.environ)
|
||||
# The common dir is the checkout's .git, whichever worktree runs this.
|
||||
pending = pending_file(project_key(str(pathlib.Path(common).parent), paths.code), paths)
|
||||
history = pathlib.Path(argv[0]) if argv else pathlib.Path(top, "docs", "comprehension-history.md")
|
||||
try:
|
||||
figures = blocks(pending.read_text(encoding="utf-8")) if pending.exists() else []
|
||||
text = history.read_text(encoding="utf-8") if history.exists() else "# Comprehension history\n"
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
print(f"could not read the reading cost: {failure}", file=sys.stderr)
|
||||
return 1
|
||||
held = set(text.splitlines())
|
||||
new = [block for block in figures if block.splitlines()[0] not in held]
|
||||
if new:
|
||||
text = text.rstrip("\n") + "\n\n" + "\n".join(new)
|
||||
history.parent.mkdir(parents=True, exist_ok=True)
|
||||
if unwritten := replace_file(history, text.encode()):
|
||||
print(f"could not write {history}: {unwritten.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"Appended {len(new)} reading-cost figures to {history}.")
|
||||
print(trend(blocks(text)))
|
||||
return 0
|
||||
|
||||
|
||||
def trend(figures: list[str]) -> str:
|
||||
if len(figures) < 2 * WINDOW:
|
||||
return f"{len(figures)} chunks measured; the trend needs {2 * WINDOW}."
|
||||
last, before = figures[-WINDOW:], figures[-2 * WINDOW:-WINDOW]
|
||||
means = f"the last {WINDOW} chunks read {mean(last)} tokens on average before their first commit, the {WINDOW} before them {mean(before)}."
|
||||
if mean(last) <= mean(before):
|
||||
return f"Not rising: {means}"
|
||||
places: collections.Counter[str] = collections.Counter()
|
||||
for block in last:
|
||||
places.update({path: int(count) for path, count in PLACE.findall(block)})
|
||||
read_most = "".join(f"\n- `{path}` {count}" for path, count in sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT])
|
||||
return f"Rising: {means}\n\nRead most over the last {WINDOW}:\n{read_most}"
|
||||
|
||||
|
||||
def mean(figures: list[str]) -> int:
|
||||
return round(sum(map(tokens_of, figures)) / len(figures))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user