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