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:
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- larv-review runs the new `bin/reading_cost.py`, which measures each chunk `loop-claude` finished from its archive: the tokens the worker and its subagents took in before the worker's first commit, and the files git tracks that they read most. It appends each figure the project's `docs/comprehension-history.md` lacks. When the last 5 chunks' mean is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it; only its own chunk or you remove it.
|
||||
- larv-review runs the new `bin/reading_cost.py`, which measures each chunk `loop-claude` finished from its archive: the tokens the worker and its subagents took in before the worker's first commit, and the files git tracks that they read most. It appends each figure the project's `docs/comprehension-history.md` lacks. When the last 5 chunks' mean is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it; only its own chunk or you remove it. The chunk that ships it runs `reading_cost.py --reset`, so the trend counts only chunks that finished after it.
|
||||
- larv-review appends every scoring run to the project's `docs/comprehension-history.md`: the commit the seats read, each seat's five scores and the seats' mean, and the places each seat named. The ratchet compares a run with the history's last run on the default branch. The `comprehension floor:` entry in `docs/decisions.md` keeps only the decisions to ship under the floor; a project's next scoring run moves the last scores the entry still holds into the history. The seats do not read the history.
|
||||
- The README's goals put quality with the fewest interrupts first, as goal 1; sharing the setup, backups and leaking nothing follow as goals 2–4.
|
||||
- larv-review reruns the comprehension scoring run before merge when any commit since the last run changes more than `docs/decisions.md`, `docs/comprehension-history.md`, `todo.md` or `CHANGELOG.md`, so the recorded scores are the merged commit's. A score under the floor, or below the default branch's recorded scores, blocks the merge and is never filed in `todo.md`. A fix lifts either; your decision to ship under the floor lifts only a score under the floor. A rerun counts toward the three-round cap only when it reports a blocking score that no decision of yours covers.
|
||||
|
||||
@@ -67,7 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
|
||||
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading_cost.py [history]` measures the chunks `loop-claude` finished into a project's comprehension history and says whether the figures rise; `reading_cost.py --help` states the measure.
|
||||
- `reading_cost.py [--reset] [history]` measures the chunks `loop-claude` finished into a project's comprehension history and says whether the figures rise; `reading_cost.py --help` states the measure.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`
|
||||
|
||||
@@ -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)
|
||||
|
||||
+1
-1
@@ -116,4 +116,4 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
|
||||
|
||||
## reading cost: a rise is the last 5 chunks' mean above the 5 before them, and files or refreshes one plan item that only its own chunk or the human removes
|
||||
|
||||
2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy, so a flat trend rises about every other chunk; the item is refreshed, never refiled, and a chunk that sees no rise leaves it, so the plan does not churn with the noise (goal 1.4). No published standard sets this threshold. Valid while figures arrive once per chunk.
|
||||
2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy, so a flat trend rises about every other chunk; the item is refreshed, never refiled, a chunk that sees no rise leaves it, and the chunk that ships it resets the trend, so the plan neither churns with the noise nor refiles the item on figures that chunk already answered (goal 1.4). No published standard sets this threshold. Valid while figures arrive once per chunk.
|
||||
|
||||
@@ -24,7 +24,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claud
|
||||
|
||||
Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary.
|
||||
|
||||
**Reading cost.** Run `~/.claude/bin/reading_cost.py` in the chunk's worktree and commit what it appends to `docs/comprehension-history.md`; the commit re-enters no pass. On `Rising:`, file a plan item titled `**Lower the reading cost of the files chunks read most before their first commit.**` under the next release, with no Exempt reason and the tool's means and files as its detail; where the plan already holds it, refresh its detail instead. Leave the plan as it is on any other output.
|
||||
**Reading cost.** Run `~/.claude/bin/reading_cost.py` in the chunk's worktree and commit what it appends to `docs/comprehension-history.md`; the commit re-enters no pass. On `Rising:`, file a plan item titled `**Lower the reading cost of the files chunks read most before their first commit.**` under the next release, with no Exempt reason and the tool's means and files as its detail; where the plan already holds it, refresh its detail instead. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it.
|
||||
|
||||
## 3. Passes
|
||||
|
||||
@@ -89,7 +89,7 @@ Then the comprehension floor, which the scoring run measures. Four simulated rea
|
||||
|
||||
Two files of the project keep the floor's records:
|
||||
|
||||
- **History.** `docs/comprehension-history.md` keeps every scoring run, appended and never edited. A run is a `## <UTC time, ISO 8601>, <PR or branch> at <commit>` heading naming when the seats finished and the commit they read; a table of each seat's five scores, with a last row holding the four seats' mean of each; and under each seat, labelled `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`, its places, each as `path:line` and the unit's name. A `## Reading cost` heading opens a reading-cost figure (§2), not a run. Appending a run re-enters no pass. Resolve a merge conflict in the file by putting the default branch's runs and figures first, and dropping a figure for a chunk the default branch already holds.
|
||||
- **History.** `docs/comprehension-history.md` keeps every scoring run, appended and never edited. A run is a `## <UTC time, ISO 8601>, <PR or branch> at <commit>` heading naming when the seats finished and the commit they read; a table of each seat's five scores, with a last row holding the four seats' mean of each; and under each seat, labelled `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`, its places, each as `path:line` and the unit's name. A `## Reading cost` heading opens a reading-cost figure or reset (§2), not a run. Appending a run re-enters no pass. Resolve a merge conflict in the file by putting the default branch's runs and figures first, and dropping a figure for a chunk the default branch already holds.
|
||||
- **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores.
|
||||
|
||||
A `comprehension floor:` entry written before the history may still hold the last scoring run's five scores. While the default branch's history holds no run, the ratchet compares with those scores. The next scoring run moves them, and only them, into the history as its first run: a heading of the date or time the entry gives and whatever it names the run by, its commit included where named, and a table with the mean alone. The rest of the entry stays.
|
||||
|
||||
Reference in New Issue
Block a user