Answer architecture round 1: 0 🔴, 12 🟡; break the import loop, share the interrupt hand-over and formats, measure under a lock 20 cycles past the last measurement, go on off a terminal, and add a reset

This commit is contained in:
2026-10-15 00:49:02 +02:00
parent 5e0816bd80
commit acdba1abf4
19 changed files with 333 additions and 200 deletions
+70 -23
View File
@@ -1,32 +1,74 @@
"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures and the calls already raised at the archive's root."""
"""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 routing_figures.measure import Chunk, ChunkFigures, measured, Subagent
from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent
from failure import Failure
from transcript_archive.read import finished_chunks
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"
RAISED_CALL = re.compile(rf"^- {STAMPED} (.+)$", re.MULTILINE)
VERDICT = re.compile(rf"^{STAMPED} Verdict: (?:finished|unfinished)$", re.MULTILINE)
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`.
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."""
try:
return sum(len(VERDICT.findall(path.read_text(encoding="utf-8"))) for path in root.rglob("*.outcomes.md"))
return sum(len(VERDICT_AT.findall(path.read_text(encoding="utf-8"))) for path in root.rglob("*.outcomes.md"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not count the cycles in {root}: {failure}")
def measure_archive(root: pathlib.Path, home: str) -> list[ChunkFigures] | Failure:
"""Each finished chunk's figures, measured one chunk at a time, since the archive outgrows memory."""
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
def measure_archive(root: pathlib.Path, home: str, since: str) -> list[ChunkFigures] | Failure:
"""The figures of each chunk that finished after since, measured one chunk at a time, since the archive outgrows memory."""
try:
projects = sorted({path.parent.parent for path in root.rglob("*.outcomes.md")})
except OSError as failure:
@@ -36,14 +78,15 @@ def measure_archive(root: pathlib.Path, home: str) -> list[ChunkFigures] | Failu
chunks = finished_chunks(project)
if isinstance(chunks, Failure):
return chunks
for chunk in chunks:
for chunk in (chunk for chunk in chunks if chunk.finished > since):
folder = project / chunk.folder
try:
kept = "\n".join(path.read_text(encoding="utf-8") for path in sorted(folder.glob("*.outcomes.md")))
subagents = [Subagent(meta(path), entries(path)) for path in chunk.subagents]
found.append(measured(Chunk(str(project.relative_to(root)), kept, entries(chunk.transcript), subagents), home))
subagents = [subagent(path) for path in chunk.subagents]
worker = entries(chunk.transcript)
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the chunk {folder}: {failure}")
found.append(measured(Chunk(str(project.relative_to(root)), kept, worker, subagents), home))
return found
@@ -52,14 +95,15 @@ def entries(path: pathlib.Path) -> list[dict]:
return [entry for line in handle if (entry := parse_entry(line))]
def meta(transcript: pathlib.Path) -> dict:
"""The .meta.json Claude Code writes beside a subagent's transcript; empty where it wrote none or one this cannot read."""
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:
found = json.loads(path.read_text(encoding="utf-8"))
meta = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, ValueError):
return {}
return found if isinstance(found, dict) else {}
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:
@@ -67,19 +111,22 @@ def write_figures(root: pathlib.Path, text: str) -> Failure | None:
return Failure(f"could not write {root / FIGURES}: {unwritten.reason}") if unwritten else None
def unraised(root: pathlib.Path, found: list[str]) -> list[str] | Failure:
"""The calls among found that were never raised."""
raised = read_raised(root)
return raised if isinstance(raised, Failure) else [call for call in found if call not in set(RAISED_CALL.findall(raised))]
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, raised: list[str], at: str) -> Failure | None:
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 call opens a list below the heading; each later one joins it.
gap = "\n" if RAISED_CALL.search(kept) else "\n\n"
unwritten = replace_file(root / RAISED, (kept.rstrip("\n") + gap + "".join(f"- {at} {call}\n" for call in raised)).encode())
# 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