From 1b8142e7e5dd21b5d458b44a25e27038d3bc62c4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 15:40:43 +0200 Subject: [PATCH 01/16] Measure each chunk's reading cost from its transcript and keep it in the comprehension history --- .gitignore | 1 + AGENTS.md | 2 + CHANGELOG.md | 1 + README.md | 1 + bin/loop_claude/cycle/archive.py | 8 +- bin/loop_claude/cycle/reading_cost.py | 181 ++++++++++++++++++++++++++ bin/loop_claude/cycle/run.py | 3 +- bin/loop_claude/loop/main.py | 5 +- bin/reading_cost.py | 90 +++++++++++++ bin/test_loop_claude.py | 45 ++++++- bin/test_reading_cost.py | 58 +++++++++ docs/decisions.md | 8 ++ skills/larv-review/SKILL.md | 4 +- todo.md | 5 - 14 files changed, 400 insertions(+), 12 deletions(-) create mode 100644 bin/loop_claude/cycle/reading_cost.py create mode 100755 bin/reading_cost.py create mode 100644 bin/test_reading_cost.py diff --git a/.gitignore b/.gitignore index ebd762be..a3627db5 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/AGENTS.md b/AGENTS.md index b237fa09..62262042 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 57b03d9c..11714be8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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//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. diff --git a/README.md b/README.md index 109c70ce..6ec464e2 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit - `loop-claude ` 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'` diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index f78b07d0..3724dec3 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -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}") diff --git a/bin/loop_claude/cycle/reading_cost.py b/bin/loop_claude/cycle/reading_cost.py new file mode 100644 index 00000000..c2271590 --- /dev/null +++ b/bin/loop_claude/cycle/reading_cost.py @@ -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 diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 716b6c49..2ef2f8cb 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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() diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 9de7f303..174410f8 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -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 /session/. A file there is replaced only by a version that grew from it. A file Claude Code rewrote lands beside its copy as .. +When a chunk finishes, the reading cost of its work before the worker's first commit is kept in +$LOOP_CLAUDE_TRANSCRIPTS//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 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 diff --git a/bin/reading_cost.py b/bin/reading_cost.py new file mode 100755 index 00000000..33f250b2 --- /dev/null +++ b/bin/reading_cost.py @@ -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//reading-cost.md (default ~/.claude/loop-claude-transcripts), +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 , finished " 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:])) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 300be867..d81b2939 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -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"), diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py new file mode 100644 index 00000000..5bf82838 --- /dev/null +++ b/bin/test_reading_cost.py @@ -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() diff --git a/docs/decisions.md b/docs/decisions.md index 91393e41..f76636cc 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 3aff8ca7..6a9c3950 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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. diff --git a/todo.md b/todo.md index eaa39d4e..50f6d9bc 100644 --- a/todo.md +++ b/todo.md @@ -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. -- 2.52.0 From 13d8b167a7f0f8081b8f44355f5d1b48e9e06090 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:10:23 +0200 Subject: [PATCH 02/16] Answer architecture round 1: measure from loop-claude's archive in the CLI, file the reading-cost item only on a rise, keep only tracked files --- .gitignore | 1 + AGENTS.md | 4 +- CHANGELOG.md | 2 +- README.md | 2 +- bin/loop_claude/cycle/archive.py | 42 ++++- bin/loop_claude/cycle/reading_cost.py | 181 ------------------ bin/loop_claude/cycle/run.py | 7 +- bin/loop_claude/loop/main.py | 5 +- bin/reading_cost.py | 256 +++++++++++++++++++++----- bin/shell_reads.py | 91 +++++++++ bin/test_loop_claude.py | 45 +---- bin/test_loop_claude_black_box.py | 7 +- bin/test_reading_cost.py | 129 ++++++++++--- bin/test_types.py | 2 +- docs/decisions.md | 8 +- skills/larv-review/SKILL.md | 4 +- todo.md | 9 +- 17 files changed, 468 insertions(+), 327 deletions(-) delete mode 100644 bin/loop_claude/cycle/reading_cost.py mode change 100755 => 100644 bin/reading_cost.py create mode 100644 bin/shell_reads.py diff --git a/.gitignore b/.gitignore index a3627db5..1bfa6950 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ !bin/markdown_sections.py !bin/rank_todo.py !bin/reading_cost.py +!bin/shell_reads.py !bin/statusline.py !bin/test_*.py !docs/ diff --git a/AGENTS.md b/AGENTS.md index 62262042..bd27bc48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,8 +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 +- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR +- 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 ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 11714be8..2cbb941b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +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//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 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 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. diff --git a/README.md b/README.md index 6ec464e2..f9e290e4 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit - `loop-claude ` 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. +- `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. - `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'` diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 3724dec3..4fa9ab04 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -1,6 +1,8 @@ +import dataclasses import hashlib import os import pathlib +import re import sys import time @@ -10,12 +12,25 @@ from file_writes import make_private, replace_file from loop_claude.paths import Paths from loop_claude.claude_code.session import session_files +FINISHED = "Verdict: finished" +UNFINISHED = "Verdict: unfinished" +FINISHED_AT = re.compile(rf"^(\S+) {re.escape(FINISHED)}$", re.MULTILINE) + + +@dataclasses.dataclass(frozen=True) +class FinishedChunk: + folder: str + finished: str + transcript: pathlib.Path + subagents: list[pathlib.Path] + def archive(project_key: str, path: str, task: str, outcome: str, at: float, paths: Paths) -> Failure | None: try: with open(path, "rb") as handle: raw = handle.read() - folder = paths.transcript_archive / project_key / chunk_of(raw) + # 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() make_private(folder) except OSError as failure: return unarchived(failure.filename, failure.strerror) @@ -24,7 +39,7 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" outcomes = copy.with_suffix(".outcomes.md") - stamped = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))} {outcome}" + stamped = f"{utc(at)} {outcome}" if copy.exists() and outcomes.exists(): return add_outcome(outcomes, stamped) # The copy lands last, so a copy on disk always has its outcomes and its session's files beside it. @@ -35,11 +50,6 @@ 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}") @@ -89,3 +99,21 @@ def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None: return copy if data != kept else None beside = copy.with_name(f"{copy.name}.{hashlib.sha256(data).hexdigest()}") return None if beside.exists() else beside + + +def utc(at: float) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)) + + +# One per chunk folder, its latest finished copy, in the order they finished. +def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure: + found = [] + try: + for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()): + copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8")))) + if copies: + finished, outcomes = copies[-1] + found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl")))) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read the archive {project_archive}: {failure}") + return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder)) diff --git a/bin/loop_claude/cycle/reading_cost.py b/bin/loop_claude/cycle/reading_cost.py deleted file mode 100644 index c2271590..00000000 --- a/bin/loop_claude/cycle/reading_cost.py +++ /dev/null @@ -1,181 +0,0 @@ -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 diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 2ef2f8cb..c8d26336 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -2,7 +2,7 @@ import dataclasses import typing from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working -from loop_claude.cycle.archive import archive +from loop_claude.cycle.archive import archive, FINISHED, UNFINISHED from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file from loop_claude.effects import Effects from failure import Failure @@ -12,7 +12,6 @@ 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 @@ -110,9 +109,9 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str: def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: 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): + if failure := archive(cycle.project_key, transcript_path, cycle.task, f"{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 := record_reading(cycle.project_key, transcript_path, cycle.effects.now(), cycle.paths) or delete_session(cycle.session)): + if finished and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) return Archived() diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 174410f8..9de7f303 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -32,9 +32,6 @@ 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 /session/. A file there is replaced only by a version that grew from it. A file Claude Code rewrote lands beside its copy as .. -When a chunk finishes, the reading cost of its work before the worker's first commit is kept in -$LOOP_CLAUDE_TRANSCRIPTS//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 in ~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first @@ -53,7 +50,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 reading cost cannot be measured or kept, or its session deleted +- a finished chunk's session cannot be 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 diff --git a/bin/reading_cost.py b/bin/reading_cost.py old mode 100755 new mode 100644 index 33f250b2..52790664 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -1,24 +1,27 @@ #!/usr/bin/env python3 -"""Move loop-claude's reading-cost figures into a project's history, and say whether they rise. +"""Measure each chunk loop-claude finished, append the figures to 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//reading-cost.md (default ~/.claude/loop-claude-transcripts), -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 , finished " heading. +docs/comprehension-history.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 chunk the judge ruled +finished that history does not hold, it measures what the worker and its subagents read before +the worker's first commit: the tokens they took in, 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. 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. +Exit 1, saying why, when git cannot start or finds no checkout, the archive or the history cannot +be read or written, or a figure in the history cannot be read back. """ import collections +import dataclasses import os import pathlib import re @@ -27,63 +30,218 @@ 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.claude_code.entries import assistant_parts, parse_entry, tool_call +from failure import Failure +from loop_claude.cycle.archive import finished_chunks, FinishedChunk from loop_claude.paths import paths_from from loop_claude.project.checkout import project_key +from shell_reads import Reads, resolved, shell_reads from file_writes import replace_file +from markdown_sections import sections +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 +TOKENS = re.compile(r"^(\d+) tokens read before the first commit\.$") WINDOW = 5 -PLACE = re.compile(r"^- `(.+)` (\d+)$", 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] + + +@dataclasses.dataclass(frozen=True) +class Checkout: + root: str + top: str + tracked: frozenset[str] 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) + helped = argv[:1] in (["-h"], ["--help"]) + if helped or len(argv) > 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") + 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()): - 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 failed(Failure(f"could not write {history}: {unwritten.reason}")) + readings = readings_of(text) + if isinstance(readings, Failure): + return failed(readings) + print(f"Appended {len(figures)} reading-cost figures to {history}.") + print(trend(readings)) 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): +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 checkout's .git, whichever worktree runs this. + return Checkout(str(pathlib.Path(common).parent), top, frozenset(filter(None, listed.stdout.split("\0")))) + + +def read_history(history: pathlib.Path) -> str | Failure: + try: + return history.read_text(encoding="utf-8") if history.exists() else "# Comprehension history\n" + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {history}: {failure}") + + +def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: + """The worker's transcript, then each subagent's.""" + try: + return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)] + except OSError as failure: + return Failure(f"could not read {failure.filename}: {failure.strerror}") + + +def unheld(chunks: list[FinishedChunk], history: str) -> list[FinishedChunk]: + held = {heading.removeprefix(HEADING).split(",")[0] for heading in sections(history) if heading.startswith(HEADING)} + return [chunk for chunk in chunks if chunk_id(chunk) not in held] + + +def chunk_id(chunk: FinishedChunk) -> str: + return chunk.folder[:12] + + +def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None: + worker, *subagents = [entries_of(thread) for thread in threads] + commit = commit_time(worker) + if commit is None: + return None + tokens = 0 + reads = Reads([], []) + for thread in (worker, *subagents): + read_before = [entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] + tokens += tokens_in(read_before) + for entry in read_before: + for part in assistant_parts(entry): + found = reads_of(part, str(entry.get("cwd") or "/"), home) + reads.read.extend(found.read) + reads.added.extend(found.added) + roots = [checkout.root, *reads.added] + return Reading(tokens, collections.Counter(place for path in reads.read if (place := relative(path, roots)) in checkout.tracked)) + + +def entries_of(raw: bytes) -> list[dict]: + return [entry for line in raw.splitlines() if (entry := parse_entry(line))] + + +def commit_time(worker: list[dict]) -> str | None: + for entry in worker: + for part in assistant_parts(entry): + name, arguments = call_of(part) + if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))): + return str(entry.get("timestamp", "")) + return None + + +def tokens_in(entries: list[dict]) -> int: + # Claude Code writes one entry per content block of a message, each with the message's usage. + usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)} + return sum(count(usage, "input_tokens") + count(usage, "cache_creation_input_tokens") for usage in usages.values() if isinstance(usage, dict)) + + +def count(usage: dict, field: str) -> int: + value = usage.get(field) + return value if isinstance(value, int) else 0 + + +def call_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 reads_of(part: object, cwd: str, home: str) -> Reads: + name, arguments = call_of(part) + path = arguments.get("file_path") if name == "Read" else arguments.get("path") if name == "Grep" else None + if path: + return Reads([resolved(cwd, str(path), home)], []) + return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], []) + + +# Relative to the deepest root holding it, so the checkout and each worktree name a file alike. +def relative(path: str, roots: list[str]) -> str | None: + holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")] + return path[len(max(holding, key=len).rstrip("/")) + 1:] if holding else None + + +def figure(chunk: FinishedChunk, reading: Reading) -> str: + places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places)) + 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 "") + + +def readings_of(history: str) -> list[Reading] | Failure: + readings = [] + for heading, bodies in sections(history).items(): + if heading.startswith(HEADING): + lines = bodies[0].splitlines() + 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 + + +def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]: + return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT] + + +def merged(history: str, figures: list[str]) -> str: + return history.rstrip("\n") + "\n\n" + "\n".join(figures) + + +def trend(readings: list[Reading]) -> str: + if len(readings) < 2 * WINDOW: + return f"{len(readings)} chunks measured; the trend needs {2 * WINDOW}." + last, earlier = readings[-WINDOW:], readings[-2 * WINDOW:-WINDOW] + means = f"the last {WINDOW} chunks read {mean(last)} tokens on average before their first commit, the {WINDOW} before them {mean(earlier)}." + if mean(last) <= mean(earlier): 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]) + read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in last), collections.Counter()))) 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)) +def mean(readings: list[Reading]) -> int: + return round(sum(reading.tokens for reading in readings) / len(readings)) if __name__ == "__main__": diff --git a/bin/shell_reads.py b/bin/shell_reads.py new file mode 100644 index 00000000..f14ba4f6 --- /dev/null +++ b/bin/shell_reads.py @@ -0,0 +1,91 @@ +"""The files a shell command reads, and the worktrees it adds, as absolute paths.""" +import dataclasses +import posixpath +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"} +READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"} +WORKTREE_OPTIONS_WITH_VALUE = {"-b", "-B", "--reason"} + + +@dataclasses.dataclass(frozen=True) +class Reads: + read: list[str] + added: list[str] + + +def shell_reads(command: str, cwd: str, home: str) -> Reads: + reads = Reads([], []) + base = cwd + for tokens in shell_lines(command): + for words in segments(tokens): + if words[0] == "cd" and len(words) == 2: + base = resolved(base, words[1], home) + reads.read.extend(resolved(base, word, home) for word in operands(words)) + reads.added.extend(resolved(base, path, home) for path in worktree_added(words)) + return reads + + +def shell_lines(command: str) -> typing.Iterator[list[str]]: + """Each line's tokens, skipping a heredoc's body, which feeds a program rather than naming files.""" + ends = None + for line in command.splitlines(): + if ends is not None: + ends = None if line.strip() == ends else ends + continue + try: + lexer = shlex.shlex(line, posix=True, punctuation_chars=True) + lexer.whitespace_split = True + 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 + yield tokens + + +def segments(tokens: list[str]) -> list[list[str]]: + found: list[list[str]] = [[]] + target = False + for token in tokens: + if target: + target = False + elif all(char in "();<>|&" for char in token): + # A redirect's target is written or fed, not read by the command. + target = "<" 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 {"-e", "-f"} & set(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)] + + +# git worktree add [-b ] [] +def worktree_added(words: list[str]) -> list[str]: + if words[:1] != ["git"] or "worktree" not in words or words[words.index("worktree") + 1:][:1] != ["add"]: + return [] + after = iter(words[words.index("worktree") + 2:]) + for word in after: + if word in WORKTREE_OPTIONS_WITH_VALUE: + next(after, None) + elif not word.startswith("-"): + return [word] + return [] + + +def resolved(base: str, path: str, home: str) -> str: + return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path)) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index d81b2939..300be867 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,5 +1,4 @@ import ast -import collections import contextlib import dataclasses import hashlib @@ -17,7 +16,7 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude.cycle import archive, interrupt, judge, reading_cost, retry, run, states, worker +from loop_claude.cycle import archive, interrupt, judge, 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 @@ -189,24 +188,6 @@ 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")) @@ -443,28 +424,6 @@ 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([ @@ -656,7 +615,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 reading cost cannot be measured or kept, or its session deleted"), + ("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be 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"), diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index e6db5120..1e78a640 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -18,6 +18,11 @@ import unittest BIN = pathlib.Path(__file__).resolve().parent TASK = "Do the next chunk." + +# A git hook's GIT_DIR, the host's LOOP_CLAUDE_* or PYTHONPATH would point the program under test at the host's own state. +def host_env() -> dict[str, str]: + return {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))} + # Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role, # or none left, is Ctrl-C to loop-claude, which otherwise loops forever. FAKE_CLAUDE = """#!{python} @@ -155,7 +160,7 @@ class Checkout: self.root.mkdir(parents=True) (self.root / "README.md").write_text(PREMISES) self.script = BIN / "loop-claude" - self.env = {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))} + self.env = host_env() fake = self.temp / "fake-bin" fake.mkdir() (fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable)) diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 5bf82838..f61474dd 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -1,3 +1,8 @@ +import collections +import contextlib +import hashlib +import io +import json import os import pathlib import subprocess @@ -5,48 +10,122 @@ import sys import tempfile import unittest +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from loop_claude.cycle.archive import archive, FINISHED, finished_chunks, FinishedChunk, UNFINISHED +from reading_cost import Checkout, Reading +from failure import Failure +from test_loop_claude_black_box import host_env +from loop_claude.paths import paths_from +import reading_cost +from shell_reads import Reads, shell_reads + 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" +def said(timestamp, message_id, command=None, tokens=0, cwd="/c/p", **call): + part = {"type": "tool_use", "name": "Bash", "input": {"command": command}} if command else {"type": "tool_use", **call} + return {"type": "assistant", "timestamp": timestamp, "cwd": cwd, "message": {"id": message_id, "content": [part], "usage": {"input_tokens": tokens, "cache_creation_input_tokens": 2 * tokens, "cache_read_input_tokens": 1000}}} + + +def jsonl(entries): + return b"".join(json.dumps(entry).encode() + b"\n" for entry in entries) + + +def folder_name(): + return hashlib.sha256(os.urandom(8)).hexdigest() + + +class ShellReads(unittest.TestCase): + def test_reads_operands_past_a_cd_and_skips_patterns_redirect_targets_and_heredoc_bodies(self): + 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_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"])) + + +class Measure(unittest.TestCase): + def test_counts_each_message_once_and_the_tracked_files_read_before_the_first_commit(self): + 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": "/c/p/.env"}), + said("3", "m2", command="git worktree add ../w && cd ../w && cat src/a.py && cd src && cat b.py"), + said("4", "m3", command="cd /tmp && cat x.py"), + said("5", "m4", command="git -C ../w commit -m 'x'", tokens=100), + said("6", "m5", tokens=100, name="Read", input={"file_path": "/c/p/late.py"}), + ] + subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "/c/w/src/a.py"}), said("7", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})] + checkout = Checkout("/c/p", "/c/w", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"})) + self.assertEqual(reading_cost.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1}))) + + def test_measures_nothing_for_a_worker_that_never_committed(self): + self.assertIsNone(reading_cost.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) + + def test_skips_a_usage_that_is_not_a_count(self): + self.assertEqual(reading_cost.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2) + + +class Figures(unittest.TestCase): + def test_rises_only_above_the_five_before_and_needs_ten(self): + flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10 + self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured; the trend needs 10.") + self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks read 100 tokens")) + self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: 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") + + def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self): + reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3})) + written = reading_cost.figure(FinishedChunk("abcdef0123456789", "t", pathlib.Path(), []), reading) + self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished t\n\n7 tokens read before the first commit.\n\nRead most:\n\n- `a.py` 3\n- `b.py` 1\n") + self.assertEqual(reading_cost.readings_of(written), [reading]) + 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')) class ReadingCostTool(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) - self.home = pathlib.Path(temp.name) + self.home = pathlib.Path(os.path.realpath(temp.name)) + self.env = {**host_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.home)} 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) + (self.checkout / "a.py").write_text("") + self.git("init", "-q") + self.git("add", "a.py") + self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") + self.paths = paths_from(self.home, {}) - 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 git(self, *args): + subprocess.run(["git", *args], cwd=self.checkout, check=True, env=self.env) - 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))) + def archive_chunk(self, at, outcome=FINISHED): + transcript = self.home / ".claude" / "projects" / "-proj" / f"{folder_name()}.jsonl" + (transcript.with_suffix("") / "subagents").mkdir(parents=True) + worker = [said("1", "m1", tokens=10, cwd=str(self.checkout), name="Read", input={"file_path": str(self.checkout / "a.py")}), said("2", "m2", command="git commit -m x")] + transcript.write_bytes(jsonl([{"timestamp": str(at)}, *worker])) + (transcript.with_suffix("") / "subagents" / "agent-a.jsonl").write_bytes(jsonl([said("1", "s1", tokens=1)])) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(archive("proj", str(transcript), "Do it.", f"{outcome}\n\nEvidence:\n> merged", at, self.paths)) + + def run_tool(self, cwd): + return subprocess.run([sys.executable, str(TOOL)], capture_output=True, cwd=cwd, env=self.env, text=True) + + def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self): + self.archive_chunk(1790000200) + self.archive_chunk(1790000100) + self.archive_chunk(1790000000, UNFINISHED) + chunks = finished_chunks(self.paths.transcript_archive / "proj") + self.assertEqual([chunk.finished for chunk in chunks], ["2026-09-21T14:15:00Z", "2026-09-21T14:16:40Z"]) worktree = self.home / "code" / "proj-wt" - subprocess.run(["git", "worktree", "add", "-q", str(worktree)], cwd=self.checkout, check=True) + self.git("worktree", "add", "-q", str(worktree)) 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")) + self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures to {history}.\n2 chunks measured; the trend needs 10.\n") + figure = "## Reading cost, chunk {}, finished {}\n\n33 tokens read before the first commit.\n\nRead most:\n\n- `a.py` 1\n" + 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) def test_exits_1_outside_a_checkout(self): ran = self.run_tool(self.home) diff --git a/bin/test_types.py b/bin/test_types.py index e071bb85..18a7bbb4 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -11,5 +11,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-m", "reading_cost", "-m", "shell_reads", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index f76636cc..e295a2b3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -110,10 +110,10 @@ lilleman decided to ship each of these under the floor on the day listed. Each l 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` +## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -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. +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; `bin/reading_cost.py` instead measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 with its subagents' transcripts. -## reading cost: a rise is the last 5 chunks' mean above the 5 before them, and keeps one standing plan item +## 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; 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. +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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 6a9c3950..037b1762 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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. 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. +**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. ## 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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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. +- **History.** `docs/comprehension-history.md` keeps every scoring run, appended and never edited. A run is a `## , at ` 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 `, hardest first:` or, for the architect, `, 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. - **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. diff --git a/todo.md b/todo.md index 50f6d9bc..3e9674a5 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 9` -`Next ID = 83` +`Next ID = 84` | Goal | W | |---|---| @@ -37,6 +37,7 @@ | 59 | 0.1.0 | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 3 | 3 | 6 | 6 | 1.4 | 19.8 | | 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 1.1 | 16.9 | | 80 | 0.1.0 | | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 1 | 5 | 5 | 4 | 16.8 | +| 83 | 0.1.0 | | **Group `bin/` by tool, so each tool's modules and tests sit together.** | 3 | 4 | 4 | 6 | 1.1 | 15.9 | | 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 1.1 | 15.6 | | 67 | 0.1.0 | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 4 | 5 | 1.3 | 14.9 | | 66 | 0.1.0 | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 3 | 3 | 4 | 5 | 1.1 | 14.2 | @@ -112,6 +113,10 @@ The repo has no CI, so larv-review's gate is the local run, and larv-review's Ga Raised by the principles audit of PR #224. The `settings.json` decision is valid while every machine taking this checkout is a sandbox, but Install asks for a sandbox only for `loop-claude`, so a new machine is never told. +### 83. Group `bin/` by tool, so each tool's modules and tests sit together. + +Raised by the architect on PR #225 and by the inherited architect of PR #224's scoring run: `bin/` is one flat folder of tools, the modules they share and the repo's checks, with `loop_claude`'s tests beside them instead of beside the package. + ### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key. The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. @@ -162,7 +167,7 @@ Claude Code owns that file and writes it. `trust` reads it, changes it and write ### 4. Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran. -Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. +Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading_cost.py` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id the history holds, so give it a way to match a figure written under the old name. ### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in. -- 2.52.0 From 471350d388dee6165adeb13ce430e01992ac4054 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:28:49 +0200 Subject: [PATCH 03/16] Answer architecture round 1: give the transcript archive one module that writes and reads it, anchor the finished line to its stamp, build Reads once, and record the scoring run --- bin/loop_claude/cycle/run.py | 2 +- .../archive.py => transcript_archive.py} | 2 +- bin/reading_cost.py | 19 +++---- bin/shell_reads.py | 9 ++-- bin/test_loop_claude.py | 3 +- bin/test_reading_cost.py | 2 +- docs/comprehension-history.md | 51 +++++++++++++++++++ todo.md | 4 +- 8 files changed, 70 insertions(+), 22 deletions(-) rename bin/loop_claude/{cycle/archive.py => transcript_archive.py} (97%) diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index c8d26336..2f544116 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -2,7 +2,7 @@ import dataclasses import typing from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working -from loop_claude.cycle.archive import archive, FINISHED, UNFINISHED +from loop_claude.transcript_archive import archive, FINISHED, UNFINISHED from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file from loop_claude.effects import Effects from failure import Failure diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/transcript_archive.py similarity index 97% rename from bin/loop_claude/cycle/archive.py rename to bin/loop_claude/transcript_archive.py index 4fa9ab04..bc04daaa 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/transcript_archive.py @@ -14,7 +14,7 @@ from loop_claude.claude_code.session import session_files FINISHED = "Verdict: finished" UNFINISHED = "Verdict: unfinished" -FINISHED_AT = re.compile(rf"^(\S+) {re.escape(FINISHED)}$", re.MULTILINE) +FINISHED_AT = re.compile(rf"^(\d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\dZ) {re.escape(FINISHED)}$", re.MULTILINE) @dataclasses.dataclass(frozen=True) diff --git a/bin/reading_cost.py b/bin/reading_cost.py index 52790664..5bedf9d8 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -32,7 +32,7 @@ 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.cycle.archive import finished_chunks, FinishedChunk +from loop_claude.transcript_archive import finished_chunks, FinishedChunk from loop_claude.paths import paths_from from loop_claude.project.checkout import project_key from shell_reads import Reads, resolved, shell_reads @@ -147,18 +147,11 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No commit = commit_time(worker) if commit is None: return None - tokens = 0 - reads = Reads([], []) - for thread in (worker, *subagents): - read_before = [entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] - tokens += tokens_in(read_before) - for entry in read_before: - for part in assistant_parts(entry): - found = reads_of(part, str(entry.get("cwd") or "/"), home) - reads.read.extend(found.read) - reads.added.extend(found.added) - roots = [checkout.root, *reads.added] - return Reading(tokens, collections.Counter(place for path in reads.read if (place := relative(path, roots)) in checkout.tracked)) + before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)] + reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)] + roots = [checkout.root, *(added for found in reads for added in found.added)] + places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked) + return Reading(sum(map(tokens_in, before)), places) def entries_of(raw: bytes) -> list[dict]: diff --git a/bin/shell_reads.py b/bin/shell_reads.py index f14ba4f6..89d0c833 100644 --- a/bin/shell_reads.py +++ b/bin/shell_reads.py @@ -20,15 +20,16 @@ class Reads: def shell_reads(command: str, cwd: str, home: str) -> Reads: - reads = Reads([], []) + read: list[str] = [] + added: list[str] = [] base = cwd for tokens in shell_lines(command): for words in segments(tokens): if words[0] == "cd" and len(words) == 2: base = resolved(base, words[1], home) - reads.read.extend(resolved(base, word, home) for word in operands(words)) - reads.added.extend(resolved(base, path, home) for path in worktree_added(words)) - return reads + read += [resolved(base, word, home) for word in operands(words)] + added += [resolved(base, path, home) for path in worktree_added(words)] + return Reads(read, added) def shell_lines(command: str) -> typing.Iterator[list[str]]: diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 300be867..c30c727f 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -16,12 +16,13 @@ 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 import transcript_archive as archive 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 from failure import Failure from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from +from loop_claude.cycle import interrupt, judge, retry, run, states, worker from loop_claude.cycle.retry import Limited from loop_claude.loop import main, reload from loop_claude import paths diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index f61474dd..8a61ed20 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -12,7 +12,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude.cycle.archive import archive, FINISHED, finished_chunks, FinishedChunk, UNFINISHED +from loop_claude.transcript_archive import archive, FINISHED, finished_chunks, FinishedChunk, UNFINISHED from reading_cost import Checkout, Reading from failure import Failure from test_loop_claude_black_box import host_env diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index d975b6e2..36b343a5 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -109,3 +109,54 @@ Inherited architect, would restructure first: - `bin/loop_claude/project/checkout.py:32` `read_utf8` - `agents/stability-reviewer.md:3`, `agents/systems-architect.md:3`: house style - `workflow-bench/bench.py:26`: not runnable from the repo + +## 2026-10-08T14:28:39Z, PR #225 at 13d8b16 + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Junior A | 7 | 6 | 7 | 6 | 6.5 | +| Mid A | 7 | 6.5 | 7 | 6 | 6.5 | +| Maintainability senior | 7.5 | 7 | 7.5 | 7 | 7 | +| Inherited architect | 7 | 6.5 | 6.5 | 7 | 7 | +| Mean | 7.13 | 6.50 | 7.00 | 6.50 | 6.75 | + +Junior A, hardest first: + +- `skills/larv-review/SKILL.md:79` "Architecture": Floor, Ratchet, Fresh, Suspended, and the history paragraph at `:95` +- `skills/larv-review/SKILL.md:53` "Round cap", with `:64` "Re-entry" +- `bin/loop_claude/cycle/judge.py:31` `run_judge`, with `grounded`, `verbatim` and `plain` +- `bin/loop_claude/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` and `:104` `question_for` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` +- `bin/loop_claude/cycle/archive.py:28` `archive`, with `copy_for` and `finished_chunks` +- `bin/reading_cost.py:145` `measure`, with `bin/shell_reads.py:52` `segments` and `:67` `operands` +- `bin/rank_todo.py:408` `rank_details` + +Mid A, hardest first: + +- `skills/larv-review/SKILL.md:53` "Round cap", with "History", "Ratchet", "Fresh" and "Suspended" +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES`, with `QUOTE_SOURCES`, `ANSWER_DESTINATIONS` and `ANSWERS_RECORDED` +- `bin/loop_claude/cycle/states.py:69` `transition` +- `bin/loop_claude/cycle/archive.py:28` `archive`, with `finished_chunks` and `FINISHED_AT` +- `bin/reading_cost.py:145` `measure`, with `located`, `relative` and `commit_time` +- `bin/shell_reads.py:67` `operands` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` +- `bin/rank_todo.py:408` `rank_details` + +Maintainability senior, hardest first: + +- `skills/larv-review/SKILL.md:79` "Architecture" +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES`, with `cycle/worker.py:41` `worker_args` +- `bin/loop_claude/cycle/judge.py:31` `run_judge` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` +- `bin/loop_claude/cycle/archive.py:17` `FINISHED_AT`, with `finished_chunks` and `cycle/run.py:110` `close` +- `bin/reading_cost.py:145` `measure`, with `located` +- `bin/shell_reads.py:67` `operands` +- `bin/rank_todo.py:408` `rank_details`, with `read_scoring` + +Inherited architect, would restructure first: + +- `skills/larv-review/SKILL.md:53` "Round cap", and `:88` "Architecture" from History to Suspended +- `bin/loop_claude/cycle/archive.py:109` `finished_chunks`, with `bin/reading_cost.py:106` `located` and `bin/loop_claude/project/checkout.py:7` `checkout_root` +- `bin/` flat folder: tools, shared modules and tests +- `bin/loop_claude/project/checkout.py:32` `read_utf8`, `claude_code/transcript.py:27` `render`, `judge_reply.py:87` `Verdict` beside `states.py:24` `ruling` +- `bin/loop_claude/loop/main.py:9` the recorded-answers rule, beside `judge_reply.py:11` `ANSWERS_RECORDED` diff --git a/todo.md b/todo.md index 3e9674a5..03996a80 100644 --- a/todo.md +++ b/todo.md @@ -89,7 +89,7 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go ### 62. Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name. -Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 1.1: the `comprehension floor:` entry in `docs/decisions.md` lists seven decisions to ship under the floor, and 0.1.0 waits on the floor. PR #215's last run put Locality at 6.63 and Self-sufficiency and the overall at 6.88. Its seats named, under Locality: the judge's contract spread over `cycle/judge_reply.py`, `cycle/worker.py` and `cycle/run.py`; `remaining`, which is `Unfinished.evidence` under another name, threaded through `loop/main.py`, `loop/reload.py`'s `LoopRun`, `cycle/run.py` and `worker_args`; the `quoted_answers` cap held by case order in `cycle/states.py`'s `transition` and restated in `run.py`'s `question_for`; the four outcome texts `run.py` builds inline for `archive`. Under Self-sufficiency: `skills/larv-review/SKILL.md`, which needs `CLAUDE.md` → "Vocabulary" open beside it; the archive layout, defined only in `bin/loop_claude/loop/main.py`'s docstring and not at `cycle/archive.py`; `JUDGE_RULES`' precedence in `cycle/judge_reply.py`, restated by `verdict_from`'s branch order and the `Reply` field descriptions; the `sys.path` insert in `bin/loop-claude` that the `from failure import` lines rely on, unstated at the import sites. +Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 1.1: the `comprehension floor:` entry in `docs/decisions.md` lists seven decisions to ship under the floor, and 0.1.0 waits on the floor. PR #215's last run put Locality at 6.63 and Self-sufficiency and the overall at 6.88. Its seats named, under Locality: the judge's contract spread over `cycle/judge_reply.py`, `cycle/worker.py` and `cycle/run.py`; `remaining`, which is `Unfinished.evidence` under another name, threaded through `loop/main.py`, `loop/reload.py`'s `LoopRun`, `cycle/run.py` and `worker_args`; the `quoted_answers` cap held by case order in `cycle/states.py`'s `transition` and restated in `run.py`'s `question_for`; the four outcome texts `run.py` builds inline for `archive`. Under Self-sufficiency: `skills/larv-review/SKILL.md`, which needs `CLAUDE.md` → "Vocabulary" open beside it; the archive layout, defined only in `bin/loop_claude/loop/main.py`'s docstring and not at `transcript_archive.py`; `JUDGE_RULES`' precedence in `cycle/judge_reply.py`, restated by `verdict_from`'s branch order and the `Reply` field descriptions; the `sys.path` insert in `bin/loop-claude` that the `from failure import` lines rely on, unstated at the import sites. ### 21. Give `settings.json`'s model one writer, and sort its keys. @@ -121,6 +121,8 @@ Raised by the architect on PR #225 and by the inherited architect of PR #224's s The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. +`bin/reading_cost.py` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading_cost.py` never looks. Derive both keys one way. + ### 67. Point stability-reviewer at the technical principles in place of its own restatement of them. DRY, in `principles/technical-principles.md`: `agents/stability-reviewer.md` restates principles in its own words, and the copy has drifted: it asks for "properly randomised UUIDs" where the principle requires UUID v7. -- 2.52.0 From aa062da0bdd8812ad6ab02fb533dd4c77c4d50fd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:31:37 +0200 Subject: [PATCH 04/16] 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 --- CHANGELOG.md | 2 +- README.md | 2 +- bin/loop_claude/transcript_archive.py | 3 +- bin/reading_cost.py | 84 ++++++++++++++++++--------- bin/shell_reads.py | 5 +- bin/test_reading_cost.py | 18 +++++- docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 4 +- 8 files changed, 82 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cbb941b..39bef0a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index f9e290e4..5f542e3d 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit - `loop-claude ` 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'` diff --git a/bin/loop_claude/transcript_archive.py b/bin/loop_claude/transcript_archive.py index bc04daaa..f9ce9919 100644 --- a/bin/loop_claude/transcript_archive.py +++ b/bin/loop_claude/transcript_archive.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. diff --git a/bin/reading_cost.py b/bin/reading_cost.py index 5bedf9d8..552c5834 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -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 , finished " 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, " 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]]: diff --git a/bin/shell_reads.py b/bin/shell_reads.py index 89d0c833..034129e8 100644 --- a/bin/shell_reads.py +++ b/bin/shell_reads.py @@ -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 diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 8a61ed20..0e1845b9 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -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) diff --git a/docs/decisions.md b/docs/decisions.md index e295a2b3..38f2e0bb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 037b1762..adeaad67 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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. -- 2.52.0 From 24efce674c5281e980dff215161ed3d1b7c8acb1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:32:39 +0200 Subject: [PATCH 05/16] Answer architecture round 2: keep reading_cost's main to finding, updating and reporting --- bin/reading_cost.py | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/bin/reading_cost.py b/bin/reading_cost.py index 552c5834..9725d6a5 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -17,9 +17,8 @@ order the chunks finished. 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. +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. Exit 1, saying why, when git cannot start or finds no checkout, the archive or the history cannot be read or written, or a figure in the history cannot be read back. @@ -70,31 +69,39 @@ class Checkout: def main(argv: list[str]) -> int: reset = argv[:1] == ["--reset"] given = argv[1:] if reset else argv - helped = given[:1] in (["-h"], ["--help"]) - if helped or len(given) > 1: + if given[:1] in (["-h"], ["--help"]) or len(given) > 1: + helped = len(given) == 1 print(__doc__.strip(), file=sys.stdout if helped else sys.stderr) return 0 if helped else 1 - home = pathlib.Path.home() checkout = located() if isinstance(checkout, Failure): return failed(checkout) history = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "comprehension-history.md") + updated = update(history, checkout, reset) + if isinstance(updated, Failure): + return failed(updated) + appended, readings = updated + print(f"Appended {appended} reading-cost figures{' and a reset' if reset else ''} to {history}.") + print(trend(readings)) + return 0 + + +def update(history: pathlib.Path, checkout: Checkout, reset: bool) -> tuple[int, list[Reading]] | Failure: + """How many figures it appended, and the readings the trend counts.""" text = read_history(history) if isinstance(text, Failure): - return failed(text) - figures = new_figures(text, checkout, home) + return text + figures = new_figures(text, checkout, pathlib.Path.home()) if isinstance(figures, Failure): - return failed(figures) + return 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) + return readings 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 + return unwritten + return len(figures), readings def new_figures(history: str, checkout: Checkout, home: pathlib.Path) -> list[str] | Failure: -- 2.52.0 From 5062a97158555765fbb83e749b6cb68914cc4848 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:40:26 +0200 Subject: [PATCH 06/16] Answer stability round 1: compare medians, refuse unknown options, name the archive read, repair a failed run, and pass the clock and home in from main --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- bin/reading_cost.py | 48 ++++++++++++++++++++----------------- bin/test_reading_cost.py | 22 ++++++++++------- docs/decisions.md | 4 ++-- skills/larv-review/SKILL.md | 2 +- 6 files changed, 45 insertions(+), 35 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bd27bc48..5a408cbf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ Decisions live in `docs/decisions.md`: - 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: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -- 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 +- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that only its own chunk or the human removes ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 39bef0a7..5cc3e74a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. The chunk that ships it runs `reading_cost.py --reset`, so the trend counts only chunks that finished after 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' median 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. diff --git a/bin/reading_cost.py b/bin/reading_cost.py index 9725d6a5..815e81b9 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -7,7 +7,7 @@ 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 project, $LOOP_CLAUDE_TRANSCRIPTS/ (default ~/.claude/loop-claude-transcripts), being the checkout's path relative to ~/code, or to / outside it. For each chunk the judge ruled -finished that history does not hold, it measures what the worker and its subagents read before +finished, under a UTC time, that history does not hold, it measures what the worker and its subagents read before the worker's first commit: the tokens they took in, 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 @@ -16,8 +16,8 @@ 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 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 +It then compares the median 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 medians. 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 cannot start or finds no checkout, the archive or the history cannot @@ -28,6 +28,7 @@ import dataclasses import os import pathlib import re +import statistics import subprocess import sys import time @@ -69,32 +70,35 @@ class Checkout: def main(argv: list[str]) -> int: reset = argv[:1] == ["--reset"] given = argv[1:] if reset else argv - if given[:1] in (["-h"], ["--help"]) or len(given) > 1: - helped = len(given) == 1 + if given[:1] in (["-h"], ["--help"]) or len(given) > 1 or given[:1] and given[0].startswith("-"): + helped = given[:1] in (["-h"], ["--help"]) and len(given) == 1 print(__doc__.strip(), file=sys.stdout if helped else sys.stderr) return 0 if helped else 1 checkout = located() if isinstance(checkout, Failure): return failed(checkout) + home = pathlib.Path.home() + paths = paths_from(home, os.environ) + archive = paths.transcript_archive / project_key(checkout.root, paths.code) history = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "comprehension-history.md") - updated = update(history, checkout, reset) + updated = update(history, archive, checkout, str(home), utc(time.time()) if reset else None) if isinstance(updated, Failure): return failed(updated) appended, readings = updated - print(f"Appended {appended} reading-cost figures{' and a reset' if reset else ''} to {history}.") + print(f"Appended {appended} reading-cost figures from {archive}{' and a reset' if reset else ''} to {history}.") print(trend(readings)) return 0 -def update(history: pathlib.Path, checkout: Checkout, reset: bool) -> tuple[int, list[Reading]] | Failure: +def update(history: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> tuple[int, list[Reading]] | Failure: """How many figures it appended, and the readings the trend counts.""" text = read_history(history) if isinstance(text, Failure): return text - figures = new_figures(text, checkout, pathlib.Path.home()) + figures = new_figures(text, archive, checkout, home) if isinstance(figures, Failure): return figures - marks = [*figures, f"## {RESET}{utc(time.time())}\n"] if reset else 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): @@ -104,9 +108,8 @@ def update(history: pathlib.Path, checkout: Checkout, reset: bool) -> tuple[int, return len(figures), readings -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)) +def new_figures(history: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure: + chunks = finished_chunks(archive) if isinstance(chunks, Failure): return chunks figures = [] @@ -114,7 +117,7 @@ def new_figures(history: str, checkout: Checkout, home: pathlib.Path) -> list[st threads = read_threads(chunk) if isinstance(threads, Failure): return threads - if reading := measure(threads, checkout, str(home)): + if reading := measure(threads, checkout, home): figures.append(figure(chunk, reading)) return figures @@ -257,19 +260,20 @@ def merged(history: str, figures: list[str]) -> str: return history.rstrip("\n") + "\n\n" + "\n".join(figures) +# Medians, so one chunk that ran a panel of readers or waited out a usage limit does not decide the trend alone. def trend(readings: list[Reading]) -> str: if len(readings) < 2 * WINDOW: return f"{len(readings)} chunks measured; the trend needs {2 * WINDOW}." - last, earlier = readings[-WINDOW:], readings[-2 * WINDOW:-WINDOW] - means = f"the last {WINDOW} chunks read {mean(last)} tokens on average before their first commit, the {WINDOW} before them {mean(earlier)}." - if mean(last) <= mean(earlier): - return f"Not rising: {means}" - read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in last), collections.Counter()))) - return f"Rising: {means}\n\nRead most over the last {WINDOW}:\n{read_most}" + last, earlier = middle(readings[-WINDOW:]), middle(readings[-2 * WINDOW:-WINDOW]) + medians = f"the last {WINDOW} chunks' median is {last} tokens read before their first commit, the {WINDOW} before them {earlier}." + if last <= earlier: + return f"Not rising: {medians}" + read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter()))) + return f"Rising: {medians}\n\nRead most over the last {WINDOW}:\n{read_most}" -def mean(readings: list[Reading]) -> int: - return round(sum(reading.tokens for reading in readings) / len(readings)) +def middle(readings: list[Reading]) -> int: + return round(statistics.median(reading.tokens for reading in readings)) if __name__ == "__main__": diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 0e1845b9..a1008d68 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -73,8 +73,9 @@ class Figures(unittest.TestCase): def test_rises_only_above_the_five_before_and_needs_ten(self): flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10 self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured; the trend needs 10.") - self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks read 100 tokens")) - self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: 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") + self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 tokens")) + self.assertTrue(reading_cost.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:")) + self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 tokens read before their first commit, the 5 before them 100.\n\nRead most over the last 5:\n\n- `b.py` 10") def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self): reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3})) @@ -120,8 +121,8 @@ class ReadingCostTool(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(archive("proj", str(transcript), "Do it.", f"{outcome}\n\nEvidence:\n> merged", at, self.paths)) - def run_tool(self, cwd): - return subprocess.run([sys.executable, str(TOOL)], capture_output=True, cwd=cwd, env=self.env, text=True) + def run_tool(self, cwd, *args): + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=self.env, text=True) def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self): self.archive_chunk(1790000200) @@ -134,15 +135,20 @@ class ReadingCostTool(unittest.TestCase): ran = self.run_tool(worktree) self.assertEqual(ran.returncode, 0, ran.stderr) history = worktree / "docs" / "comprehension-history.md" - self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures to {history}.\n2 chunks measured; the trend needs 10.\n") + self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured; the trend needs 10.\n") figure = "## Reading cost, chunk {}, finished {}\n\n33 tokens read before the first commit.\n\nRead most:\n\n- `a.py` 1\n" 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.assertTrue(self.run_tool(worktree).stdout.startswith(f"Appended 0 reading-cost figures from")) 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") + reset = self.run_tool(worktree, "--reset") + self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} 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_refuses_an_option_it_does_not_know(self): + ran = self.run_tool(self.checkout, "--rest") + self.assertEqual((ran.returncode, ran.stdout), (1, "")) + self.assertFalse((self.checkout / "--rest").exists()) + def test_exits_1_outside_a_checkout(self): ran = self.run_tool(self.home) self.assertEqual(ran.returncode, 1) diff --git a/docs/decisions.md b/docs/decisions.md index 38f2e0bb..e782646f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -114,6 +114,6 @@ lilleman decided to ship each of these under the floor on the day listed. Each l 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; `bin/reading_cost.py` instead measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 with its subagents' transcripts. -## 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 +## reading cost: a rise is the last 5 chunks' median 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, 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. +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). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index adeaad67..ff314df5 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it. +**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. On exit 1, repair what its message names and run it again; ask the human when the message names no repair. 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 -- 2.52.0 From f33704872f8acf1c92ad501fdfb24c6cf56ed90d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:40:31 +0200 Subject: [PATCH 07/16] Answer stability round 1: name the tool's medians in larv-review --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index ff314df5..0fb97ba3 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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. On exit 1, repair what its message names and run it again; ask the human when the message names no repair. 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. +**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 medians and files as its detail; where the plan already holds it, refresh its detail instead. On exit 1, repair what its message names and run it again; ask the human when the message names no repair. 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 -- 2.52.0 From da1ef19795db76b6d24e0a11ef00330c086b8e45 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:43:22 +0200 Subject: [PATCH 08/16] Answer product-owner round 1: name the figure's new input tokens, label the places' counts, give a usage error one line, and say where the reading-cost item goes --- CHANGELOG.md | 2 +- README.md | 2 +- bin/reading_cost.py | 37 +++++++++++++++++++------------------ bin/test_reading_cost.py | 11 +++++------ docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 2 +- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc3e74a..e75766d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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' median 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 runs the new `bin/reading_cost.py`, which measures each chunk `loop-claude` finished from its archive: the new input 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. Once 10 chunks are measured, and the last 5 chunks' median 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. diff --git a/README.md b/README.md index 5f542e3d..ad898b4e 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit - `loop-claude ` 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 [--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. +- `reading_cost.py [--reset] [history]` appends a figure for each chunk `loop-claude` finished to 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'` diff --git a/bin/reading_cost.py b/bin/reading_cost.py index 815e81b9..fc205697 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -3,14 +3,14 @@ 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 -project, $LOOP_CLAUDE_TRANSCRIPTS/ (default ~/.claude/loop-claude-transcripts), being -the checkout's path relative to ~/code, or to / outside it. For each chunk the judge ruled -finished, under a UTC time, that history does not hold, it measures what the worker and its subagents read before -the worker's first commit: the tokens they took in, 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 +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 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 history 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 @@ -49,7 +49,7 @@ 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\.$") +TOKENS = re.compile(r"^(\d+) new input tokens before the first commit\.$") WINDOW = 5 @@ -70,10 +70,12 @@ class Checkout: def main(argv: list[str]) -> int: reset = argv[:1] == ["--reset"] given = argv[1:] if reset else argv - if given[:1] in (["-h"], ["--help"]) or len(given) > 1 or given[:1] and given[0].startswith("-"): - helped = given[:1] in (["-h"], ["--help"]) and len(given) == 1 - print(__doc__.strip(), file=sys.stdout if helped else sys.stderr) - return 0 if helped else 1 + 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.py [--reset] [history]", file=sys.stderr) + return 1 checkout = located() if isinstance(checkout, Failure): return failed(checkout) @@ -85,7 +87,7 @@ def main(argv: list[str]) -> int: if isinstance(updated, Failure): return failed(updated) appended, readings = updated - print(f"Appended {appended} reading-cost figures from {archive}{' and a reset' if reset else ''} to {history}.") + print(f"Appended {appended} reading-cost figure{'' if appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {history}.") print(trend(readings)) return 0 @@ -233,7 +235,7 @@ def relative(path: str, roots: list[str]) -> str | None: def figure(chunk: FinishedChunk, reading: Reading) -> str: places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places)) - 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 "") + return f"## {HEADING}{chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\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. @@ -260,16 +262,15 @@ def merged(history: str, figures: list[str]) -> str: return history.rstrip("\n") + "\n\n" + "\n".join(figures) -# Medians, so one chunk that ran a panel of readers or waited out a usage limit does not decide the trend alone. def trend(readings: list[Reading]) -> str: if len(readings) < 2 * WINDOW: return f"{len(readings)} chunks measured; the trend needs {2 * WINDOW}." last, earlier = middle(readings[-WINDOW:]), middle(readings[-2 * WINDOW:-WINDOW]) - medians = f"the last {WINDOW} chunks' median is {last} tokens read before their first commit, the {WINDOW} before them {earlier}." + medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}." if last <= earlier: return f"Not rising: {medians}" read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter()))) - return f"Rising: {medians}\n\nRead most over the last {WINDOW}:\n{read_most}" + return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}" def middle(readings: list[Reading]) -> int: diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index a1008d68..21c673f0 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -73,16 +73,16 @@ class Figures(unittest.TestCase): def test_rises_only_above_the_five_before_and_needs_ten(self): flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10 self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured; the trend needs 10.") - self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 tokens")) + self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 new input tokens")) self.assertTrue(reading_cost.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:")) - self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 tokens read before their first commit, the 5 before them 100.\n\nRead most over the last 5:\n\n- `b.py` 10") + self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 new input tokens before their first commit, the 5 before them 100.\n\nRead most over the last 5 (opens and searches):\n\n- `b.py` 10") def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self): reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3})) written = reading_cost.figure(FinishedChunk("abcdef0123456789", "t", pathlib.Path(), []), reading) - self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished t\n\n7 tokens read before the first commit.\n\nRead most:\n\n- `a.py` 3\n- `b.py` 1\n") + self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished t\n\n7 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 3\n- `b.py` 1\n") self.assertEqual(reading_cost.readings_of(written), [reading]) - 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')) + self.assertEqual(reading_cost.readings_of(written.replace("7 new", "seven new")), 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): @@ -136,7 +136,7 @@ class ReadingCostTool(unittest.TestCase): self.assertEqual(ran.returncode, 0, ran.stderr) history = worktree / "docs" / "comprehension-history.md" self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured; the trend needs 10.\n") - figure = "## Reading cost, chunk {}, finished {}\n\n33 tokens read before the first commit.\n\nRead most:\n\n- `a.py` 1\n" + figure = "## Reading cost, chunk {}, finished {}\n\n33 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 1\n" 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 from")) self.assertEqual(history.read_text().count("## Reading cost"), 2) @@ -147,7 +147,6 @@ class ReadingCostTool(unittest.TestCase): def test_refuses_an_option_it_does_not_know(self): ran = self.run_tool(self.checkout, "--rest") self.assertEqual((ran.returncode, ran.stdout), (1, "")) - self.assertFalse((self.checkout / "--rest").exists()) def test_exits_1_outside_a_checkout(self): ran = self.run_tool(self.home) diff --git a/docs/decisions.md b/docs/decisions.md index e782646f..525780a1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -112,7 +112,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -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; `bin/reading_cost.py` instead measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 with its subagents' transcripts. +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; `bin/reading_cost.py` instead measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. ## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that only its own chunk or the human removes diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 0fb97ba3..a7fa4ab7 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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 medians and files as its detail; where the plan already holds it, refresh its detail instead. On exit 1, repair what its message names and run it again; ask the human when the message names no repair. 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. +**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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. It names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item and go on. 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 -- 2.52.0 From 5e5eea21e5d47bc0d0eab85f6fa57a3f446a34d5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:43:38 +0200 Subject: [PATCH 09/16] Answer product-owner round 1: keep the help's history path on one line --- bin/reading_cost.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/reading_cost.py b/bin/reading_cost.py index fc205697..c538d643 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -3,9 +3,9 @@ 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 project, -$LOOP_CLAUDE_TRANSCRIPTS/ (default ~/.claude/loop-claude-transcripts), being the +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 +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 history 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 -- 2.52.0 From 35907caefa23508effa9df420d346c25e801cc72 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:46:20 +0200 Subject: [PATCH 10/16] Answer prose round 1: mark the reading-cost item decision, split the rise rule's reasons, and say the trend counts since the last reset --- bin/reading_cost.py | 6 +++--- bin/shell_reads.py | 4 ++-- bin/test_reading_cost.py | 6 +++--- docs/decisions.md | 4 ++-- skills/larv-review/SKILL.md | 4 ++-- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/bin/reading_cost.py b/bin/reading_cost.py index c538d643..5e3d2267 100644 --- a/bin/reading_cost.py +++ b/bin/reading_cost.py @@ -20,8 +20,8 @@ It then compares the median tokens of the history's last 5 figures with the 5 be 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, when git cannot start or finds no checkout, the archive or the history cannot -be read or written, or a figure in the history cannot be read back. +Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the +archive or the history cannot be read or written, or a figure in the history cannot be read back. """ import collections import dataclasses @@ -264,7 +264,7 @@ def merged(history: str, figures: list[str]) -> str: def trend(readings: list[Reading]) -> str: if len(readings) < 2 * WINDOW: - return f"{len(readings)} chunks measured; the trend needs {2 * WINDOW}." + return f"{len(readings)} chunks measured since the last reset; the trend needs {2 * WINDOW}." last, earlier = middle(readings[-WINDOW:]), middle(readings[-2 * WINDOW:-WINDOW]) medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}." if last <= earlier: diff --git a/bin/shell_reads.py b/bin/shell_reads.py index 034129e8..268eb6f8 100644 --- a/bin/shell_reads.py +++ b/bin/shell_reads.py @@ -32,7 +32,7 @@ def shell_reads(command: str, cwd: str, home: str) -> Reads: def shell_lines(command: str) -> typing.Iterator[list[str]]: - """Each line's tokens, skipping a heredoc's body, which feeds a program rather than naming files.""" + """Each line's tokens, skipping a heredoc's body, which feeds a program.""" ends = None for line in command.splitlines(): if ends is not None: @@ -56,7 +56,7 @@ def segments(tokens: list[str]) -> list[list[str]]: if target: target = False elif all(char in "();<>|&" for char in token): - # A redirect's target is written or fed, not read by the command. + # A redirect's target is not an operand, so it does not count as a read. target = "<" in token or ">" in token found.append([]) else: diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 21c673f0..52e86d34 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -72,7 +72,7 @@ class Measure(unittest.TestCase): class Figures(unittest.TestCase): def test_rises_only_above_the_five_before_and_needs_ten(self): flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10 - self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured; the trend needs 10.") + self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured since the last reset; the trend needs 10.") self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 new input tokens")) self.assertTrue(reading_cost.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:")) self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 new input tokens before their first commit, the 5 before them 100.\n\nRead most over the last 5 (opens and searches):\n\n- `b.py` 10") @@ -135,13 +135,13 @@ class ReadingCostTool(unittest.TestCase): ran = self.run_tool(worktree) self.assertEqual(ran.returncode, 0, ran.stderr) history = worktree / "docs" / "comprehension-history.md" - self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured; the trend needs 10.\n") + self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured since the last reset; the trend needs 10.\n") figure = "## Reading cost, chunk {}, finished {}\n\n33 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 1\n" 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 from")) self.assertEqual(history.read_text().count("## Reading cost"), 2) reset = self.run_tool(worktree, "--reset") - self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} and a reset to {history}.\n0 chunks measured; the trend needs 10.\n") + self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} and a reset to {history}.\n0 chunks measured since the last reset; 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_refuses_an_option_it_does_not_know(self): diff --git a/docs/decisions.md b/docs/decisions.md index 525780a1..69785613 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -112,8 +112,8 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -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; `bin/reading_cost.py` instead measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. +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. So `bin/reading_cost.py` measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. ## reading cost: a rise is the last 5 chunks' median 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, 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). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. 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: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). The item is marked `decision`, so the bar does not drop it. A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index a7fa4ab7..200dd908 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. It names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item and go on. 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. +**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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items", marked `decision` since the reading-cost decision cites it, with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the one the plan holds, and go on. 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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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. +- **History.** `docs/comprehension-history.md` keeps every scoring run and reading-cost figure, appended and never edited, except as the merge-conflict rule below says. A run is a `## , at ` 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 `, hardest first:` or, for the architect, `, 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). 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. -- 2.52.0 From f35e525b9ca8064b8e182aa5d195722c578dd863 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:47:03 +0200 Subject: [PATCH 11/16] Answer prose round 2: score the reading-cost item like any other, and name the question item a failed run refreshes --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- docs/decisions.md | 6 +++--- skills/larv-review/SKILL.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5a408cbf..64e82ed7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ Decisions live in `docs/decisions.md`: - 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: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that only its own chunk or the human removes +- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that no later run deletes ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index e75766d4..7fbefa5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 new input 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. Once 10 chunks are measured, and the last 5 chunks' median 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 runs the new `bin/reading_cost.py`, which measures each chunk `loop-claude` finished from its archive: the new input 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. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it; a later run never deletes 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. diff --git a/docs/decisions.md b/docs/decisions.md index 69785613..57f26fb5 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -112,8 +112,8 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -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. So `bin/reading_cost.py` measures each finished chunk the history lacks from the archive, in the next chunk's worktree, so a PR that never merges loses no figure and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. +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. So `bin/reading_cost.py` measures each finished chunk the history lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. -## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that only its own chunk or the human removes +## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that no later run deletes -2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). The item is marked `decision`, so the bar does not drop it. A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. 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: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 200dd908..e0805cc2 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items", marked `decision` since the reading-cost decision cites it, with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the one the plan holds, and go on. 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. +**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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. 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 -- 2.52.0 From 1fc91a5535b76f8d7a2151bbe1251ce38b5ffd39 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 16:47:31 +0200 Subject: [PATCH 12/16] Answer prose round 3: drop the claim that no later run deletes the reading-cost item --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- docs/decisions.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64e82ed7..f4a59110 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ Decisions live in `docs/decisions.md`: - 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: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR -- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that no later run deletes +- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fbefa5a..613aedca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 new input 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. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it; a later run never deletes it. The chunk that ships it runs `reading_cost.py --reset`, so the trend counts only chunks that finished after it. +- larv-review runs the new `bin/reading_cost.py`, which measures each chunk `loop-claude` finished from its archive: the new input 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. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes 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. diff --git a/docs/decisions.md b/docs/decisions.md index 57f26fb5..934c1ece 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -114,6 +114,6 @@ lilleman decided to ship each of these under the floor on the day listed. Each l 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. So `bin/reading_cost.py` measures each finished chunk the history lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. -## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item that no later run deletes +## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item 2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk. -- 2.52.0 From 60353275f64a0850f7b83f5f85ad9f63d9465627 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 17:54:46 +0200 Subject: [PATCH 13/16] Answer architecture round 4: record the rescore, which fell under the ratchet on Locality and Shape --- docs/comprehension-history.md | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 36b343a5..9fe05bfe 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -160,3 +160,54 @@ Inherited architect, would restructure first: - `bin/` flat folder: tools, shared modules and tests - `bin/loop_claude/project/checkout.py:32` `read_utf8`, `claude_code/transcript.py:27` `render`, `judge_reply.py:87` `Verdict` beside `states.py:24` `ruling` - `bin/loop_claude/loop/main.py:9` the recorded-answers rule, beside `judge_reply.py:11` `ANSWERS_RECORDED` + +## 2026-10-08T15:54:46Z, PR #225 at 1fc91a5 + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Junior A | 7 | 6 | 6.5 | 6 | 6.5 | +| Mid A | 7 | 6.5 | 7 | 6.5 | 7 | +| Maintainability senior | 7.5 | 6.5 | 7 | 6.5 | 7 | +| Inherited architect | 7 | 6 | 6.5 | 7 | 6.5 | +| Mean | 7.13 | 6.25 | 6.75 | 6.50 | 6.75 | + +Junior A, hardest first: + +- `skills/larv-review/SKILL.md:53` "Round cap", through "Re-entry", "Fresh" and "Suspended" +- `bin/loop_claude/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` +- `bin/reading_cost.py:180` `measure` +- `bin/reading_cost.py:242` `readings_of`, with `:171` `unheld` and `:236` `figure` +- `bin/loop_claude/cycle/judge.py:31` `run_judge` +- `bin/loop_claude/transcript_archive.py:29` `archive`, with `copy_for` and `finished_chunks` +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES` +- `bin/rank_todo.py:408` `rank_details` + +Mid A, hardest first: + +- `skills/larv-review/SKILL.md:53` "Round cap", with "Architecture" from Floor to Suspended +- `bin/loop_claude/cycle/judge.py:31` `run_judge` +- `bin/loop_claude/cycle/states.py:69` `transition` +- `bin/reading_cost.py:180` `measure`, and `:242` `readings_of` +- `bin/loop_claude/transcript_archive.py:29` `archive`, `:95` `copy_for` and `:110` `finished_chunks` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` +- `bin/loop_claude/loop/reload.py:50` `exec_if_edited` +- `bin/rank_todo.py:408` `rank_details` + +Maintainability senior, hardest first: + +- `skills/larv-review/SKILL.md:79` "Architecture" +- `skills/larv-review/SKILL.md:95` the move of an old entry's scores into the history +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES` +- `bin/loop_claude/cycle/judge.py:31` `run_judge` +- `bin/reading_cost.py:180` `measure`, and `:242` `readings_of` +- `bin/loop_claude/transcript_archive.py:18` `FINISHED_AT`, with `finished_chunks` and `cycle/run.py:110` `close` +- `bin/reading_cost.py:141` `located`, beside `bin/loop_claude/project/checkout.py:7` `checkout_root` +- `bin/shell_reads.py:52` `segments`, and `:67` `operands` + +Inherited architect, would restructure first: + +- `bin/` by kind: tools, shared modules and tests +- `bin/loop_claude/transcript_archive.py:110` `finished_chunks`, read by `bin/reading_cost.py` through four `loop_claude` modules +- `docs/comprehension-history.md`, written by `bin/reading_cost.py:242` and by `skills/larv-review/SKILL.md:92`'s prose +- `skills/larv-review/SKILL.md:53` "Round cap" +- `bin/loop_claude/cycle/judge_reply.py:87` `Verdict` beside `states.py` `ruling`, and `project/checkout.py:32` `read_utf8` -- 2.52.0 From 946daf5e3fa5f803391bf1d2f49505f996599545 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 17:59:19 +0200 Subject: [PATCH 14/16] Answer architecture round 4: give the figures their own docs/reading-cost.md, and package the tool as bin/reading-cost with one module that reads loop-claude's archive --- .gitignore | 5 +- AGENTS.md | 2 +- CHANGELOG.md | 2 +- README.md | 2 +- bin/reading-cost | 9 + bin/reading_cost.py | 281 -------------------------- bin/reading_cost/__init__.py | 0 bin/reading_cost/archive.py | 20 ++ bin/reading_cost/figures.py | 68 +++++++ bin/reading_cost/main.py | 126 ++++++++++++ bin/reading_cost/measure.py | 80 ++++++++ bin/{ => reading_cost}/shell_reads.py | 0 bin/test_reading_cost.py | 36 ++-- bin/test_types.py | 2 +- docs/decisions.md | 4 +- skills/larv-review/SKILL.md | 6 +- todo.md | 4 +- 17 files changed, 335 insertions(+), 312 deletions(-) create mode 100755 bin/reading-cost delete mode 100644 bin/reading_cost.py create mode 100644 bin/reading_cost/__init__.py create mode 100644 bin/reading_cost/archive.py create mode 100644 bin/reading_cost/figures.py create mode 100644 bin/reading_cost/main.py create mode 100644 bin/reading_cost/measure.py rename bin/{ => reading_cost}/shell_reads.py (100%) diff --git a/.gitignore b/.gitignore index 1bfa6950..bcf6e1e2 100644 --- a/.gitignore +++ b/.gitignore @@ -25,8 +25,9 @@ !bin/loop_claude/**/*.py !bin/markdown_sections.py !bin/rank_todo.py -!bin/reading_cost.py -!bin/shell_reads.py +!bin/reading-cost +!bin/reading_cost/ +!bin/reading_cost/*.py !bin/statusline.py !bin/test_*.py !docs/ diff --git a/AGENTS.md b/AGENTS.md index f4a59110..40f17a90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,7 @@ 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: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR +- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR - reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 613aedca..00a4b450 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 new input 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. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading_cost.py --reset`, so the trend counts only chunks that finished after it. +- larv-review runs the new `bin/reading-cost`, which measures each chunk `loop-claude` finished from its archive: the new input 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/reading-cost.md` lacks. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading-cost --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. diff --git a/README.md b/README.md index ad898b4e..f55d6009 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit - `loop-claude ` 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 [--reset] [history]` appends a figure for each chunk `loop-claude` finished to a project's comprehension history, and says whether the figures rise; `reading_cost.py --help` states the measure. +- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --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'` diff --git a/bin/reading-cost b/bin/reading-cost new file mode 100755 index 00000000..9f370fb6 --- /dev/null +++ b/bin/reading-cost @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from reading_cost import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/reading_cost.py b/bin/reading_cost.py deleted file mode 100644 index 5e3d2267..00000000 --- a/bin/reading_cost.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/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 [--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 -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 history 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 history'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 history cannot be read or written, or a figure in the history cannot be read back. -""" -import collections -import dataclasses -import os -import pathlib -import re -import statistics -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, utc -from loop_claude.paths import paths_from -from loop_claude.project.checkout import project_key -from shell_reads import Reads, resolved, shell_reads -from file_writes import replace_file -from markdown_sections import sections - -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+) new input tokens before the first commit\.$") -WINDOW = 5 - - -@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] - - -@dataclasses.dataclass(frozen=True) -class Checkout: - root: str - top: str - tracked: frozenset[str] - - -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.py [--reset] [history]", file=sys.stderr) - return 1 - checkout = located() - if isinstance(checkout, Failure): - return failed(checkout) - home = pathlib.Path.home() - paths = paths_from(home, os.environ) - archive = paths.transcript_archive / project_key(checkout.root, paths.code) - history = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "comprehension-history.md") - updated = update(history, archive, checkout, str(home), utc(time.time()) if reset else None) - if isinstance(updated, Failure): - return failed(updated) - appended, readings = updated - print(f"Appended {appended} reading-cost figure{'' if appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {history}.") - print(trend(readings)) - return 0 - - -def update(history: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> tuple[int, list[Reading]] | Failure: - """How many figures it appended, and the readings the trend counts.""" - text = read_history(history) - 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_history(history, text)): - return unwritten - return len(figures), readings - - -def new_figures(history: 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, history): - 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_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 - - -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 checkout's .git, whichever worktree runs this. - return Checkout(str(pathlib.Path(common).parent), top, frozenset(filter(None, listed.stdout.split("\0")))) - - -def read_history(history: pathlib.Path) -> str | Failure: - try: - return history.read_text(encoding="utf-8") if history.exists() else "# Comprehension history\n" - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"could not read {history}: {failure}") - - -def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: - """The worker's transcript, then each subagent's.""" - try: - return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)] - except OSError as failure: - return Failure(f"could not read {failure.filename}: {failure.strerror}") - - -def unheld(chunks: list[FinishedChunk], history: str) -> list[FinishedChunk]: - held = {heading.removeprefix(HEADING).split(",")[0] for heading in sections(history) if heading.startswith(HEADING)} - return [chunk for chunk in chunks if chunk_id(chunk) not in held] - - -def chunk_id(chunk: FinishedChunk) -> str: - return chunk.folder[:12] - - -def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None: - worker, *subagents = [entries_of(thread) for thread in threads] - commit = commit_time(worker) - if commit is None: - return None - before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)] - reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)] - roots = [checkout.root, *(added for found in reads for added in found.added)] - places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked) - return Reading(sum(map(tokens_in, before)), places) - - -def entries_of(raw: bytes) -> list[dict]: - return [entry for line in raw.splitlines() if (entry := parse_entry(line))] - - -def commit_time(worker: list[dict]) -> str | None: - for entry in worker: - for part in assistant_parts(entry): - name, arguments = call_of(part) - if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))): - return str(entry.get("timestamp", "")) - return None - - -def tokens_in(entries: list[dict]) -> int: - # Claude Code writes one entry per content block of a message, each with the message's usage. - usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)} - 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 - - -def call_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 reads_of(part: object, cwd: str, home: str) -> Reads: - name, arguments = call_of(part) - path = arguments.get("file_path") if name == "Read" else arguments.get("path") if name == "Grep" else None - if path: - return Reads([resolved(cwd, str(path), home)], []) - return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], []) - - -# Relative to the deepest root holding it, so the checkout and each worktree name a file alike. -def relative(path: str, roots: list[str]) -> str | None: - holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")] - return path[len(max(holding, key=len).rstrip("/")) + 1:] if holding else None - - -def figure(chunk: FinishedChunk, reading: Reading) -> str: - places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places)) - return f"## {HEADING}{chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\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: - dated = [] - resets = [""] - for heading, bodies in sections(history).items(): - 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") - 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]]: - return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT] - - -def merged(history: str, figures: list[str]) -> str: - return history.rstrip("\n") + "\n\n" + "\n".join(figures) - - -def trend(readings: list[Reading]) -> str: - if len(readings) < 2 * WINDOW: - return f"{len(readings)} chunks measured since the last reset; the trend needs {2 * WINDOW}." - last, earlier = middle(readings[-WINDOW:]), middle(readings[-2 * WINDOW:-WINDOW]) - medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}." - if last <= earlier: - return f"Not rising: {medians}" - read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter()))) - return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}" - - -def middle(readings: list[Reading]) -> int: - return round(statistics.median(reading.tokens for reading in readings)) - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) diff --git a/bin/reading_cost/__init__.py b/bin/reading_cost/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/reading_cost/archive.py b/bin/reading_cost/archive.py new file mode 100644 index 00000000..f2f01328 --- /dev/null +++ b/bin/reading_cost/archive.py @@ -0,0 +1,20 @@ +import pathlib +import typing + +from failure import Failure +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 + + +def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path: + paths = paths_from(home, env) + return paths.transcript_archive / project_key(checkout_root, paths.code) + + +def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: + """The worker's transcript, then each subagent's.""" + try: + return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)] + except OSError as failure: + return Failure(f"could not read {failure.filename}: {failure.strerror}") diff --git a/bin/reading_cost/figures.py b/bin/reading_cost/figures.py new file mode 100644 index 00000000..03a7b69f --- /dev/null +++ b/bin/reading_cost/figures.py @@ -0,0 +1,68 @@ +import collections +import re +import statistics + +from failure import Failure +from reading_cost.archive import FinishedChunk +from reading_cost.measure import Reading +from markdown_sections import sections + +HEADING = "Reading cost, chunk " +PLACE = re.compile(r"^- `(.+)` (\d+)$") +PLACES_KEPT = 10 +RESET = "Reading cost reset, " +TOKENS = re.compile(r"^(\d+) new input tokens before the first commit\.$") +WINDOW = 5 + + +def unheld(chunks: list[FinishedChunk], record: str) -> list[FinishedChunk]: + held = {heading.removeprefix(HEADING).split(",")[0] for heading in sections(record) if heading.startswith(HEADING)} + return [chunk for chunk in chunks if chunk_id(chunk) not in held] + + +def chunk_id(chunk: FinishedChunk) -> str: + return chunk.folder[:12] + + +def figure(chunk: FinishedChunk, reading: Reading) -> str: + places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places)) + return f"## {HEADING}{chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\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(record: str) -> list[Reading] | Failure: + dated = [] + resets = [""] + for heading, bodies in sections(record).items(): + 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") + 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]]: + return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT] + + +def merged(record: str, figures: list[str]) -> str: + return record.rstrip("\n") + "\n\n" + "\n".join(figures) + + +def trend(readings: list[Reading]) -> str: + if len(readings) < 2 * WINDOW: + return f"{len(readings)} chunks measured since the last reset; the trend needs {2 * WINDOW}." + last, earlier = median_tokens(readings[-WINDOW:]), median_tokens(readings[-2 * WINDOW:-WINDOW]) + medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}." + if last <= earlier: + return f"Not rising: {medians}" + read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter()))) + return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}" + + +def median_tokens(readings: list[Reading]) -> int: + return round(statistics.median(reading.tokens for reading in readings)) diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py new file mode 100644 index 00000000..7530fe34 --- /dev/null +++ b/bin/reading_cost/main.py @@ -0,0 +1,126 @@ +"""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 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, RESET, trend, unheld +from reading_cost.archive import finished_chunks, project_archive, read_threads, utc +from file_writes import replace_file + +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.root, home, os.environ) + record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "reading-cost.md") + updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None) + if isinstance(updated, Failure): + return failed(updated) + appended, readings = updated + print(f"Appended {appended} reading-cost figure{'' if appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record}.") + print(trend(readings)) + return 0 + + +def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> tuple[int, list[Reading]] | Failure: + """How many figures it appended, and the readings the trend counts.""" + 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 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 checkout's .git, whichever worktree runs this. + return Checkout(str(pathlib.Path(common).parent), top, 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}") diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py new file mode 100644 index 00000000..226ee692 --- /dev/null +++ b/bin/reading_cost/measure.py @@ -0,0 +1,80 @@ +import collections +import dataclasses +import re + +from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call +from reading_cost.shell_reads import Reads, resolved, shell_reads + +COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b") + + + +@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] + + + +@dataclasses.dataclass(frozen=True) +class Checkout: + root: str + top: str + tracked: frozenset[str] + + +def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None: + worker, *subagents = [entries_of(thread) for thread in threads] + commit = commit_time(worker) + if commit is None: + return None + before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)] + reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)] + roots = [checkout.root, *(added for found in reads for added in found.added)] + places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked) + return Reading(sum(map(tokens_in, before)), places) + + +def entries_of(raw: bytes) -> list[dict]: + return [entry for line in raw.splitlines() if (entry := parse_entry(line))] + + +def commit_time(worker: list[dict]) -> str | None: + for entry in worker: + for part in assistant_parts(entry): + name, arguments = call_of(part) + if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))): + return str(entry.get("timestamp", "")) + return None + + +def tokens_in(entries: list[dict]) -> int: + # Claude Code writes one entry per content block of a message, each with the message's usage. + usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)} + 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 + + +def call_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 reads_of(part: object, cwd: str, home: str) -> Reads: + name, arguments = call_of(part) + path = arguments.get("file_path") if name == "Read" else arguments.get("path") if name == "Grep" else None + if path: + return Reads([resolved(cwd, str(path), home)], []) + return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], []) + + +# Relative to the deepest root holding it, so the checkout and each worktree name a file alike. +def relative(path: str, roots: list[str]) -> str | None: + holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")] + return path[len(max(holding, key=len).rstrip("/")) + 1:] if holding else None diff --git a/bin/shell_reads.py b/bin/reading_cost/shell_reads.py similarity index 100% rename from bin/shell_reads.py rename to bin/reading_cost/shell_reads.py diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 52e86d34..0e7db0e5 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -13,14 +13,14 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude.transcript_archive import archive, FINISHED, FINISHED_AT, finished_chunks, FinishedChunk, UNFINISHED, utc -from reading_cost import Checkout, Reading +from reading_cost.measure import Checkout, Reading from failure import Failure +from reading_cost import figures, measure from test_loop_claude_black_box import host_env from loop_claude.paths import paths_from -import reading_cost -from shell_reads import Reads, shell_reads +from reading_cost.shell_reads import Reads, shell_reads -TOOL = pathlib.Path(__file__).resolve().parent / "reading_cost.py" +TOOL = pathlib.Path(__file__).resolve().parent / "reading-cost" def said(timestamp, message_id, command=None, tokens=0, cwd="/c/p", **call): @@ -60,36 +60,36 @@ class Measure(unittest.TestCase): ] subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "/c/w/src/a.py"}), said("7", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})] checkout = Checkout("/c/p", "/c/w", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"})) - self.assertEqual(reading_cost.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1}))) + self.assertEqual(measure.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1}))) def test_measures_nothing_for_a_worker_that_never_committed(self): - self.assertIsNone(reading_cost.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) + self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) def test_skips_a_usage_that_is_not_a_count(self): - self.assertEqual(reading_cost.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2) + self.assertEqual(measure.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2) class Figures(unittest.TestCase): def test_rises_only_above_the_five_before_and_needs_ten(self): flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10 - self.assertEqual(reading_cost.trend(flat[:9]), "9 chunks measured since the last reset; the trend needs 10.") - self.assertTrue(reading_cost.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 new input tokens")) - self.assertTrue(reading_cost.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:")) - self.assertEqual(reading_cost.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 new input tokens before their first commit, the 5 before them 100.\n\nRead most over the last 5 (opens and searches):\n\n- `b.py` 10") + self.assertEqual(figures.trend(flat[:9]), "9 chunks measured since the last reset; the trend needs 10.") + self.assertTrue(figures.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 new input tokens")) + self.assertTrue(figures.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:")) + self.assertEqual(figures.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 new input tokens before their first commit, the 5 before them 100.\n\nRead most over the last 5 (opens and searches):\n\n- `b.py` 10") def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self): reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3})) - written = reading_cost.figure(FinishedChunk("abcdef0123456789", "t", pathlib.Path(), []), reading) + written = figures.figure(FinishedChunk("abcdef0123456789", "t", pathlib.Path(), []), reading) self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished t\n\n7 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 3\n- `b.py` 1\n") - self.assertEqual(reading_cost.readings_of(written), [reading]) - self.assertEqual(reading_cost.readings_of(written.replace("7 new", "seven new")), Failure('the figure under "## Reading cost, chunk abcdef012345, finished t" holds no single tokens line; restore it from git history')) + self.assertEqual(figures.readings_of(written), [reading]) + self.assertEqual(figures.readings_of(written.replace("7 new", "seven new")), 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())) + return figures.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())]) + self.assertEqual(figures.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) @@ -134,10 +134,10 @@ class ReadingCostTool(unittest.TestCase): self.git("worktree", "add", "-q", str(worktree)) ran = self.run_tool(worktree) self.assertEqual(ran.returncode, 0, ran.stderr) - history = worktree / "docs" / "comprehension-history.md" + history = worktree / "docs" / "reading-cost.md" self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured since the last reset; the trend needs 10.\n") figure = "## Reading cost, chunk {}, finished {}\n\n33 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 1\n" - self.assertEqual(history.read_text(), "# Comprehension history\n\n" + "\n".join(figure.format(chunk.folder[:12], chunk.finished) for chunk in chunks)) + self.assertEqual(history.read_text(), "# Reading cost\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 from")) self.assertEqual(history.read_text().count("## Reading cost"), 2) reset = self.run_tool(worktree, "--reset") diff --git a/bin/test_types.py b/bin/test_types.py index 18a7bbb4..f626d4cb 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -11,5 +11,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-m", "reading_cost", "-m", "shell_reads", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index 934c1ece..6291d557 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -110,9 +110,9 @@ lilleman decided to ship each of these under the floor on the day listed. Each l 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: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/comprehension-history.md` in the next chunk's PR +## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR -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. So `bin/reading_cost.py` measures each finished chunk the history lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. +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. So `bin/reading-cost` measures each finished chunk `docs/reading-cost.md` lacks from the archive, in the next chunk's worktree. The figures keep a file of their own, so `docs/comprehension-history.md` keeps one writer, the scoring run. A PR that never merges then loses no figure, and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. ## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index e0805cc2..8ff82132 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -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.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. 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. +**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files chunks read most before their first commit.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. 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 and reading-cost figure, appended and never edited, except as the merge-conflict rule below says. A run is a `## , at ` 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 `, hardest first:` or, for the architect, `, 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). 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 `## , at ` 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 `, hardest first:` or, for the architect, `, 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. - **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. @@ -105,7 +105,7 @@ Fix the places the seats name under the lowest dimension and under each dimensio Put each run's five scores in the summary, and append the run to the history on this branch. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`). -**Fresh.** Where the chunk ran a scoring run, the architecture pass is done only once its last scoring run measured the commit to merge. That run may predate commits that change only `docs/decisions.md`, `docs/comprehension-history.md`, `todo.md` or `CHANGELOG.md`. Any other commit after it, a prose fix included, because the seats read the docs, calls for a rescore: the scoring run again, once every other pass is done, the auto-reviewer included. A rescore reporting a 🔴 that no decision to ship answers is an architecture round. Any other rescore is not a round: append only its run to the history, in a commit titled `Rescore: …`. A `Rescore:` commit re-enters no pass: push it and wait for the forge's checks (§4 step 3), not for an auto-review. +**Fresh.** Where the chunk ran a scoring run, the architecture pass is done only once its last scoring run measured the commit to merge. That run may predate commits that change only `docs/decisions.md`, `docs/comprehension-history.md`, `docs/reading-cost.md`, `todo.md` or `CHANGELOG.md`. Any other commit after it, a prose fix included, because the seats read the docs, calls for a rescore: the scoring run again, once every other pass is done, the auto-reviewer included. A rescore reporting a 🔴 that no decision to ship answers is an architecture round. Any other rescore is not a round: append only its run to the history, in a commit titled `Rescore: …`. A `Rescore:` commit re-enters no pass: push it and wait for the forge's checks (§4 step 3), not for an auto-review. **Suspended.** A decision in the project's `docs/decisions.md`, held before the chunk began, may name plan items to ship without a scoring run. A named item counts as `todo.md` worded it before the chunk began. The decision must name the later plan item whose chunk ends the suspension with a scoring run. A chunk may ship named items only with each other. Such a chunk skips the scoring run, so neither the floor nor the ratchet can block it, and its summary cites the decision. A chunk shipping its release's last item runs the scoring run, even when every item it ships is named. diff --git a/todo.md b/todo.md index 03996a80..162efd2e 100644 --- a/todo.md +++ b/todo.md @@ -121,7 +121,7 @@ Raised by the architect on PR #225 and by the inherited architect of PR #224's s The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. -`bin/reading_cost.py` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading_cost.py` never looks. Derive both keys one way. +`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way. ### 67. Point stability-reviewer at the technical principles in place of its own restatement of them. @@ -169,7 +169,7 @@ Claude Code owns that file and writes it. `trust` reads it, changes it and write ### 4. Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran. -Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading_cost.py` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id the history holds, so give it a way to match a figure written under the old name. +Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading-cost` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id `docs/reading-cost.md` holds, so give it a way to match a figure written under the old name. ### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in. -- 2.52.0 From 8c9bf090f1acd71894545c06bf87939b583339fe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 18:02:03 +0200 Subject: [PATCH 15/16] Answer architecture round 4: anchor the record's headings to a UTC stamp, import the archive's names from their owner, keep docs/reading-cost.md out of the panel's reading, and order the decision's reasons --- CHANGELOG.md | 2 +- bin/loop_claude/transcript_archive.py | 3 ++- bin/reading_cost/archive.py | 2 +- bin/reading_cost/figures.py | 21 ++++++++++++--------- bin/reading_cost/main.py | 20 +++++++++++++------- bin/test_reading_cost.py | 9 ++++++--- docs/decisions.md | 2 +- skills/comprehension-panel/scoring-run.md | 2 +- todo.md | 2 +- 9 files changed, 38 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00a4b450..966255ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ - larv-review runs the new `bin/reading-cost`, which measures each chunk `loop-claude` finished from its archive: the new input 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/reading-cost.md` lacks. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading-cost --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. +- 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`, `docs/reading-cost.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. - larv-review skips the comprehension scoring run for a chunk whose plan items a project decision names. The decision also names the later item whose scoring run ends the suspension. Neither the comprehension floor nor the ratchet can block a skipped chunk, its summary cites the decision, and a chunk shipping its release's last item is always measured. - README → Install and Update give the commands that check the latest tag out into `~/.claude`: on a new machine, whether or not Claude Code has already created the directory, and on one already on an older tag. - A session commits changes Claude Code made to `settings.json` only once their diff holds no credential, and asks you to move any credential out of the file first. diff --git a/bin/loop_claude/transcript_archive.py b/bin/loop_claude/transcript_archive.py index f9ce9919..fbbc69fe 100644 --- a/bin/loop_claude/transcript_archive.py +++ b/bin/loop_claude/transcript_archive.py @@ -15,7 +15,8 @@ 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) +STAMPED = r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ" +FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE) @dataclasses.dataclass(frozen=True) diff --git a/bin/reading_cost/archive.py b/bin/reading_cost/archive.py index f2f01328..d19ce9f1 100644 --- a/bin/reading_cost/archive.py +++ b/bin/reading_cost/archive.py @@ -2,7 +2,7 @@ import pathlib import typing from failure import Failure -from loop_claude.transcript_archive import finished_chunks, FinishedChunk, utc +from loop_claude.transcript_archive import FinishedChunk from loop_claude.paths import paths_from from loop_claude.project.checkout import project_key diff --git a/bin/reading_cost/figures.py b/bin/reading_cost/figures.py index 03a7b69f..aaeccc1a 100644 --- a/bin/reading_cost/figures.py +++ b/bin/reading_cost/figures.py @@ -3,20 +3,21 @@ import re import statistics from failure import Failure -from reading_cost.archive import FinishedChunk +from loop_claude.transcript_archive import FinishedChunk, STAMPED from reading_cost.measure import Reading from markdown_sections import sections -HEADING = "Reading cost, chunk " +FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$") PLACE = re.compile(r"^- `(.+)` (\d+)$") PLACES_KEPT = 10 RESET = "Reading cost reset, " +RESET_AT = re.compile(rf"^{RESET}({STAMPED})$") TOKENS = re.compile(r"^(\d+) new input tokens before the first commit\.$") WINDOW = 5 def unheld(chunks: list[FinishedChunk], record: str) -> list[FinishedChunk]: - held = {heading.removeprefix(HEADING).split(",")[0] for heading in sections(record) if heading.startswith(HEADING)} + held = {match.group(1) for heading in sections(record) if (match := FIGURE.match(heading))} return [chunk for chunk in chunks if chunk_id(chunk) not in held] @@ -26,7 +27,7 @@ def chunk_id(chunk: FinishedChunk) -> str: def figure(chunk: FinishedChunk, reading: Reading) -> str: places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places)) - return f"## {HEADING}{chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{places}" if places else "") + return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\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. @@ -34,15 +35,17 @@ def readings_of(record: str) -> list[Reading] | Failure: dated = [] resets = [""] for heading, bodies in sections(record).items(): - if heading.startswith(RESET): - resets.append(heading.removeprefix(RESET)) - elif heading.startswith(HEADING): + if reset := RESET_AT.match(heading): + resets.append(reset.group(1)) + elif named := FIGURE.match(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") - 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)] + dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := PLACE.match(line))})))) + elif heading.startswith("Reading cost"): + return Failure(f"\"## {heading}\" names no chunk and UTC time, or no reset time; restore it from git history") + return [reading for finished, _, reading in sorted(dated, key=lambda item: item[:2]) if finished > max(resets)] def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]: diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py index 7530fe34..087210da 100644 --- a/bin/reading_cost/main.py +++ b/bin/reading_cost/main.py @@ -22,6 +22,7 @@ lists the files the last 5 chunks read most. With fewer than 10 figures, it says 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 @@ -31,9 +32,16 @@ import time from reading_cost.measure import Checkout, measure, Reading from failure import Failure from reading_cost.figures import figure, merged, readings_of, RESET, trend, unheld -from reading_cost.archive import finished_chunks, project_archive, read_threads, utc +from loop_claude.transcript_archive import finished_chunks, utc +from reading_cost.archive import project_archive, read_threads from file_writes import replace_file +@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 @@ -52,14 +60,12 @@ def main(argv: list[str]) -> int: updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None) if isinstance(updated, Failure): return failed(updated) - appended, readings = updated - print(f"Appended {appended} reading-cost figure{'' if appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record}.") - print(trend(readings)) + 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) -> tuple[int, list[Reading]] | Failure: - """How many figures it appended, and the readings the trend counts.""" +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 @@ -73,7 +79,7 @@ def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home return readings if marks and (unwritten := write_record(record, text)): return unwritten - return len(figures), readings + return Updated(len(figures), readings) def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure: diff --git a/bin/test_reading_cost.py b/bin/test_reading_cost.py index 0e7db0e5..5a1a6990 100644 --- a/bin/test_reading_cost.py +++ b/bin/test_reading_cost.py @@ -79,10 +79,13 @@ class Figures(unittest.TestCase): def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self): reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3})) - written = figures.figure(FinishedChunk("abcdef0123456789", "t", pathlib.Path(), []), reading) - self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished t\n\n7 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 3\n- `b.py` 1\n") + written = figures.figure(FinishedChunk("abcdef0123456789", "2026-10-08T00:00:00Z", pathlib.Path(), []), reading) + self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished 2026-10-08T00:00:00Z\n\n7 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 3\n- `b.py` 1\n") self.assertEqual(figures.readings_of(written), [reading]) - self.assertEqual(figures.readings_of(written.replace("7 new", "seven new")), Failure('the figure under "## Reading cost, chunk abcdef012345, finished t" holds no single tokens line; restore it from git history')) + self.assertEqual(figures.readings_of(written.replace("7 new", "seven new")), Failure('the figure under "## Reading cost, chunk abcdef012345, finished 2026-10-08T00:00:00Z" holds no single tokens line; restore it from git history')) + for damaged in (written.replace(", finished", ""), "## Reading cost reset, x\n"): + with self.subTest(damaged=damaged): + self.assertIsInstance(figures.readings_of(damaged), Failure) def test_counts_only_figures_finished_after_the_last_reset_in_the_order_they_finished(self): diff --git a/docs/decisions.md b/docs/decisions.md index 6291d557..8e975411 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -112,7 +112,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR -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. So `bin/reading-cost` measures each finished chunk `docs/reading-cost.md` lacks from the archive, in the next chunk's worktree. The figures keep a file of their own, so `docs/comprehension-history.md` keeps one writer, the scoring run. A PR that never merges then loses no figure, and loop-claude needs no change. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. +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. So `bin/reading-cost` measures each finished chunk `docs/reading-cost.md` lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. The figures keep a file of their own, so `docs/comprehension-history.md` keeps one writer, the scoring run. Serves goal 4 by naming only files git tracks, and token counts. 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 new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts. ## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item diff --git a/skills/comprehension-panel/scoring-run.md b/skills/comprehension-panel/scoring-run.md index eda4f4e5..7ab5c3b5 100644 --- a/skills/comprehension-panel/scoring-run.md +++ b/skills/comprehension-panel/scoring-run.md @@ -27,7 +27,7 @@ You are one seat of a comprehension panel. Tools: Read, Grep, Glob, and Bash onl ``` Target: the project checked out at {checkout} (branch `{branch}`). Read ONLY there — never {main}, which is a different version. -Depth 1, the whole project: read README.md, AGENTS.md and CLAUDE.md (the charter), then every non-test tracked file: {files}. Do NOT open todo.md, docs/decisions.md or docs/comprehension-history.md (the plan, the decision log and past panels' scores), nor any review output. You may open a test file when the code does not answer a question; say when you did. +Depth 1, the whole project: read README.md, AGENTS.md and CLAUDE.md (the charter), then every non-test tracked file: {files}. Do NOT open todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' scores and past chunks' reading cost), nor any review output. You may open a test file when the code does not answer a question; say when you did. Your harness pre-loads these files into your context before your first tool call, from a DIFFERENT version (main): {preloaded}. Treat the worktree's own copies as the ones under review. A pre-loaded AGENTS.md may list decision titles; do not use them as evidence. diff --git a/todo.md b/todo.md index 162efd2e..fb1e5daf 100644 --- a/todo.md +++ b/todo.md @@ -115,7 +115,7 @@ Raised by the principles audit of PR #224. The `settings.json` decision is valid ### 83. Group `bin/` by tool, so each tool's modules and tests sit together. -Raised by the architect on PR #225 and by the inherited architect of PR #224's scoring run: `bin/` is one flat folder of tools, the modules they share and the repo's checks, with `loop_claude`'s tests beside them instead of beside the package. +Raised by the architect on PR #225 and by the inherited architect of PR #224's scoring run: `bin/` is one flat folder of tools, the modules they share and the repo's checks, with `loop_claude`'s tests beside them instead of beside the package. `loop_claude/claude_code/` parses Claude Code's own formats and `bin/reading_cost/measure.py` imports it too, so it is a package of its own. ### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key. -- 2.52.0 From c7333c05eef0a0ad86bec5dccd5485b95e1e523d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 19:29:52 +0200 Subject: [PATCH 16/16] Rescore: PR #225 passes the ratchet; lilleman ships it under the floor --- docs/comprehension-history.md | 51 +++++++++++++++++++++++++++++++++++ docs/decisions.md | 1 + todo.md | 2 ++ 3 files changed, 54 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 9fe05bfe..1f8fe617 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -211,3 +211,54 @@ Inherited architect, would restructure first: - `docs/comprehension-history.md`, written by `bin/reading_cost.py:242` and by `skills/larv-review/SKILL.md:92`'s prose - `skills/larv-review/SKILL.md:53` "Round cap" - `bin/loop_claude/cycle/judge_reply.py:87` `Verdict` beside `states.py` `ruling`, and `project/checkout.py:32` `read_utf8` + +## 2026-10-08T17:29:52Z, PR #225 at 8c9bf09 + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Junior A | 7 | 6.5 | 7 | 6.5 | 6.5 | +| Mid A | 7 | 7 | 7 | 6.5 | 7 | +| Maintainability senior | 7.5 | 6.5 | 7 | 7 | 7 | +| Inherited architect | 7.5 | 7 | 7 | 7.5 | 7 | +| Mean | 7.25 | 6.75 | 7.00 | 6.88 | 6.88 | + +Junior A, hardest first: + +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES`, with `Reply` and `verdict_from` +- `bin/loop_claude/cycle/judge.py:31` `run_judge`, with `grounded`, `verbatim` and `plain` +- `bin/loop_claude/cycle/states.py:69` `transition` +- `bin/loop_claude/transcript_archive.py:30` `archive`, `copy_for` and `finished_chunks` +- `bin/reading_cost/measure.py:27` `measure`, with `bin/reading_cost/main.py:113` `located` +- `skills/larv-review/SKILL.md:95` the old entry's scores, and `:108` "Fresh" +- `bin/reading_cost/shell_reads.py:21` `shell_reads`, with `operands`, `segments` and `shell_lines` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` + +Mid A, hardest first: + +- `skills/larv-review/SKILL.md:53` "Round cap", through "Architecture", "Fresh" and "Suspended" +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES`, and `:90` `verdict_from` +- `bin/loop_claude/cycle/states.py:69` `transition`, with `cycle/run.py:35` `run_cycle` and `:104` `question_for` +- `bin/loop_claude/transcript_archive.py:30` `archive`, `copy_for` and `finished_chunks` +- `bin/loop_claude/claude_code/entries.py:28` `written_by_human` +- `bin/reading_cost/figures.py:34` `readings_of` +- `bin/reading_cost/shell_reads.py:52` `segments`, and `:67` `operands` +- `bin/reading_cost/main.py:113` `located`, beside `bin/loop_claude/project/checkout.py:7` `checkout_root` + +Maintainability senior, hardest first: + +- `bin/loop_claude/transcript_archive.py:30` `archive`, and `:111` `finished_chunks` +- `bin/reading_cost/figures.py:34` `readings_of` +- `bin/reading_cost/shell_reads.py:52` `segments`, and `:67` `operands` +- `bin/loop_claude/cycle/judge.py:31` `run_judge` +- `bin/reading_cost/main.py:113` `located`, and `measure.py:21` `Checkout` +- `skills/larv-review/SKILL.md:53` "Round cap", and `:108` "Fresh" and "Suspended" +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES` +- `bin/rank_todo.py:408` `rank_details` + +Inherited architect, would restructure first: + +- `bin/loop_claude/claude_code/` and the read side of `bin/loop_claude/transcript_archive.py`, into a package both tools import +- `skills/larv-review/SKILL.md:58` "Count", with a checker +- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES`, beside `judge.py:53` `judge_prompt` +- `bin/loop_claude/project/checkout.py:7` `checkout_root` and `bin/reading_cost/main.py:113` `located`, and `checkout.py:32` `read_utf8` +- `bin/failure.py`, `bin/file_writes.py` and `bin/markdown_sections.py`, into one package diff --git a/docs/decisions.md b/docs/decisions.md index 8e975411..50712341 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -49,6 +49,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l - 2026-10-03, PR #208: 7.5, 7.0, 7.13, 6.63, 6.88. - 2026-10-04, PR #215: 7.38, 6.63, 7.0, 6.88, 6.88. - 2026-10-08, PR #224: 7.00, 6.50, 7.00, 6.50, 6.75. lilleman shipped it below the ratchet as well: its 20 lines of skill prose left the code as it was, so the fall is the panel's noise between runs, which `todo.md` item 75 addresses. +- 2026-10-08, PR #225: 7.25, 6.75, 7.00, 6.88, 6.88. Above PR #224's run on every score but Shape, which held. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes diff --git a/todo.md b/todo.md index fb1e5daf..89904fcd 100644 --- a/todo.md +++ b/todo.md @@ -91,6 +91,8 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 1.1: the `comprehension floor:` entry in `docs/decisions.md` lists seven decisions to ship under the floor, and 0.1.0 waits on the floor. PR #215's last run put Locality at 6.63 and Self-sufficiency and the overall at 6.88. Its seats named, under Locality: the judge's contract spread over `cycle/judge_reply.py`, `cycle/worker.py` and `cycle/run.py`; `remaining`, which is `Unfinished.evidence` under another name, threaded through `loop/main.py`, `loop/reload.py`'s `LoopRun`, `cycle/run.py` and `worker_args`; the `quoted_answers` cap held by case order in `cycle/states.py`'s `transition` and restated in `run.py`'s `question_for`; the four outcome texts `run.py` builds inline for `archive`. Under Self-sufficiency: `skills/larv-review/SKILL.md`, which needs `CLAUDE.md` → "Vocabulary" open beside it; the archive layout, defined only in `bin/loop_claude/loop/main.py`'s docstring and not at `transcript_archive.py`; `JUDGE_RULES`' precedence in `cycle/judge_reply.py`, restated by `verdict_from`'s branch order and the `Reply` field descriptions; the `sys.path` insert in `bin/loop-claude` that the `from failure import` lines rely on, unstated at the import sites. +PR #225's last run, at 8c9bf09, put Locality at 6.75 and Self-sufficiency and the overall at 6.88. Its seats named: the judge's policy spread over `loop/main.py`'s docstring, `cycle/judge_reply.py`'s `JUDGE_RULES`, `cycle/judge.py`'s `judge_prompt` and `cycle/worker.py`'s `worker_args`; `loop_claude/claude_code/` and the read side of `transcript_archive.py`, which `bin/reading_cost/` also imports; two meanings of a checkout's root in `project/checkout.py`'s `checkout_root` and `reading_cost/main.py`'s `located`; and `skills/larv-review/SKILL.md` §3's round count, which only prose enforces. + ### 21. Give `settings.json`'s model one writer, and sort its keys. Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. -- 2.52.0