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
This commit is contained in:
+104
-25
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user