Measure each chunk's reading cost from its transcript and keep it in the comprehension history
This commit is contained in:
@@ -15,8 +15,7 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
raw = handle.read()
|
||||
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
|
||||
folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
|
||||
folder = paths.transcript_archive / project_key / chunk_of(raw)
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return unarchived(failure.filename, failure.strerror)
|
||||
@@ -36,6 +35,11 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat
|
||||
return None
|
||||
|
||||
|
||||
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
|
||||
def chunk_of(raw: bytes) -> str:
|
||||
return hashlib.sha256(first_timestamped_line(raw)).hexdigest()
|
||||
|
||||
|
||||
def unarchived(where: object, why: str | None) -> Failure:
|
||||
return Failure(f"could not archive the transcript: {where}: {why}")
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import collections
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
import time
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import make_private, replace_file
|
||||
from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call
|
||||
from loop_claude.cycle.archive import chunk_of
|
||||
from loop_claude.paths import Paths
|
||||
|
||||
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
|
||||
# Each reads the files it names; for these, the first operand is a pattern or a program unless -e or -f gives it.
|
||||
READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"}
|
||||
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
|
||||
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
|
||||
PLACES_KEPT = 10
|
||||
HEADING = "## Reading cost, chunk "
|
||||
TOKENS = re.compile(r"^(\d+) tokens read before the first commit\.$", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reading:
|
||||
"""What the worker and its subagents took in before the worker's first commit."""
|
||||
tokens: int
|
||||
places: collections.Counter[str]
|
||||
|
||||
|
||||
def record_reading(project_key: str, transcript: str, at: float, paths: Paths) -> Failure | None:
|
||||
try:
|
||||
raw = pathlib.Path(transcript).read_bytes()
|
||||
subagents = [path.read_bytes() for path in sorted(pathlib.Path(transcript.removesuffix(".jsonl"), "subagents").glob("*.jsonl"))]
|
||||
except OSError as failure:
|
||||
return Failure(f"could not measure the reading cost: {failure.filename}: {failure.strerror}")
|
||||
reading = measure(raw, subagents)
|
||||
if reading is None:
|
||||
return None
|
||||
return keep_reading(pending_file(project_key, paths), entry(chunk_of(raw)[:12], time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)), reading))
|
||||
|
||||
|
||||
def pending_file(project_key: str, paths: Paths) -> pathlib.Path:
|
||||
return paths.transcript_archive / project_key / "reading-cost.md"
|
||||
|
||||
|
||||
def measure(transcript: bytes, subagents: list[bytes]) -> Reading | None:
|
||||
worker = entries_of(transcript)
|
||||
commit = next((entry.get("timestamp", "") for entry in worker if any(commits(part) for part in assistant_parts(entry))), None)
|
||||
if commit is None:
|
||||
return None
|
||||
tokens = 0
|
||||
places: collections.Counter[str] = collections.Counter()
|
||||
for thread in (worker, *map(entries_of, subagents)):
|
||||
# Claude Code writes one entry per content block of a message, each with the message's usage.
|
||||
counted: set[str] = set()
|
||||
for entry in thread:
|
||||
if entry.get("type") != "assistant" or entry.get("timestamp", "") >= commit:
|
||||
continue
|
||||
message = entry.get("message") or {}
|
||||
if (key := str(message.get("id") or entry.get("uuid"))) not in counted:
|
||||
counted.add(key)
|
||||
usage = message.get("usage") or {}
|
||||
tokens += int(usage.get("input_tokens") or 0) + int(usage.get("cache_creation_input_tokens") or 0)
|
||||
for part in assistant_parts(entry):
|
||||
places.update(read_paths(part, entry.get("cwd") or ""))
|
||||
return Reading(tokens, places)
|
||||
|
||||
|
||||
def entries_of(raw: bytes) -> list[dict]:
|
||||
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
|
||||
|
||||
|
||||
def arguments_of(part: object) -> tuple[object, dict]:
|
||||
call = tool_call(part)
|
||||
return (call[0], call[1]) if call and isinstance(call[1], dict) else (None, {})
|
||||
|
||||
|
||||
def commits(part: object) -> bool:
|
||||
name, arguments = arguments_of(part)
|
||||
return name == "Bash" and bool(COMMIT.search(str(arguments.get("command", ""))))
|
||||
|
||||
|
||||
def read_paths(part: object, cwd: str) -> list[str]:
|
||||
name, arguments = arguments_of(part)
|
||||
if name == "Read":
|
||||
return place(str(arguments.get("file_path", "")), cwd, cwd)
|
||||
if name == "Grep" and arguments.get("path"):
|
||||
return place(str(arguments["path"]), cwd, cwd)
|
||||
if name == "Bash":
|
||||
return bash_reads(str(arguments.get("command", "")), cwd)
|
||||
return []
|
||||
|
||||
|
||||
def bash_reads(command: str, cwd: str) -> list[str]:
|
||||
found = []
|
||||
base = cwd
|
||||
lines = iter(command.splitlines())
|
||||
for line in lines:
|
||||
try:
|
||||
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
|
||||
lexer.whitespace_split = True
|
||||
tokens = list(lexer)
|
||||
except ValueError:
|
||||
continue
|
||||
for words in segments(tokens):
|
||||
if words[0] == "cd" and len(words) == 2:
|
||||
base = posixpath.normpath(posixpath.join(base, os.path.expanduser(words[1])))
|
||||
found += [kept for path in operands(words) for kept in place(path, base, cwd)]
|
||||
if "<<" in tokens or "<<-" in tokens:
|
||||
marker = tokens[tokens.index("<<" if "<<" in tokens else "<<-") + 1:][:1]
|
||||
for body in lines:
|
||||
if marker and body.strip() == marker[0]:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def segments(tokens: list[str]) -> list[list[str]]:
|
||||
found: list[list[str]] = [[]]
|
||||
skip = False
|
||||
for token in tokens:
|
||||
if skip:
|
||||
skip = False
|
||||
elif token and all(char in "();<>|&" for char in token):
|
||||
# A redirect's target is written or fed, not read by the command.
|
||||
skip = "<" in token or ">" in token
|
||||
found.append([])
|
||||
else:
|
||||
found[-1].append(token)
|
||||
return [words for words in found if words]
|
||||
|
||||
|
||||
def operands(words: list[str]) -> list[str]:
|
||||
program = posixpath.basename(words[0])
|
||||
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
|
||||
return []
|
||||
given = [word for word in words[1:] if not word.startswith("-")]
|
||||
if program in PATTERN_FIRST and not any(word in ("-e", "-f") for word in words):
|
||||
given = given[1:]
|
||||
return [word for word in given if ("/" in word or re.search(r"\.[A-Za-z0-9]+$", word)) and not NOT_A_PATH.search(word)]
|
||||
|
||||
|
||||
# Relative to the folder it was read in, a worktree or the checkout, so both name a file alike; a file outside both is no place of the project.
|
||||
def place(path: str, base: str, cwd: str) -> list[str]:
|
||||
full = posixpath.normpath(posixpath.join(base, os.path.expanduser(path)))
|
||||
roots = [root.rstrip("/") + "/" for root in (base, cwd) if root]
|
||||
return next(([full.removeprefix(root)] for root in roots if full.startswith(root)), [])
|
||||
|
||||
|
||||
def entry(chunk: str, finished: str, reading: Reading) -> str:
|
||||
places = "".join(f"- `{path}` {count}\n" for path, count in sorted(reading.places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT])
|
||||
return f"{HEADING}{chunk}, finished {finished}\n\n{reading.tokens} tokens read before the first commit.\n" + (f"\nRead most:\n\n{places}" if places else "")
|
||||
|
||||
|
||||
def keep_reading(pending: pathlib.Path, block: str) -> Failure | None:
|
||||
try:
|
||||
make_private(pending.parent)
|
||||
kept = pending.read_text(encoding="utf-8") if pending.exists() else ""
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not keep the reading cost in {pending}: {failure}")
|
||||
if block.splitlines()[0] in kept.splitlines():
|
||||
return None
|
||||
if unwritten := replace_file(pending, (kept + ("\n" if kept else "") + block).encode()):
|
||||
return Failure(f"could not keep the reading cost in {pending}: {unwritten.reason}")
|
||||
return None
|
||||
|
||||
|
||||
def blocks(text: str) -> list[str]:
|
||||
"""The reading-cost entries of a markdown file, in order, each from its heading to the next heading."""
|
||||
found = []
|
||||
for section in re.split(r"(?m)^(?=## )", text):
|
||||
if section.startswith(HEADING):
|
||||
found.append(section.rstrip("\n") + "\n")
|
||||
return found
|
||||
|
||||
|
||||
def tokens_of(block: str) -> int:
|
||||
match = TOKENS.search(block)
|
||||
return int(match.group(1)) if match else 0
|
||||
@@ -12,6 +12,7 @@ from loop_claude.cycle.judge import judge
|
||||
from loop_claude.project.model_choice import Models
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.claude_code.transcript import read_transcript, render
|
||||
from loop_claude.cycle.reading_cost import record_reading
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from loop_claude.stop import Stop
|
||||
@@ -111,7 +112,7 @@ def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) ->
|
||||
finished = isinstance(verdict, Finished)
|
||||
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}\n\nEvidence:\n{quoted(verdict.evidence)}", cycle.effects.now(), cycle.paths):
|
||||
return Stop(1, failure.reason)
|
||||
if finished and (failure := delete_session(cycle.session)):
|
||||
if finished and (failure := record_reading(cycle.project_key, transcript_path, cycle.effects.now(), cycle.paths) or delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
return Archived()
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ time. Claude Code keeps a folder per session beside its transcript, holding the
|
||||
transcripts among other files; that folder, and every other file named after the session except
|
||||
the transcript, are copied into <chunk>/session/. A file there is replaced only by a version that
|
||||
grew from it. A file Claude Code rewrote lands beside its copy as <name>.<hash of its content>.
|
||||
When a chunk finishes, the reading cost of its work before the worker's first commit is kept in
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<key>/reading-cost.md; reading_cost.py --help says what it holds and how
|
||||
it reaches the project.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first
|
||||
@@ -50,7 +53,7 @@ Exit 1, saying why, when:
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- a finished chunk's reading cost cannot be measured or kept, or its session deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
||||
|
||||
Executable
+90
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move loop-claude's reading-cost figures into a project's history, and say whether they rise.
|
||||
|
||||
usage: reading_cost.py [history]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. history defaults to
|
||||
docs/comprehension-history.md there, created when missing. When loop-claude finishes a chunk, it
|
||||
measures what the worker and its subagents read before the worker's first commit: the tokens they
|
||||
took in, and the project's files they opened or searched, with how often. It keeps each figure in
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<key>/reading-cost.md (default ~/.claude/loop-claude-transcripts), <key>
|
||||
being the checkout's path relative to ~/code, or to / outside it. This appends to history each
|
||||
figure it does not yet hold, under a "## Reading cost, chunk <id>, finished <UTC time>" heading.
|
||||
|
||||
It then compares the mean tokens of the history's last 5 figures with the 5 before them, and prints
|
||||
"Rising:" or "Not rising:" with both means. 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 finds no checkout, or the figures or the history cannot be read or
|
||||
written.
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_claude.cycle.reading_cost import blocks, pending_file, PLACES_KEPT, tokens_of
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude.project.checkout import project_key
|
||||
from file_writes import replace_file
|
||||
|
||||
WINDOW = 5
|
||||
PLACE = re.compile(r"^- `(.+)` (\d+)$", re.MULTILINE)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]) or len(argv) > 1:
|
||||
print(__doc__.strip(), file=sys.stdout if argv[:1] in (["-h"], ["--help"]) else sys.stderr)
|
||||
return 0 if argv[:1] in (["-h"], ["--help"]) else 1
|
||||
found = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], capture_output=True, text=True)
|
||||
if found.returncode != 0:
|
||||
print(found.stderr.strip(), file=sys.stderr)
|
||||
return 1
|
||||
top, common = found.stdout.splitlines()
|
||||
paths = paths_from(pathlib.Path.home(), os.environ)
|
||||
# The common dir is the checkout's .git, whichever worktree runs this.
|
||||
pending = pending_file(project_key(str(pathlib.Path(common).parent), paths.code), paths)
|
||||
history = pathlib.Path(argv[0]) if argv else pathlib.Path(top, "docs", "comprehension-history.md")
|
||||
try:
|
||||
figures = blocks(pending.read_text(encoding="utf-8")) if pending.exists() else []
|
||||
text = history.read_text(encoding="utf-8") if history.exists() else "# Comprehension history\n"
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
print(f"could not read the reading cost: {failure}", file=sys.stderr)
|
||||
return 1
|
||||
held = set(text.splitlines())
|
||||
new = [block for block in figures if block.splitlines()[0] not in held]
|
||||
if new:
|
||||
text = text.rstrip("\n") + "\n\n" + "\n".join(new)
|
||||
history.parent.mkdir(parents=True, exist_ok=True)
|
||||
if unwritten := replace_file(history, text.encode()):
|
||||
print(f"could not write {history}: {unwritten.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"Appended {len(new)} reading-cost figures to {history}.")
|
||||
print(trend(blocks(text)))
|
||||
return 0
|
||||
|
||||
|
||||
def trend(figures: list[str]) -> str:
|
||||
if len(figures) < 2 * WINDOW:
|
||||
return f"{len(figures)} chunks measured; the trend needs {2 * WINDOW}."
|
||||
last, before = figures[-WINDOW:], figures[-2 * WINDOW:-WINDOW]
|
||||
means = f"the last {WINDOW} chunks read {mean(last)} tokens on average before their first commit, the {WINDOW} before them {mean(before)}."
|
||||
if mean(last) <= mean(before):
|
||||
return f"Not rising: {means}"
|
||||
places: collections.Counter[str] = collections.Counter()
|
||||
for block in last:
|
||||
places.update({path: int(count) for path, count in PLACE.findall(block)})
|
||||
read_most = "".join(f"\n- `{path}` {count}" for path, count in sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT])
|
||||
return f"Rising: {means}\n\nRead most over the last {WINDOW}:\n{read_most}"
|
||||
|
||||
|
||||
def mean(figures: list[str]) -> int:
|
||||
return round(sum(map(tokens_of, figures)) / len(figures))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
+43
-2
@@ -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"),
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
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()
|
||||
Reference in New Issue
Block a user