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
+41 -19
View File
@@ -5,28 +5,28 @@ import re
import statistics
import typing
from claude_code.entries import assistant_parts, parts, tool_call
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from git_command import commits
from reading_cost.measure import count
from model_routing.ladder import position, Rung
from round_titles import round_counts
from loop_claude.routing import route_from
from model_routing.route import route_from
from shell_command import simple_commands
from utc_stamp import STAMPED
from transcript_archive.outcomes import workers
from transcript_archive.outcomes import UNFINISHED_AT, workers
CYCLES_PER_CHECK = 20
MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE)
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
MEASURED_AT_LEAST = 5
DIMENSIONS = ("project", "subagent type", "rung", "tool")
# The tool label of a message that follows no tool call, such as the first message after a prompt.
PROMPT = "prompt"
UNFINISHED_AT = re.compile(rf"^{STAMPED} Verdict: unfinished$", re.MULTILINE)
@dataclasses.dataclass(frozen=True)
class Subagent:
"""meta is the subagent's .meta.json: its agentType, and the toolUseId of the worker's Agent call that launched it."""
meta: dict
"""What the subagent's .meta.json names, its agentType and the toolUseId of the worker's Agent call that launched it, each empty where it names none; and its transcript's entries."""
kind: str
launched_by: str
entries: list[dict]
@@ -74,23 +74,33 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
tokens: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS}
for at, tools, spent in spend(chunk.worker):
add(tokens, chunk.project, "worker", str(rung_at(cycles, at)), tools, spent)
launches = {str(part.get("id")): (str(entry.get("timestamp", "")), arguments) for entry in chunk.worker for part in assistant_parts(entry) if (found := tool_call(part)) and found[0] == "Agent" and isinstance(arguments := found[1], dict)}
launches = agent_calls(chunk.worker)
reported = results(chunk.worker)
delegated: collections.Counter[str] = collections.Counter()
reports: dict[str, Reports] = {}
for subagent in chunk.subagents:
launch = str(subagent.meta.get("toolUseId"))
launched_at, arguments = launches.get(launch, ("", {}))
kind = str(subagent.meta.get("agentType") or arguments.get("subagent_type") or "unknown")
launched_at, arguments = launches.get(subagent.launched_by, ("", {}))
kind = subagent.kind or str(arguments.get("subagent_type") or "unknown")
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
delegated[rung] += 1
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(launch, "")), sum(map(len, results(subagent.entries).values())))
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
for _, tools, spent in spend(subagent.entries):
add(tokens, chunk.project, kind, rung, tools, spent)
start = route_from(cycles[0][1]) if cycles else None
return ChunkFigures(tokens, start.rung if start and start.item else None, rounds_past_first(chunk.worker, home), len(UNFINISHED_AT.findall(chunk.outcomes)), delegated, reports)
def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
"""The timestamp and the arguments of each Agent call, by the call's id."""
found = {}
for entry in worker:
for part in assistant_parts(entry):
call = tool_call(part)
if call and call[0] == "Agent" and isinstance(part, dict) and isinstance(call[1], dict):
found[str(part.get("id"))] = (str(entry.get("timestamp", "")), call[1])
return found
def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, rung: str, tools: list[str], spent: int) -> None:
tokens["project"][project] += spent
tokens["subagent type"][kind] += spent
@@ -130,7 +140,7 @@ def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]:
spent = []
before = [PROMPT]
for at, usage, called in messages.values():
tokens = sum(count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0
tokens = sum(usage_count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0
spent.append((at, before, tokens))
before = called or [PROMPT]
return spent
@@ -142,11 +152,17 @@ def results(entries: list[dict]) -> dict[str, str]:
for entry in entries:
for part in parts(entry):
if isinstance(part, dict) and part.get("type") == "tool_result":
body = part.get("content")
found[str(part.get("tool_use_id"))] = body if isinstance(body, str) else "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else ""
found[str(part.get("tool_use_id"))] = result_text(part.get("content"))
return found
# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]}
def result_text(body: object) -> str:
if isinstance(body, str):
return body
return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else ""
def rounds_past_first(worker: list[dict], home: str) -> int:
# A commit retried after a failed hook repeats its title, so each title counts once.
titles = dict.fromkeys(
@@ -158,6 +174,11 @@ def rounds_past_first(worker: list[dict], home: str) -> int:
return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values())
def due(cycle: int, last_measured: int) -> bool:
"""Whether the archive's cycle count has run CYCLES_PER_CHECK past the cycle the figures were last measured at: counting from the last measurement, a count another loop pushed past a multiple still measures."""
return cycle >= last_measured + CYCLES_PER_CHECK
def totals(chunks: list[ChunkFigures]) -> Figures:
tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS}
routed: dict[Rung, list[ChunkFigures]] = {}
@@ -178,7 +199,7 @@ def calls(figures: Figures) -> list[str]:
for what, of in (("review rounds past each pass's first", lambda chunk: chunk.rounds_past_first), ("unfinished verdicts", lambda chunk: chunk.unfinished)):
if mean(figures.routed[lower], of) > mean(figures.routed[upper], of):
found.append(f"Chunks routed onto {lower} took more {what} than chunks routed onto {upper}.")
# Characters stand in for tokens: both sides are text the worker would read.
# Characters stand in for tokens: both sides are text the worker would read. Both would fill the same peak context, so comparing the sums compares their shares of it.
found += [f"{kind} subagents' reports took more of the worker's context than their searches would have." for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report > reports.searches]
return found
@@ -187,10 +208,11 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
return statistics.mean(map(of, chunks))
def render(figures: Figures, found: list[str], at: str, cycle: int) -> str:
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
sections = [
"# Routing figures",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly.",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly.",
"## Calls for a routing change",
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
*[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))],
+31 -13
View File
@@ -1,6 +1,7 @@
import collections
import json
import pathlib
import shutil
import sys
import tempfile
import unittest
@@ -8,7 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive
from routing_figures.measure import calls, Chunk, ChunkFigures, measured, render, Reports, Subagent, totals
from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals
from failure import Failure
from transcript_archive import outcomes
from model_routing.ladder import Rung
@@ -61,8 +62,8 @@ class Measured(unittest.TestCase):
result("a2", "y" * 5),
]
subagents = [
Subagent({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T10:00:01Z", model="claude-sonnet-5-5"), result("r", "z" * 20)]),
Subagent({"agentType": "Explore", "toolUseId": "a2"}, [message("s2", "2026-10-14T10:00:01Z")]),
Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z", model="claude-sonnet-5-5"), result("r", "z" * 20)]),
Subagent("", "a2", [message("s2", "2026-10-14T10:00:01Z")]),
]
found = measured(Chunk("log", stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m")), worker, subagents), "/h")
self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1})
@@ -103,19 +104,24 @@ class Calls(unittest.TestCase):
def test_renders_each_dimension_largest_first_and_the_calls(self):
chunk = ChunkFigures({"project": collections.Counter({"a": 2, "b": 20})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)})
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40)
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "")
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
self.assertIn("| b | 20 |\n| a | 2 |", text)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 |", text)
self.assertIn("| Explore | 2 | 3 | 4 |", text)
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20))
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
def test_measures_once_the_count_runs_20_past_the_last_measurement(self):
self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True])
self.assertTrue(due(20, 0))
class Archive(unittest.TestCase):
def setUp(self):
self.root = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(lambda: __import__("shutil").rmtree(self.root))
self.addCleanup(shutil.rmtree, self.root)
def chunk(self, key, name, kept, worker, subagent=None):
folder = self.root / key / name
@@ -136,22 +142,34 @@ class Archive(unittest.TestCase):
def test_measures_each_finished_chunk_keyed_by_its_project(self):
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e")), [message("m1", "2026-10-14T09:00:00Z")])
found = archive.measure_archive(self.root, "/h")
found = archive.measure_archive(self.root, "/h", "")
self.assertEqual([chunk.tokens["project"] for chunk in found], [{"home/x": 222}])
self.assertEqual(found[0].tokens["subagent type"], {"worker": 111, "Explore": 111})
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), [])
def test_keeps_the_figures_and_says_which_calls_it_raises_for_the_first_time(self):
self.assertIsNone(archive.write_figures(self.root, "# Routing figures\n"))
self.assertEqual((self.root / archive.FIGURES).read_text(), "# Routing figures\n")
self.assertEqual(archive.unraised(self.root, ["A.", "B."]), ["A.", "B."])
def test_keeps_the_figures_and_reads_back_the_cycle_they_were_measured_at(self):
self.assertEqual(archive.last_measured(self.root), 0)
self.assertIsNone(archive.write_figures(self.root, render(totals([]), [], "2026-10-15T00:00:00Z", 40, "")))
self.assertEqual(archive.last_measured(self.root), 40)
def test_reads_the_calls_raised_since_the_latest_reset(self):
self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset()))
self.assertIsNone(archive.mark_raised(self.root, ["A."], "2026-10-15T00:00:00Z"))
self.assertEqual(archive.unraised(self.root, ["A.", "B."]), ["B."])
self.assertIsNone(archive.mark_raised(self.root, ["B."], "2026-10-15T01:00:00Z"))
self.assertEqual((self.root / archive.RAISED).read_text(), "# Routing calls raised\n\n- 2026-10-15T00:00:00Z A.\n- 2026-10-15T01:00:00Z B.\n")
self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset({"A.", "B."})))
self.assertIsNone(archive.mark_raised(self.root, ["Reset"], "2026-10-15T00:30:00Z"))
self.assertEqual(archive.raised(self.root), archive.Raised("2026-10-15T00:30:00Z", frozenset({"B."})))
def test_holds_the_lock_while_no_other_loop_does(self):
with archive.locked(self.root) as held, archive.locked(self.root) as other:
self.assertEqual((held, other), (True, False))
with archive.locked(self.root) as again:
self.assertTrue(again)
def test_fails_on_an_archive_it_cannot_read(self):
(self.root / archive.RAISED).mkdir()
self.assertIsInstance(archive.unraised(self.root, ["A."]), Failure)
self.assertIsInstance(archive.raised(self.root), Failure)
if __name__ == "__main__":