"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures and the calls raised at the archive's root.""" import contextlib import dataclasses import fcntl import json import pathlib import re import typing from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent from failure import Failure from claude_code.entries import parse_entry from file_writes import replace_file from utc_stamp import STAMPED from transcript_archive.outcomes import VERDICT_AT FIGURES = "routing-figures.md" LOCK = "routing-figures.lock" RAISED = "routing-calls-raised.md" RAISED_HEADING = "# Routing calls raised\n" # Each line is a call and when it was raised, or a reset: `- ` or `- Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again. RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE) RESET = "Reset" @dataclasses.dataclass(frozen=True) class Raised: """since is the latest reset's stamp, empty for none; calls are those raised after it.""" since: str calls: frozenset[str] @contextlib.contextmanager def locked(root: pathlib.Path) -> typing.Iterator[bool]: """Whether this loop holds the archive's routing lock; while another loop holds it, measuring is that loop's.""" try: handle = open(root / LOCK, "a") except OSError: yield False return with handle: try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: yield False return yield True def cycles(root: pathlib.Path) -> int | Failure: """The cycles every project's loop has closed with a verdict.""" listed = archived_outcomes(root) if isinstance(listed, Failure): return listed try: return sum(len(VERDICT_AT.findall(path.read_text(encoding="utf-8"))) for _, path in listed) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not count the cycles in {root}: {failure}") def last_measured(root: pathlib.Path) -> int | Failure: """The cycle the kept figures were measured at; 0 before any.""" try: found = MEASURED_AT.search((root / FIGURES).read_text(encoding="utf-8")) except FileNotFoundError: return 0 except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {root / FIGURES}: {failure}") return int(found.group(1)) if found else 0 @dataclasses.dataclass(frozen=True) class Measured: """skipped names each chunk folder that could not be read whole, such as one another loop is writing.""" chunks: list[ChunkFigures] skipped: tuple[str, ...] def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Failure: """The figures of each chunk that finished after since, measured one chunk at a time because the archive outgrows memory. Only an archive that cannot be listed fails.""" listed = archived_outcomes(root) if isinstance(listed, Failure): return listed projects = sorted({root / key for key, _ in listed}) found = [] skipped = [] for project in projects: chunks = finished_chunks(project) if isinstance(chunks, Failure): skipped.append(str(project.relative_to(root))) continue for chunk in (chunk for chunk in chunks if chunk.finished > since): folder = project / chunk.folder try: kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)] subagents = [subagent(path) for path in chunk.subagents] worker = entries(chunk.transcript) except (OSError, UnicodeDecodeError): skipped.append(str(folder.relative_to(root))) continue found.append(measured(Chunk(str(project.relative_to(root)), kept, worker, subagents), home)) return Measured(found, tuple(skipped)) def entries(path: pathlib.Path) -> list[dict]: with open(path, "rb") as handle: return [entry for line in handle if (entry := parse_entry(line))] def subagent(transcript: pathlib.Path) -> Subagent: """The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable names nothing.""" path = transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json") try: meta = json.loads(path.read_text(encoding="utf-8")) except (FileNotFoundError, ValueError): meta = {} meta = meta if isinstance(meta, dict) else {} return Subagent(str(meta.get("agentType") or ""), str(meta.get("toolUseId") or ""), entries(transcript)) def write_figures(root: pathlib.Path, text: str) -> Failure | None: unwritten = replace_file(root / FIGURES, text.encode()) return Failure(f"could not write {root / FIGURES}: {unwritten.reason}") if unwritten else None def raised(root: pathlib.Path) -> Raised | Failure: text = read_raised(root) if isinstance(text, Failure): return text lines = RAISED_LINE.findall(text) since = max((stamp for stamp, what in lines if what == RESET), default="") return Raised(since, frozenset(what for stamp, what in lines if stamp > since and what != RESET)) def mark_raised(root: pathlib.Path, calls: list[str], at: str) -> Failure | None: kept = read_raised(root) if isinstance(kept, Failure): return kept # The first line opens a list below the heading; each later one joins it. gap = "\n" if RAISED_LINE.search(kept) else "\n\n" unwritten = replace_file(root / RAISED, (kept.rstrip("\n") + gap + "".join(f"- {at} {call}\n" for call in calls)).encode()) return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None def read_raised(root: pathlib.Path) -> str | Failure: try: return (root / RAISED).read_text(encoding="utf-8") except FileNotFoundError: return RAISED_HEADING except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {root / RAISED}: {failure}")