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

This commit is contained in:
2026-10-08 15:40:43 +02:00
parent cefb297e14
commit 1b8142e7e5
14 changed files with 400 additions and 12 deletions
+43 -2
View File
@@ -1,4 +1,5 @@
import ast
import collections
import contextlib
import dataclasses
import hashlib
@@ -16,7 +17,7 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker
from loop_claude.cycle import archive, interrupt, judge, reading_cost, retry, run, states, worker
from loop_claude.project import checkout, model_choice, records
from loop_claude.effects import Effects
from loop_claude.claude_code import entries, session, transcript, trust
@@ -188,6 +189,24 @@ class Cycles(unittest.TestCase):
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_a_finished_chunk_that_committed_keeps_its_reading_cost_once(self):
def committing(args):
Worker(self.paths.claude_code_transcripts.parent)(args)
with open(session.transcript_file(self.session), "a") as handle:
handle.write(json.dumps({**assistant({"type": "tool_use", "name": "Bash", "input": {"command": "git commit -m x"}}), "timestamp": "9"}) + "\n")
return Streamed(0)
fake = FakeEffects(streams=[committing], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
[kept] = (self.paths.transcript_archive / "proj").glob("reading-cost.md")
self.assertRegex(kept.read_text(), r"^## Reading cost, chunk [0-9a-f]{12}, finished 2026-09-21T14:13:20Z\n\n0 tokens read before the first commit\.\n$")
self.assertIsNone(reading_cost.keep_reading(kept, kept.read_text()))
self.assertEqual(len(reading_cost.blocks(kept.read_text())), 1)
def test_a_finished_chunk_that_never_committed_keeps_no_reading_cost(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
self.assertFalse((self.paths.transcript_archive / "proj" / "reading-cost.md").exists())
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
@@ -424,6 +443,28 @@ class Records(unittest.TestCase):
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
class ReadingCost(unittest.TestCase):
def test_counts_each_message_once_and_the_projects_files_read_before_the_first_commit(self):
def said(timestamp, message_id, command=None, tokens=0, **call):
part = {"type": "tool_use", "name": "Bash", "input": {"command": command}} if command else {"type": "tool_use", **call}
return {"type": "assistant", "timestamp": timestamp, "cwd": "/c/p", "message": {"id": message_id, "content": [part], "usage": {"input_tokens": tokens, "cache_creation_input_tokens": 2 * tokens, "cache_read_input_tokens": 1000}}}
worker = [
said("1", "m1", tokens=10, name="Read", input={"file_path": "/c/p/README.md"}),
said("2", "m1", tokens=10, name="Read", input={"file_path": "/tmp/log.txt"}),
said("3", "m2", command="cd ../w && sed -n 1,5p src/a.py | grep -n x\ngrep -rn 'def x' bin/t.py > out.txt\npython3 - <<'EOF'\ncat secret.py\nEOF\ncat README.md"),
said("4", "m3", command="git -C ../w commit -m 'x'", tokens=100),
said("5", "m4", tokens=100, name="Read", input={"file_path": "/c/p/late.py"}),
]
subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "src/a.py", "pattern": "x"}), said("6", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})]
lines = lambda entries: b"".join(json.dumps(entry).encode() + b"\n" for entry in entries)
reading = reading_cost.measure(lines(worker), [lines(subagent)])
self.assertEqual(reading, reading_cost.Reading(33, collections.Counter({"README.md": 2, "src/a.py": 2, "bin/t.py": 1})))
self.assertEqual(reading_cost.entry("abc", "t", reading), "## Reading cost, chunk abc, finished t\n\n33 tokens read before the first commit.\n\nRead most:\n\n- `README.md` 2\n- `src/a.py` 2\n- `bin/t.py` 1\n")
def test_measures_nothing_for_a_worker_that_never_committed(self):
self.assertIsNone(reading_cost.measure(json.dumps(assistant({"type": "tool_use", "name": "Bash", "input": {"command": "git log --grep commit"}})).encode(), []))
class Render(unittest.TestCase):
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
said = transcript.render([
@@ -615,7 +656,7 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "rule", "1", "entries.reason", read),
("cycle/run.py", "ask", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's reading cost cannot be measured or kept, or its session deleted"),
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),