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

This commit is contained in:
2026-10-08 16:40:26 +02:00
parent 24efce674c
commit 5062a97158
6 changed files with 45 additions and 35 deletions
+26 -22
View File
@@ -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/<key> (default ~/.claude/loop-claude-transcripts), <key> 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 <id>, finished <UTC time>" heading, in the
@@ -16,8 +16,8 @@ order the chunks finished.
--reset also appends a "## Reading cost reset, <UTC time>" heading: the trend then counts only
figures of chunks that finished after it.
It then compares the mean tokens of the history's last 5 figures with the 5 before them, in the
order their chunks finished, and prints "Rising:" or "Not rising:" with both means. Rising, it
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__":
+14 -8
View File
@@ -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)