Measure each chunk's reading cost from its transcript and keep it in the comprehension history

This commit is contained in:
2026-10-08 15:40:43 +02:00
parent cefb297e14
commit 1b8142e7e5
14 changed files with 400 additions and 12 deletions
+1
View File
@@ -25,6 +25,7 @@
!bin/loop_claude/**/*.py
!bin/markdown_sections.py
!bin/rank_todo.py
!bin/reading_cost.py
!bin/statusline.py
!bin/test_*.py
!docs/
+2
View File
@@ -24,6 +24,8 @@ Decisions live in `docs/decisions.md`:
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
- reading cost: loop-claude keeps each finished chunk's figure in its archive, and the next chunk's larv-review moves it into `docs/comprehension-history.md`
- reading cost: a rise is the last 5 chunks' mean above the 5 before them, and keeps one standing plan item
## Working rules
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `loop-claude` measures each finished chunk's reading cost: the tokens the worker and its subagents took in before the worker's first commit, and the project's files they read most. It keeps the figure in `$LOOP_CLAUDE_TRANSCRIPTS/<key>/reading-cost.md`. larv-review runs the new `bin/reading_cost.py`, which 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 keeps one plan item naming the files read most; when not, it deletes that item.
- 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.
+1
View File
@@ -67,6 +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]` moves `loop-claude`'s reading-cost figures into a project's comprehension history and says whether they 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'`
+6 -2
View File
@@ -15,8 +15,7 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat
try:
with open(path, "rb") as handle:
raw = handle.read()
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
folder = paths.transcript_archive / project_key / chunk_of(raw)
make_private(folder)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
@@ -36,6 +35,11 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat
return None
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
def chunk_of(raw: bytes) -> str:
return hashlib.sha256(first_timestamped_line(raw)).hexdigest()
def unarchived(where: object, why: str | None) -> Failure:
return Failure(f"could not archive the transcript: {where}: {why}")
+181
View File
@@ -0,0 +1,181 @@
import collections
import dataclasses
import os
import pathlib
import posixpath
import re
import shlex
import time
from failure import Failure
from file_writes import make_private, replace_file
from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call
from loop_claude.cycle.archive import chunk_of
from loop_claude.paths import Paths
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
# Each reads the files it names; for these, the first operand is a pattern or a program unless -e or -f gives it.
READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"}
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
PLACES_KEPT = 10
HEADING = "## Reading cost, chunk "
TOKENS = re.compile(r"^(\d+) tokens read before the first commit\.$", re.MULTILINE)
@dataclasses.dataclass(frozen=True)
class Reading:
"""What the worker and its subagents took in before the worker's first commit."""
tokens: int
places: collections.Counter[str]
def record_reading(project_key: str, transcript: str, at: float, paths: Paths) -> Failure | None:
try:
raw = pathlib.Path(transcript).read_bytes()
subagents = [path.read_bytes() for path in sorted(pathlib.Path(transcript.removesuffix(".jsonl"), "subagents").glob("*.jsonl"))]
except OSError as failure:
return Failure(f"could not measure the reading cost: {failure.filename}: {failure.strerror}")
reading = measure(raw, subagents)
if reading is None:
return None
return keep_reading(pending_file(project_key, paths), entry(chunk_of(raw)[:12], time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)), reading))
def pending_file(project_key: str, paths: Paths) -> pathlib.Path:
return paths.transcript_archive / project_key / "reading-cost.md"
def measure(transcript: bytes, subagents: list[bytes]) -> Reading | None:
worker = entries_of(transcript)
commit = next((entry.get("timestamp", "") for entry in worker if any(commits(part) for part in assistant_parts(entry))), None)
if commit is None:
return None
tokens = 0
places: collections.Counter[str] = collections.Counter()
for thread in (worker, *map(entries_of, subagents)):
# Claude Code writes one entry per content block of a message, each with the message's usage.
counted: set[str] = set()
for entry in thread:
if entry.get("type") != "assistant" or entry.get("timestamp", "") >= commit:
continue
message = entry.get("message") or {}
if (key := str(message.get("id") or entry.get("uuid"))) not in counted:
counted.add(key)
usage = message.get("usage") or {}
tokens += int(usage.get("input_tokens") or 0) + int(usage.get("cache_creation_input_tokens") or 0)
for part in assistant_parts(entry):
places.update(read_paths(part, entry.get("cwd") or ""))
return Reading(tokens, places)
def entries_of(raw: bytes) -> list[dict]:
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
def arguments_of(part: object) -> tuple[object, dict]:
call = tool_call(part)
return (call[0], call[1]) if call and isinstance(call[1], dict) else (None, {})
def commits(part: object) -> bool:
name, arguments = arguments_of(part)
return name == "Bash" and bool(COMMIT.search(str(arguments.get("command", ""))))
def read_paths(part: object, cwd: str) -> list[str]:
name, arguments = arguments_of(part)
if name == "Read":
return place(str(arguments.get("file_path", "")), cwd, cwd)
if name == "Grep" and arguments.get("path"):
return place(str(arguments["path"]), cwd, cwd)
if name == "Bash":
return bash_reads(str(arguments.get("command", "")), cwd)
return []
def bash_reads(command: str, cwd: str) -> list[str]:
found = []
base = cwd
lines = iter(command.splitlines())
for line in lines:
try:
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
tokens = list(lexer)
except ValueError:
continue
for words in segments(tokens):
if words[0] == "cd" and len(words) == 2:
base = posixpath.normpath(posixpath.join(base, os.path.expanduser(words[1])))
found += [kept for path in operands(words) for kept in place(path, base, cwd)]
if "<<" in tokens or "<<-" in tokens:
marker = tokens[tokens.index("<<" if "<<" in tokens else "<<-") + 1:][:1]
for body in lines:
if marker and body.strip() == marker[0]:
break
return found
def segments(tokens: list[str]) -> list[list[str]]:
found: list[list[str]] = [[]]
skip = False
for token in tokens:
if skip:
skip = False
elif token and all(char in "();<>|&" for char in token):
# A redirect's target is written or fed, not read by the command.
skip = "<" in token or ">" in token
found.append([])
else:
found[-1].append(token)
return [words for words in found if words]
def operands(words: list[str]) -> list[str]:
program = posixpath.basename(words[0])
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
return []
given = [word for word in words[1:] if not word.startswith("-")]
if program in PATTERN_FIRST and not any(word in ("-e", "-f") for word in words):
given = given[1:]
return [word for word in given if ("/" in word or re.search(r"\.[A-Za-z0-9]+$", word)) and not NOT_A_PATH.search(word)]
# Relative to the folder it was read in, a worktree or the checkout, so both name a file alike; a file outside both is no place of the project.
def place(path: str, base: str, cwd: str) -> list[str]:
full = posixpath.normpath(posixpath.join(base, os.path.expanduser(path)))
roots = [root.rstrip("/") + "/" for root in (base, cwd) if root]
return next(([full.removeprefix(root)] for root in roots if full.startswith(root)), [])
def entry(chunk: str, finished: str, reading: Reading) -> str:
places = "".join(f"- `{path}` {count}\n" for path, count in sorted(reading.places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT])
return f"{HEADING}{chunk}, finished {finished}\n\n{reading.tokens} tokens read before the first commit.\n" + (f"\nRead most:\n\n{places}" if places else "")
def keep_reading(pending: pathlib.Path, block: str) -> Failure | None:
try:
make_private(pending.parent)
kept = pending.read_text(encoding="utf-8") if pending.exists() else ""
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not keep the reading cost in {pending}: {failure}")
if block.splitlines()[0] in kept.splitlines():
return None
if unwritten := replace_file(pending, (kept + ("\n" if kept else "") + block).encode()):
return Failure(f"could not keep the reading cost in {pending}: {unwritten.reason}")
return None
def blocks(text: str) -> list[str]:
"""The reading-cost entries of a markdown file, in order, each from its heading to the next heading."""
found = []
for section in re.split(r"(?m)^(?=## )", text):
if section.startswith(HEADING):
found.append(section.rstrip("\n") + "\n")
return found
def tokens_of(block: str) -> int:
match = TOKENS.search(block)
return int(match.group(1)) if match else 0
+2 -1
View File
@@ -12,6 +12,7 @@ from loop_claude.cycle.judge import judge
from loop_claude.project.model_choice import Models
from loop_claude.paths import Paths
from loop_claude.claude_code.transcript import read_transcript, render
from loop_claude.cycle.reading_cost import record_reading
from loop_claude.cycle.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.stop import Stop
@@ -111,7 +112,7 @@ def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) ->
finished = isinstance(verdict, Finished)
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}\n\nEvidence:\n{quoted(verdict.evidence)}", cycle.effects.now(), cycle.paths):
return Stop(1, failure.reason)
if finished and (failure := delete_session(cycle.session)):
if finished and (failure := record_reading(cycle.project_key, transcript_path, cycle.effects.now(), cycle.paths) or delete_session(cycle.session)):
return Stop(1, failure.reason)
return Archived()
+4 -1
View File
@@ -32,6 +32,9 @@ time. Claude Code keeps a folder per session beside its transcript, holding the
transcripts among other files; that folder, and every other file named after the session except
the transcript, are copied into <chunk>/session/. A file there is replaced only by a version that
grew from it. A file Claude Code rewrote lands beside its copy as <name>.<hash of its content>.
When a chunk finishes, the reading cost of its work before the worker's first commit is kept in
$LOOP_CLAUDE_TRANSCRIPTS/<key>/reading-cost.md; reading_cost.py --help says what it holds and how
it reaches the project.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first
@@ -50,7 +53,7 @@ Exit 1, saying why, when:
- the models file cannot be read or written
- claude leaves no transcript
- a transcript cannot be read or archived
- a finished chunk's session cannot be deleted
- a finished chunk's reading cost cannot be measured or kept, or its session deleted
- claude cannot start for an interrupt
- python cannot start for a reload
- a reload cannot read the state the running script handed it, likely because the edit changed that
+90
View File
@@ -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:]))
+43 -2
View File
@@ -1,4 +1,5 @@
import ast
import collections
import contextlib
import dataclasses
import hashlib
@@ -16,7 +17,7 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker
from loop_claude.cycle import archive, interrupt, judge, reading_cost, retry, run, states, worker
from loop_claude.project import checkout, model_choice, records
from loop_claude.effects import Effects
from loop_claude.claude_code import entries, session, transcript, trust
@@ -188,6 +189,24 @@ class Cycles(unittest.TestCase):
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_a_finished_chunk_that_committed_keeps_its_reading_cost_once(self):
def committing(args):
Worker(self.paths.claude_code_transcripts.parent)(args)
with open(session.transcript_file(self.session), "a") as handle:
handle.write(json.dumps({**assistant({"type": "tool_use", "name": "Bash", "input": {"command": "git commit -m x"}}), "timestamp": "9"}) + "\n")
return Streamed(0)
fake = FakeEffects(streams=[committing], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
[kept] = (self.paths.transcript_archive / "proj").glob("reading-cost.md")
self.assertRegex(kept.read_text(), r"^## Reading cost, chunk [0-9a-f]{12}, finished 2026-09-21T14:13:20Z\n\n0 tokens read before the first commit\.\n$")
self.assertIsNone(reading_cost.keep_reading(kept, kept.read_text()))
self.assertEqual(len(reading_cost.blocks(kept.read_text())), 1)
def test_a_finished_chunk_that_never_committed_keeps_no_reading_cost(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
self.assertFalse((self.paths.transcript_archive / "proj" / "reading-cost.md").exists())
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
@@ -424,6 +443,28 @@ class Records(unittest.TestCase):
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
class ReadingCost(unittest.TestCase):
def test_counts_each_message_once_and_the_projects_files_read_before_the_first_commit(self):
def said(timestamp, message_id, command=None, tokens=0, **call):
part = {"type": "tool_use", "name": "Bash", "input": {"command": command}} if command else {"type": "tool_use", **call}
return {"type": "assistant", "timestamp": timestamp, "cwd": "/c/p", "message": {"id": message_id, "content": [part], "usage": {"input_tokens": tokens, "cache_creation_input_tokens": 2 * tokens, "cache_read_input_tokens": 1000}}}
worker = [
said("1", "m1", tokens=10, name="Read", input={"file_path": "/c/p/README.md"}),
said("2", "m1", tokens=10, name="Read", input={"file_path": "/tmp/log.txt"}),
said("3", "m2", 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"),
said("4", "m3", command="git -C ../w commit -m 'x'", tokens=100),
said("5", "m4", tokens=100, name="Read", input={"file_path": "/c/p/late.py"}),
]
subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "src/a.py", "pattern": "x"}), said("6", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})]
lines = lambda entries: b"".join(json.dumps(entry).encode() + b"\n" for entry in entries)
reading = reading_cost.measure(lines(worker), [lines(subagent)])
self.assertEqual(reading, reading_cost.Reading(33, collections.Counter({"README.md": 2, "src/a.py": 2, "bin/t.py": 1})))
self.assertEqual(reading_cost.entry("abc", "t", reading), "## Reading cost, chunk abc, finished t\n\n33 tokens read before the first commit.\n\nRead most:\n\n- `README.md` 2\n- `src/a.py` 2\n- `bin/t.py` 1\n")
def test_measures_nothing_for_a_worker_that_never_committed(self):
self.assertIsNone(reading_cost.measure(json.dumps(assistant({"type": "tool_use", "name": "Bash", "input": {"command": "git log --grep commit"}})).encode(), []))
class Render(unittest.TestCase):
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
said = transcript.render([
@@ -615,7 +656,7 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "rule", "1", "entries.reason", read),
("cycle/run.py", "ask", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's reading cost cannot be measured or kept, or its session deleted"),
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
+58
View File
@@ -0,0 +1,58 @@
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
TOOL = pathlib.Path(__file__).resolve().parent / "reading_cost.py"
def figure(chunk, tokens, place="a.py"):
return f"## Reading cost, chunk {chunk}, finished t\n\n{tokens} tokens read before the first commit.\n\nRead most:\n\n- `{place}` 2\n"
class ReadingCostTool(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.checkout = self.home / "code" / "proj"
self.checkout.mkdir(parents=True)
subprocess.run(["git", "init", "-q"], cwd=self.checkout, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "x"], cwd=self.checkout, check=True)
self.pending = self.home / "archive" / "proj" / "reading-cost.md"
self.pending.parent.mkdir(parents=True)
def run_tool(self, cwd, *args):
env = {**os.environ, "HOME": str(self.home), "LOOP_CLAUDE_TRANSCRIPTS": str(self.home / "archive")}
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=env, text=True)
def test_appends_each_figure_once_from_a_worktree_and_reports_a_rise_with_the_places_read_most(self):
self.pending.write_text("\n".join(figure(f"c{n}", 100) for n in range(5)) + "\n" + "\n".join(figure(f"d{n}", 101, "b.py") for n in range(5)))
worktree = self.home / "code" / "proj-wt"
subprocess.run(["git", "worktree", "add", "-q", str(worktree)], cwd=self.checkout, check=True)
ran = self.run_tool(worktree)
self.assertEqual(ran.returncode, 0, ran.stderr)
history = worktree / "docs" / "comprehension-history.md"
self.assertEqual(ran.stdout, f"Appended 10 reading-cost figures to {history}.\nRising: the last 5 chunks read 101 tokens on average before their first commit, the 5 before them 100.\n\nRead most over the last 5:\n\n- `b.py` 10\n")
self.assertTrue(history.read_text().startswith("# Comprehension history\n\n## Reading cost, chunk c0, finished t\n"))
again = self.run_tool(worktree)
self.assertTrue(again.stdout.startswith(f"Appended 0 reading-cost figures to {history}.\nRising:"))
self.assertEqual(history.read_text().count("## Reading cost"), 10)
def test_reports_an_equal_mean_as_not_rising_and_too_few_figures_as_such(self):
self.pending.write_text("\n".join(figure(f"c{n}", 100) for n in range(9)))
self.assertEqual(self.run_tool(self.checkout).stdout.splitlines()[1], "9 chunks measured; the trend needs 10.")
with open(self.pending, "a") as handle:
handle.write("\n" + figure("c9", 100))
self.assertTrue(self.run_tool(self.checkout).stdout.splitlines()[1].startswith("Not rising: the last 5 chunks read 100 tokens"))
def test_exits_1_outside_a_checkout(self):
ran = self.run_tool(self.home)
self.assertEqual(ran.returncode, 1)
self.assertIn("not a git repository", ran.stderr)
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -109,3 +109,11 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
## the repo may name bender, bender-infra and ai-sandbox
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
## reading cost: loop-claude keeps each finished chunk's figure in its archive, and the next chunk's larv-review moves it into `docs/comprehension-history.md`
2026-10-08, lilleman. Serves goal 1.1: comprehension measured from real work, at no model cost (goal 1.4). loop-claude archives from the main checkout, outside any PR, so a tracked file it wrote there would dirty that checkout; the figure waits in the archive, and `bin/reading_cost.py` appends each one the history lacks, so a PR that never merges loses none. Rejected: loop-claude opening a PR of its own, one more PR per chunk and a tie to the forge; the worker measuring its own transcript before merging, which misses the chunk's tail. The figure counts tokens taken in, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk.
## reading cost: a rise is the last 5 chunks' mean above the 5 before them, and keeps one standing plan item
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; one standing item, refreshed rather than refiled, keeps that from flooding the plan. No published standard sets this threshold. Valid while figures arrive once per chunk.
+3 -1
View File
@@ -24,6 +24,8 @@ 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. Then keep at most one plan item titled `**Lower the reading cost of the files chunks read most before their first commit.**`. On `Rising:`, file it, or refresh its detail, with the tool's means and files. On `Not rising:`, delete it.
## 3. Passes
A pass is one kind of review, a row of the table, named by its first column. Its trigger says when it runs on a change it has not seen; its reviewer reports the findings.
@@ -87,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. Appending a run re-enters no pass. Resolve a merge conflict in the file by putting the default branch's runs first.
- **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 first.
- **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.
-5
View File
@@ -24,7 +24,6 @@
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 79 | 0.1.0 | | **Measure each chunk's reading cost from its transcript as loop-claude archives it, append it to `docs/comprehension-history.md`, and file a plan item naming the most-read places when the trend rises.** | 2 | 4 | 10 | 9 | 1.1, 1.4 | 34.8 |
| 72 | 0.1.0 | | **Rerun after a fix only the pass whose finding it answers, over the fix's diff alone; close a pass on a round of only 🟢, and give prose one round.** | 4 | 4 | 10 | 9 | 1.4, 1.5 | 32.3 |
| 75 | 0.1.0 | decision | **Decide the ratchet by a paired run: Mid A and the inherited architect read the whole project at the default branch and at the PR head, and rule whether it reads better, the same or worse once the PR lands; add seats only until the votes settle.** | 5 | 5 | 10 | 9 | 1.1, 1.4 | 31.6 |
| 73 | 0.1.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 10 | 8 | 1.4 | 31.4 |
@@ -55,10 +54,6 @@
## Details
### 79. Measure each chunk's reading cost from its transcript as loop-claude archives it, append it to `docs/comprehension-history.md`, and file a plan item naming the most-read places when the trend rises.
The human wants comprehension measured from real work. The archived transcript already records what the worker opened and searched before its first edit, and how much it read per line it changed; a script derives both at archive time with no model call. One chunk's figure is noise, since tasks differ; the trend over many chunks is the signal. The files read most often before an edit name where to act. Decide who commits the figure, and in which PR: loop-claude archives from the main checkout, outside any PR, and a tracked file it writes there dirties that checkout. Give these entries a heading the ratchet does not read as a scoring run.
### 72. Rerun after a fix only the pass whose finding it answers, over the fix's diff alone; close a pass on a round of only 🟢, and give prose one round.
The human ranks review cost first. An audit of the four costliest archived chunks (adf-codec, loop-claude's quoted answers, visthus networking, fejkdata on-demand loading; 2026-10-08) found nearly every finding that mattered in round 1 of its pass. Later rounds mostly re-checked the previous fix, flipped wording that earlier rounds wrote, or reported a bug the previous fix created; reviewers contradicted each other on the same CHANGELOG line across rounds. Estimated 55–75% of review effort in those chunks changed nothing a user would notice. Keep a round 2 where a fix touched behaviour: it caught real bugs the fix introduced.