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()