"""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 functools import json import pathlib import re import typing from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks from branch_chunks.read import branch_chunks from branch_chunks.cut import BranchChunk from project_key import checkout_of from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent from git_repo import default_ref, Git 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" # Seconds each git call reading a project's history may take. GIT_TIMEOUT = 60 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; unread names each project whose default branch could not be read, with why.""" chunks: list[ChunkFigures] skipped: tuple[str, ...] unread: tuple[str, ...] = () def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> 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 = [] unread = [] for project in projects: key = str(project.relative_to(root)) chunks = finished_chunks(project) if isinstance(chunks, Failure): skipped.append(key) continue chunks = [chunk for chunk in chunks if chunk.finished > since] history = branch_history(checkout_of(key, pathlib.Path(home)), git) if chunks else None if isinstance(history, Failure): unread.append(f"{key}: {history.reason}") history = None for chunk in chunks: 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(key, kept, worker, subagents), home, history)) return Measured(found, tuple(skipped), tuple(unread)) def branch_history(checkout: str, git: Git) -> list[BranchChunk] | Failure: """The chunks on the checkout's default branch as last fetched, read guarded, since the checkout's config may name a program.""" ref = default_ref(checkout, GIT_TIMEOUT, guarded=True, git=git) return ref if isinstance(ref, Failure) else branch_chunks(ref, functools.partial(git, cwd=checkout, timeout=GIT_TIMEOUT, guarded=True)) 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}")