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:
@@ -14,6 +14,7 @@ from loop_claude.claude_code.session import session_files
|
||||
|
||||
FINISHED = "Verdict: finished"
|
||||
UNFINISHED = "Verdict: unfinished"
|
||||
STAMP = "%Y-%m-%dT%H:%M:%SZ"
|
||||
FINISHED_AT = re.compile(rf"^(\d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\dZ) {re.escape(FINISHED)}$", re.MULTILINE)
|
||||
|
||||
|
||||
@@ -102,7 +103,7 @@ def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None:
|
||||
|
||||
|
||||
def utc(at: float) -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at))
|
||||
return time.strftime(STAMP, time.gmtime(at))
|
||||
|
||||
|
||||
# One per chunk folder, its latest finished copy, in the order they finished.
|
||||
|
||||
+56
-28
@@ -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]]:
|
||||
|
||||
+2
-3
@@ -5,7 +5,6 @@ import re
|
||||
import shlex
|
||||
import typing
|
||||
|
||||
HEREDOC = {"<<", "<<-"}
|
||||
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
|
||||
# Their first operand is a pattern or a program, unless -e or -f gives it.
|
||||
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
|
||||
@@ -45,8 +44,8 @@ def shell_lines(command: str) -> typing.Iterator[list[str]]:
|
||||
tokens = list(lexer)
|
||||
except ValueError:
|
||||
continue
|
||||
marker = next((tokens[index + 1] for index, token in enumerate(tokens[:-1]) if token in HEREDOC), None)
|
||||
ends = marker
|
||||
# The lexer splits <<-EOF into << and -EOF.
|
||||
ends = next((tokens[index + 1].removeprefix("-") for index, token in enumerate(tokens[:-1]) if token == "<<"), None)
|
||||
yield tokens
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_claude.transcript_archive import archive, FINISHED, finished_chunks, FinishedChunk, UNFINISHED
|
||||
from loop_claude.transcript_archive import archive, FINISHED, FINISHED_AT, finished_chunks, FinishedChunk, UNFINISHED, utc
|
||||
from reading_cost import Checkout, Reading
|
||||
from failure import Failure
|
||||
from test_loop_claude_black_box import host_env
|
||||
@@ -41,6 +41,9 @@ class ShellReads(unittest.TestCase):
|
||||
command = "cd ../w && sed -n 1,5p src/a.py | grep -n x\ngrep -rn 'def x' bin/t.py > out.txt\npython3 - <<'EOF'\ncat secret.py\nEOF\ncat ~/README.md\nsed -i s/a/b/ c.py"
|
||||
self.assertEqual(shell_reads(command, "/c/p", "/h"), Reads(["/c/w/src/a.py", "/c/w/bin/t.py", "/h/README.md"], []))
|
||||
|
||||
def test_ends_a_dashed_heredoc_at_its_marker(self):
|
||||
self.assertEqual(shell_reads("cat <<-EOF > x.md\ncat secret.py\nEOF\ncat a.py", "/c/p", "/h"), Reads(["/c/p/a.py"], []))
|
||||
|
||||
def test_names_the_worktree_a_git_worktree_add_makes(self):
|
||||
self.assertEqual(shell_reads("git worktree add -q -b topic ../p-topic origin/main", "/c/p", "/h"), Reads([], ["/c/p-topic"]))
|
||||
|
||||
@@ -81,6 +84,16 @@ class Figures(unittest.TestCase):
|
||||
self.assertEqual(reading_cost.readings_of(written.replace("7 tokens", "seven tokens")), Failure('the figure under "## Reading cost, chunk abcdef012345, finished t" holds no single tokens line; restore it from git history'))
|
||||
|
||||
|
||||
def test_counts_only_figures_finished_after_the_last_reset_in_the_order_they_finished(self):
|
||||
def written(chunk, finished, tokens):
|
||||
return reading_cost.figure(FinishedChunk(chunk, finished, pathlib.Path(), []), Reading(tokens, collections.Counter()))
|
||||
history = "\n".join([written("a", "2026-10-01T00:00:00Z", 1), written("c", "2026-10-03T00:00:00Z", 3), "## Reading cost reset, 2026-10-02T00:00:00Z\n", written("b", "2026-10-04T00:00:00Z", 2)])
|
||||
self.assertEqual(reading_cost.readings_of(history), [Reading(3, collections.Counter()), Reading(2, collections.Counter())])
|
||||
|
||||
def test_the_archive_stamps_what_it_reads_back(self):
|
||||
self.assertRegex(f"{utc(1790000000)} {FINISHED}", FINISHED_AT)
|
||||
|
||||
|
||||
class ReadingCostTool(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
@@ -126,6 +139,9 @@ class ReadingCostTool(unittest.TestCase):
|
||||
self.assertEqual(history.read_text(), "# Comprehension history\n\n" + "\n".join(figure.format(chunk.folder[:12], chunk.finished) for chunk in chunks))
|
||||
self.assertTrue(self.run_tool(worktree).stdout.startswith(f"Appended 0 reading-cost figures to {history}."))
|
||||
self.assertEqual(history.read_text().count("## Reading cost"), 2)
|
||||
reset = subprocess.run([sys.executable, str(TOOL), "--reset"], capture_output=True, cwd=worktree, env=self.env, text=True)
|
||||
self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures and a reset to {history}.\n0 chunks measured; the trend needs 10.\n")
|
||||
self.assertRegex(history.read_text(), r"\n## Reading cost reset, \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ\n$")
|
||||
|
||||
def test_exits_1_outside_a_checkout(self):
|
||||
ran = self.run_tool(self.home)
|
||||
|
||||
Reference in New Issue
Block a user