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
+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()]))],