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:
@@ -1,6 +1,8 @@
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
@@ -10,12 +12,25 @@ from file_writes import make_private, replace_file
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.claude_code.session import session_files
|
||||
|
||||
FINISHED = "Verdict: finished"
|
||||
UNFINISHED = "Verdict: unfinished"
|
||||
FINISHED_AT = re.compile(rf"^(\S+) {re.escape(FINISHED)}$", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class FinishedChunk:
|
||||
folder: str
|
||||
finished: str
|
||||
transcript: pathlib.Path
|
||||
subagents: list[pathlib.Path]
|
||||
|
||||
|
||||
def archive(project_key: str, path: str, task: str, outcome: str, at: float, paths: Paths) -> Failure | None:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
raw = handle.read()
|
||||
folder = paths.transcript_archive / project_key / chunk_of(raw)
|
||||
# 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()
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return unarchived(failure.filename, failure.strerror)
|
||||
@@ -24,7 +39,7 @@ def archive(project_key: str, path: str, task: str, outcome: str, at: float, pat
|
||||
return unkept
|
||||
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
|
||||
outcomes = copy.with_suffix(".outcomes.md")
|
||||
stamped = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))} {outcome}"
|
||||
stamped = f"{utc(at)} {outcome}"
|
||||
if copy.exists() and outcomes.exists():
|
||||
return add_outcome(outcomes, stamped)
|
||||
# The copy lands last, so a copy on disk always has its outcomes and its session's files beside it.
|
||||
@@ -35,11 +50,6 @@ 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}")
|
||||
|
||||
@@ -89,3 +99,21 @@ def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None:
|
||||
return copy if data != kept else None
|
||||
beside = copy.with_name(f"{copy.name}.{hashlib.sha256(data).hexdigest()}")
|
||||
return None if beside.exists() else beside
|
||||
|
||||
|
||||
def utc(at: float) -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at))
|
||||
|
||||
|
||||
# One per chunk folder, its latest finished copy, in the order they finished.
|
||||
def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure:
|
||||
found = []
|
||||
try:
|
||||
for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()):
|
||||
copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))))
|
||||
if copies:
|
||||
finished, outcomes = copies[-1]
|
||||
found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl"))))
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read the archive {project_archive}: {failure}")
|
||||
return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder))
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
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
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
|
||||
from loop_claude.cycle.archive import archive
|
||||
from loop_claude.cycle.archive import archive, FINISHED, UNFINISHED
|
||||
from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
@@ -12,7 +12,6 @@ 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
|
||||
@@ -110,9 +109,9 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
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):
|
||||
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"{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 := record_reading(cycle.project_key, transcript_path, cycle.effects.now(), cycle.paths) or delete_session(cycle.session)):
|
||||
if finished and (failure := delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
return Archived()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user