From 0c93614f4a23f6ed251b636df96131635ee95395 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 19:53:19 +0100 Subject: [PATCH 1/4] Split the routing figures by concern and keep their state as fields; check the decision titles AGENTS.md lists and todo.md cites --- CHANGELOG.md | 1 + bin/loop_claude/loop/main.py | 4 +- bin/loop_claude/loop/routing_check.py | 34 +- bin/loop_claude/test_loop_claude.py | 10 +- bin/repo_checks/test_citations.py | 15 + bin/routing_figures/archive.py | 73 +--- bin/routing_figures/calls.py | 93 +++++ bin/routing_figures/chunk.py | 170 +++++++++ bin/routing_figures/dollars.py | 80 +++++ bin/routing_figures/measure.py | 367 -------------------- bin/routing_figures/render.py | 100 ++++++ bin/routing_figures/state.py | 124 +++++++ bin/routing_figures/test_routing_figures.py | 124 ++++--- docs/reading-cost.md | 15 + todo.md | 23 +- 15 files changed, 708 insertions(+), 525 deletions(-) create mode 100644 bin/routing_figures/calls.py create mode 100644 bin/routing_figures/chunk.py create mode 100644 bin/routing_figures/dollars.py delete mode 100644 bin/routing_figures/measure.py create mode 100644 bin/routing_figures/render.py create mode 100644 bin/routing_figures/state.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d97ed0fd..ee7dfab9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. Both markdown files read as before, and a `Reset` line in `routing-calls-raised.md` still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once, and puts a call raised since the latest reset to you once more. - `loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence. ## 0.6.0 diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 5012758c..dc550ff4 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -77,11 +77,11 @@ without it. Once 20 cycles have closed across all projects in the archive since the last measurement, the next loop to close one measures every finished chunk there, with no model run, and writes -routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures +routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a routing change, unless raised before, is an interrupt: claude, on the project's model, on the terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to the human; loop-inbox lists it too. Once that claude ends, the calls are listed in -routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised +routing-calls-raised.md beside the figures, kept in routing-state.json, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised again at the next measurement. A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 3caa9ef6..c90fba99 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -1,15 +1,17 @@ -"""Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`.""" +"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`.""" import pathlib from routing_figures import archive from loop_claude.waiting.ask import Ask, OpenOnTerminal -from routing_figures.measure import calls, due, render, totals +from routing_figures.calls import Call, calls, totals from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over from loop_claude.effects import Effects, say from failure import Failure from loop_claude.waiting.listing import listed from loop_claude.paths import Paths +from routing_figures.render import render from model_routing.ladder import Rung +from routing_figures import state from loop_claude.stop import Stop from utc_stamp import utc @@ -24,29 +26,31 @@ def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, p return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None -def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure: +def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure: """Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due.""" cycle = archive.cycles(root) - last = archive.last_measured(root) - if isinstance(cycle, Failure) or isinstance(last, Failure) or not due(cycle, last): - return cycle if isinstance(cycle, Failure) else last if isinstance(last, Failure) else [] - kept = archive.raised(root) - if isinstance(kept, Failure): - return kept + if isinstance(cycle, Failure): + return cycle + kept = state.read_state(root) + if isinstance(kept, Failure) or not state.due(cycle, kept.measured_at): + return kept if isinstance(kept, Failure) else [] + raised = state.raised(root) + if isinstance(raised, Failure): + return raised say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True) - measured = archive.measure_archive(root, str(paths.home), kept.since, effects.git) + measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git) if isinstance(measured, Failure): return measured figures = totals(measured.chunks, measured.skipped, measured.unread) found = calls(figures) - if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, kept.since)): + if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle): return unwritten - return [call for call in found if call not in kept.calls] + return [call for call in found if call not in raised.calls] -def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None: +def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[Call], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None: """Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" - bullets = "".join(f"- {call}\n" for call in new) + bullets = "".join(f"- {call.sentence()}\n" for call in new) question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}" say(f"\n{question}", effects) if not effects.on_terminal(): @@ -59,6 +63,6 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], if unstarted: return Stop(1, f"could not start claude for the routing calls in {paths.config_clone}, the setup's development clone: {unstarted.reason}") # Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice. - if unmarked := archive.mark_raised(root, new, utc(effects.now())): + if unmarked := state.mark_raised(root, new, utc(effects.now())): say(f"routing figures: {unmarked.reason}", effects) return None diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 492cdb25..6e5466f9 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -19,7 +19,7 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from routing_figures import archive, measure +from routing_figures import archive, state from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal from loop_claude.project import checkout, model_choice, records from loop_claude.loop import chunk_start, close @@ -923,7 +923,7 @@ class RoutingCheck(unittest.TestCase): self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}]) self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release") self.assertIn("Record what they decide in this checkout, the development clone", args[6]) - (self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across") + self.assertIsNone(state.mark_measured(self.root, 0)) self.assertEqual(self.check(FakeEffects(git=[UNREAD]))[0], None) self.assertNotIn(call, self.check(FakeEffects())[1]) @@ -938,7 +938,7 @@ class RoutingCheck(unittest.TestCase): def test_says_a_figure_it_cannot_read(self): self.chunks(5, 4) - (self.root / "routing-figures.md").mkdir() + (self.root / "routing-state.json").mkdir() self.assertIn("routing figures: could not read", self.check(FakeEffects())[1]) def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self): @@ -946,7 +946,7 @@ class RoutingCheck(unittest.TestCase): stop, said = self.check(FakeEffects(on_terminal=False, git=[UNREAD])) self.assertIsNone(stop) self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said) - (self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across") + self.assertIsNone(state.mark_measured(self.root, 0)) self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False, git=[UNREAD]))[1]) def test_leaves_the_measuring_to_a_loop_holding_the_lock(self): @@ -1824,7 +1824,7 @@ class HelpLimits(unittest.TestCase): self.assertIn("fails three times running, retried a minute apart", said) self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said) - self.assertIn(f"Once {measure.CYCLES_PER_CHECK} cycles have closed across all projects", said) + self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said) self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said) self.assertIn(f"unfinished {close.UNFINISHED_LIMIT} cycles running", said) self.assertIn(f"rerun to give it {close.UNFINISHED_LIMIT} more", said) diff --git a/bin/repo_checks/test_citations.py b/bin/repo_checks/test_citations.py index 3c1796fe..06cb373f 100644 --- a/bin/repo_checks/test_citations.py +++ b/bin/repo_checks/test_citations.py @@ -13,6 +13,9 @@ RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md" CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)') HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE) LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE) +DECISION_CITATION = re.compile(r"`?docs/decisions\.md`? → `([^`]+)`") +DECISION_TITLE = re.compile(r"^## (.+)$", re.MULTILINE) +LISTED_TITLE = re.compile(r"^- (.+)$", re.MULTILINE) NAME = re.compile(r'"([^"]+)"') RULE_FILE = re.compile(rf"(? ` 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 @@ -66,47 +52,36 @@ def cycles(root: pathlib.Path) -> int | 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: +class ArchiveChunks: """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: +def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks | 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 = [measure_project(root, project, home, since, git) for project in sorted({root / key for key, _ in listed})] - return Measured( + return ArchiveChunks( [chunk for project in projects for chunk in project.chunks], tuple(skipped for project in projects for skipped in project.skipped), tuple(unread for project in projects for unread in project.unread), ) -def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: str, git: Git) -> Measured: +def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks: """The figures of each of one project's chunks that finished after since, as measure_archive measures them.""" key = str(project.relative_to(root)) listed = finished_chunks(project) if isinstance(listed, Failure): - return Measured([], (key,)) + return ArchiveChunks([], (key,)) chunks = [chunk for chunk in listed if chunk.finished > since] if not chunks: - return Measured([], ()) + return ArchiveChunks([], ()) history = branch_history(checkout_of(key, pathlib.Path(home)), git) found = [] skipped = [] @@ -119,8 +94,8 @@ def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: except (OSError, UnicodeDecodeError): skipped.append(str(folder.relative_to(root))) continue - found.append(measured(Chunk(key, kept, worker, subagents), home, None if isinstance(history, Failure) else history)) - return Measured(found, tuple(skipped), (f"{key}: {history.reason}",) if isinstance(history, Failure) else ()) + found.append(chunk_figures(Chunk(key, kept, worker, subagents), home, None if isinstance(history, Failure) else history)) + return ArchiveChunks(found, tuple(skipped), (f"{key}: {history.reason}",) if isinstance(history, Failure) else ()) def branch_history(checkout: str, git: Git) -> list[BranchChunk] | Failure: @@ -148,31 +123,3 @@ def subagent(transcript: pathlib.Path) -> Subagent: 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}") diff --git a/bin/routing_figures/calls.py b/bin/routing_figures/calls.py new file mode 100644 index 00000000..2a50c526 --- /dev/null +++ b/bin/routing_figures/calls.py @@ -0,0 +1,93 @@ +"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing:`.""" +import collections +import dataclasses +import statistics +import typing + +from routing_figures.chunk import ChunkFigures, Reports +from routing_figures.dollars import DIMENSIONS, Dollars +from model_routing.ladder import position, Rung + +# 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 + + +@dataclasses.dataclass(frozen=True) +class Figures: + """escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the routed chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why.""" + chunks: int + dollars: Dollars + routed: dict[Rung, list[ChunkFigures]] + reports: dict[str, Reports] + escalated: collections.Counter[int] + skipped: tuple[str, ...] = () + unattributed: float = 0.0 + lacking: int = 0 + unmatched: int = 0 + unread: tuple[str, ...] = () + + +def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures: + dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} + for chunk in chunks: + for dimension in DIMENSIONS: + for label, amount in chunk.dollars.get(dimension, {}).items(): + dollars[dimension][label] += amount + routed: dict[Rung, list[ChunkFigures]] = {} + reports: dict[str, Reports] = {} + for chunk in chunks: + if chunk.start: + routed.setdefault(chunk.start, []).append(chunk) + for kind, found in chunk.reports.items(): + reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found + return Figures( + chunks=len(chunks), + dollars=dollars, + routed=routed, + reports=reports, + escalated=summed(chunks, lambda chunk: chunk.escalated), + skipped=skipped, + unattributed=sum(chunk.unattributed for chunk in chunks), + lacking=sum(chunk.lacking for chunk in chunks), + unmatched=sum(chunk.start is not None and chunk.fixed_later is None for chunk in chunks), + unread=unread, + ) + + +# Each kind of call to the sentence it is put to the human in, filled with its subjects in order. +SENTENCES = { + "rounds": "Chunks routed onto {} took more review rounds past each pass's first than chunks routed onto {}.", + "unfinished": "Chunks routed onto {} took more unfinished verdicts than chunks routed onto {}.", + "reports": "{} subagents' reports took more of the worker's context than their searches would have.", +} + + +@dataclasses.dataclass(frozen=True) +class Call: + """A routing change the figures call for, known again by its fields when raised twice. kind is a key of SENTENCES; subjects are the two rungs compared, lower first, or the subagent type.""" + kind: str + subjects: tuple[str, ...] + + def sentence(self) -> str: + return SENTENCES[self.kind].format(*self.subjects) + + +def calls(figures: Figures) -> list[Call]: + """Each routing change the figures call for.""" + compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position) + found = [] + for lower, upper in zip(compared, compared[1:]): + for kind, of in (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished)): + if mean(figures.routed[lower], of) > mean(figures.routed[upper], of): + found.append(Call(kind, (str(lower), str(upper)))) + # Characters stand in for tokens: reports and the tool results their subagents read are both text the worker would read, so their sums compare their shares of its context. + found += [Call("reports", (kind,)) for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report_chars > reports.read_chars] + return found + + +def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float: + return statistics.mean(map(of, chunks)) + + +def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter: + return sum(map(of, chunks), collections.Counter()) diff --git a/bin/routing_figures/chunk.py b/bin/routing_figures/chunk.py new file mode 100644 index 00000000..3e4d053d --- /dev/null +++ b/bin/routing_figures/chunk.py @@ -0,0 +1,170 @@ +"""The figures of one finished chunk: its dollars, the rung it started on, its review rounds and unfinished verdicts, its subagents' rungs and reports, its escalations and its later fixes.""" +import collections +import dataclasses +import re + +from claude_code.entries import assistant_parts, parts, tool_call, tool_result +from branch_chunks.cut import BranchChunk +from git_command import commits +from routing_figures.dollars import costed, Dollars, Message, messages, recorded_costs, Spent +from model_routing.route import ESCALATION_MARKER, Route, route_from +from transcript_archive.outcomes import judge_costs, UNFINISHED_AT, workers +from round_titles import rounds_past_first +from model_routing.ladder import Rung +from shell_command import simple_commands + +ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):") + + +@dataclasses.dataclass(frozen=True) +class Subagent: + """kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries.""" + kind: str + launched_by: str + entries: list[dict] + + +@dataclasses.dataclass(frozen=True) +class Chunk: + """outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries.""" + project: str + outcomes: list[str] + worker: list[dict] + subagents: list[Subagent] + + +@dataclasses.dataclass(frozen=True) +class Reports: + """How many subagents of a type reported, the characters of their reports, and the characters of the tool results they read.""" + subagents: int + report_chars: int + read_chars: int + + def __add__(self, other: "Reports") -> "Reports": + return Reports(self.subagents + other.subagents, self.report_chars + other.report_chars, self.read_chars + other.read_chars) + + +@dataclasses.dataclass(frozen=True) +class ChunkFigures: + """dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no item routed it, its project's default branch could not be read, or no chunk on that branch shipped its item.""" + dollars: Dollars + start: Rung | None + rounds_past_first: int + unfinished: int + delegated: collections.Counter[str] + reports: dict[str, Reports] + escalated: collections.Counter[int] + unattributed: float + lacking: int = 0 + fixed_later: int | None = None + + +def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) -> ChunkFigures: + """history is the chunks on the project's default branch, None where it could not be read.""" + cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0]) + launches = agent_calls(chunk.worker) + reported = results(chunk.worker) + delegated = [delegation(subagent, launches, reported, cycles) for subagent in chunk.subagents] + spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] + spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages] + judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] + dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) + start = route_from(cycles[0][1]) if cycles else None + reports: dict[str, Reports] = {} + for one in delegated: + reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars) + return ChunkFigures( + dollars=dollars, + start=start.rung if start and start.item else None, + rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)), + unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), + delegated=collections.Counter(one.rung for one in delegated), + reports=reports, + escalated=escalations(launches), + unattributed=unattributed, + lacking=transcripts_lacking(launches, chunk.subagents), + fixed_later=later_fixes_of(start, history), + ) + + +@dataclasses.dataclass(frozen=True) +class Delegation: + """One subagent as the figures count it: its type, the rung it ran on, the characters of its report and of the tool results it read, and its messages.""" + kind: str + rung: str + report_chars: int + read_chars: int + messages: list[Message] + + +def delegation(subagent: Subagent, launches: dict[str, tuple[str, dict]], reported: dict[str, str], cycles: list[tuple[str, str]]) -> Delegation: + """reported holds the worker's tool results by call id, so the Agent call's result is the subagent's report.""" + launched_at, arguments = launches.get(subagent.launched_by, ("", {})) + return Delegation( + kind=subagent.kind or str(arguments.get("subagent_type") or "unknown"), + rung=str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at))), + report_chars=len(reported.get(subagent.launched_by, "")), + read_chars=sum(map(len, results(subagent.entries).values())), + messages=messages(subagent.entries), + ) + + +def transcripts_lacking(launches: dict[str, tuple[str, dict]], subagents: list[Subagent]) -> int: + """How many Agent calls, the worker's and its subagents', have no subagent transcript in the archive. Each transcript answers one call, so they are the calls less the transcripts.""" + return max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in subagents) - len(subagents)) + + +def later_fixes_of(start: Route | None, history: list[BranchChunk] | None) -> int | None: + """How many later chunks fixed code shipped by the chunk in history that shipped the item start names. None where no item routed the chunk, history could not be read, or no chunk in it shipped the item.""" + # lilleman chose on 2026-10-28 to find a routed chunk's chunk on the default branch by the item its route names, not by commit titles: it needs no title matching, and works where the worker's transcript doesn't show the titles; a chunk whose PR didn't remove its item reads as unknown. + if start is None or not start.item or history is None: + return None + return next((len(chunk.fixed_by) for chunk in history if any(shipped.id == start.item for shipped in chunk.shipped)), None) + + +def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]: + """How many of the worker's Agent calls open with each escalation trigger's number.""" + opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values()) + return collections.Counter(int(found[1]) for found in opened if found) + + +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 rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: + """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker.""" + # An outcome is stamped to the second, as 2026-10-15T00:00:00Z, and a message to the millisecond, so the message's stamp is cut to the second to compare them as text. + second = timestamp[:19] + "Z" + found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") + route = route_from(found) + return route.rung if route else found + + +def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: + """The model the subagent ran, at the effort its Agent call set, or else at the worker's.""" + model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown")) + effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "") + return Rung(model, str(effort)) + + +def results(entries: list[dict]) -> dict[str, str]: + """Each tool result's text by the id of the call it answers.""" + return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))} + + +def commit_titles(worker: list[dict], home: str) -> list[str]: + """The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title.""" + return list(dict.fromkeys( + commit.messages[0].split("\n", 1)[0] + for entry in worker for part in assistant_parts(entry) + if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict) + for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages + )) diff --git a/bin/routing_figures/dollars.py b/bin/routing_figures/dollars.py new file mode 100644 index 00000000..97538339 --- /dev/null +++ b/bin/routing_figures/dollars.py @@ -0,0 +1,80 @@ +"""Dollars a chunk's messages cost, by project, subagent type, rung and tool: each model's recorded cost split across its messages by their list prices.""" +import collections +import dataclasses +import typing + +from claude_code.entries import assistant_parts, tool_call +from routing_figures.prices import listed + +DIMENSIONS = ("project", "subagent type", "rung", "tool") +# Each of DIMENSIONS to its labels' dollars. +Dollars = dict[str, collections.defaultdict[str, float]] +# The tool label of a message that follows no tool call, such as the first message after a prompt. +PROMPT = "prompt" +# The subagent type the judge's runs are counted under; the judge is no subagent, and has no tools, so its dollars count towards PROMPT. +JUDGE = "judge" + + +@dataclasses.dataclass(frozen=True) +class Message: + """An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices.""" + at: str + tools: list[str] + model: str + list_price: float + + +class Spent(typing.NamedTuple): + """A message with the subagent type that wrote it, or `worker`, and the rung it ran on.""" + kind: str + rung: str + message: Message + + +def messages(entries: list[dict]) -> list[Message]: + """The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in.""" + # Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last. + kept: dict[str, tuple[str, dict, list[str]]] = {} + for entry in entries: + if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict): + continue + found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, [])) + found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str)) + counted = [] + before = [PROMPT] + for at, message, called in kept.values(): + model = str(message.get("model") or "") + counted.append(Message(at, before, model, listed(model, message.get("usage")))) + before = called or [PROMPT] + return counted + + +# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...} +def recorded_costs(worker: list[dict]) -> dict[str, float]: + """The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too.""" + for entry in reversed(worker): + if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict): + return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))} + return {} + + +def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: + """Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" + listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float) + for _, _, message in spent: + listed_by_model[message.model] += message.list_price + scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded} + dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} + for kind, rung, message in spent: + cost = message.list_price * scale.get(message.model, 1.0) + dollars["project"][project] += cost + dollars["subagent type"][kind] += cost + dollars["rung"][rung] += cost + for tool in message.tools: + dollars["tool"][tool] += cost / len(message.tools) + for rung, cost in judged: + dollars["project"][project] += cost + dollars["subagent type"][JUDGE] += cost + dollars["rung"][rung] += cost + dollars["tool"][PROMPT] += cost + return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model]) diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py deleted file mode 100644 index 2e8a2ad0..00000000 --- a/bin/routing_figures/measure.py +++ /dev/null @@ -1,367 +0,0 @@ -"""Dollar spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures.""" -import collections -import dataclasses -import re -import statistics -import typing - -from claude_code.entries import assistant_parts, parts, tool_call, tool_result -from branch_chunks.cut import BranchChunk -from git_command import commits -from model_routing.route import ESCALATION_MARKER, Route, route_from -from transcript_archive.outcomes import judge_costs -from routing_figures.prices import listed -from model_routing.ladder import position, Rung -from round_titles import rounds_past_first -from shell_command import simple_commands -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") -# Each of DIMENSIONS to its labels' dollars. -Dollars = dict[str, collections.defaultdict[str, float]] -# The tool label of a message that follows no tool call, such as the first message after a prompt. -PROMPT = "prompt" -# The subagent type the judge's runs are counted under; the judge is no subagent, and has no tools, so its dollars count towards PROMPT. -JUDGE = "judge" -ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):") - - -@dataclasses.dataclass(frozen=True) -class Subagent: - """kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries.""" - kind: str - launched_by: str - entries: list[dict] - - -@dataclasses.dataclass(frozen=True) -class Chunk: - """outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries.""" - project: str - outcomes: list[str] - worker: list[dict] - subagents: list[Subagent] - - -@dataclasses.dataclass(frozen=True) -class Reports: - """How many subagents of a type reported, and the characters of their reports and of the tool results they read.""" - subagents: int - report: int - searches: int - - def __add__(self, other: "Reports") -> "Reports": - return Reports(self.subagents + other.subagents, self.report + other.report, self.searches + other.searches) - - -@dataclasses.dataclass(frozen=True) -class ChunkFigures: - """dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no item routed it, its project's default branch could not be read, or no chunk on that branch shipped its item.""" - dollars: Dollars - start: Rung | None - rounds_past_first: int - unfinished: int - delegated: collections.Counter[str] - reports: dict[str, Reports] - escalated: collections.Counter[int] - unattributed: float - lacking: int = 0 - fixed_later: int | None = None - - -@dataclasses.dataclass(frozen=True) -class Figures: - """escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the routed chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why.""" - chunks: int - dollars: Dollars - routed: dict[Rung, list[ChunkFigures]] - reports: dict[str, Reports] - escalated: collections.Counter[int] - skipped: tuple[str, ...] = () - unattributed: float = 0.0 - lacking: int = 0 - unmatched: int = 0 - unread: tuple[str, ...] = () - - -@dataclasses.dataclass(frozen=True) -class Message: - """An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices.""" - at: str - tools: list[str] - model: str - list_price: float - - -class Spent(typing.NamedTuple): - """A message with the subagent type that wrote it, or `worker`, and the rung it ran on.""" - kind: str - rung: str - message: Message - - -def measured(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) -> ChunkFigures: - """history is the chunks on the project's default branch, None where it could not be read.""" - cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0]) - spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] - launches = agent_calls(chunk.worker) - reported = results(chunk.worker) - delegated: collections.Counter[str] = collections.Counter() - reports: dict[str, Reports] = {} - for subagent in chunk.subagents: - 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(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values()))) - spent += [Spent(kind, rung, message) for message in messages(subagent.entries)] - judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] - dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) - start = route_from(cycles[0][1]) if cycles else None - return ChunkFigures( - dollars=dollars, - start=start.rung if start and start.item else None, - rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)), - unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), - delegated=delegated, - reports=reports, - escalated=escalations(launches), - unattributed=unattributed, - lacking=transcripts_lacking(launches, chunk.subagents), - fixed_later=later_fixes_of(start, history), - ) - - -def transcripts_lacking(launches: dict[str, tuple[str, dict]], subagents: list[Subagent]) -> int: - """How many Agent calls, the worker's and its subagents', have no subagent transcript in the archive. Each transcript answers one call, so they are the calls less the transcripts.""" - return max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in subagents) - len(subagents)) - - -def later_fixes_of(start: Route | None, history: list[BranchChunk] | None) -> int | None: - """How many later chunks fixed code shipped by the chunk in history that shipped the item start names. None where no item routed the chunk, history could not be read, or no chunk in it shipped the item.""" - # lilleman chose on 2026-10-28 to find a routed chunk's chunk on the default branch by the item its route names, not by commit titles: it needs no title matching, and works where the worker's transcript doesn't show the titles; a chunk whose PR didn't remove its item reads as unknown. - if start is None or not start.item or history is None: - return None - return next((len(chunk.fixed_by) for chunk in history if any(shipped.id == start.item for shipped in chunk.shipped)), None) - - -def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]: - """How many of the worker's Agent calls open with each escalation trigger's number.""" - opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values()) - return collections.Counter(int(found[1]) for found in opened if found) - - -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 - - -# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...} -def recorded_costs(worker: list[dict]) -> dict[str, float]: - """The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too.""" - for entry in reversed(worker): - if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict): - return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))} - return {} - - -def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: - """Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" - listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float) - for _, _, message in spent: - listed_by_model[message.model] += message.list_price - scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded} - dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} - for kind, rung, message in spent: - cost = message.list_price * scale.get(message.model, 1.0) - dollars["project"][project] += cost - dollars["subagent type"][kind] += cost - dollars["rung"][rung] += cost - for tool in message.tools: - dollars["tool"][tool] += cost / len(message.tools) - for rung, cost in judged: - dollars["project"][project] += cost - dollars["subagent type"][JUDGE] += cost - dollars["rung"][rung] += cost - dollars["tool"][PROMPT] += cost - return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model]) - - -def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: - """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker.""" - second = timestamp[:19] + "Z" - found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") - route = route_from(found) - return route.rung if route else found - - -def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: - """The model the subagent ran, at the effort its Agent call set, or else at the worker's.""" - model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown")) - effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "") - return Rung(model, str(effort)) - - -def messages(entries: list[dict]) -> list[Message]: - """The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in.""" - # Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last. - kept: dict[str, tuple[str, dict, list[str]]] = {} - for entry in entries: - if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict): - continue - found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, [])) - found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str)) - counted = [] - before = [PROMPT] - for at, message, called in kept.values(): - model = str(message.get("model") or "") - counted.append(Message(at, before, model, listed(model, message.get("usage")))) - before = called or [PROMPT] - return counted - - -def results(entries: list[dict]) -> dict[str, str]: - """Each tool result's text by the id of the call it answers.""" - return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))} - - -def commit_titles(worker: list[dict], home: str) -> list[str]: - """The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title.""" - return list(dict.fromkeys( - commit.messages[0].split("\n", 1)[0] - for entry in worker for part in assistant_parts(entry) - if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict) - for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages - )) - - -def due(cycle: int, last_measured: int) -> bool: - """Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK.""" - return cycle >= last_measured + CYCLES_PER_CHECK - - -def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures: - dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} - for chunk in chunks: - for dimension in DIMENSIONS: - for label, amount in chunk.dollars.get(dimension, {}).items(): - dollars[dimension][label] += amount - routed: dict[Rung, list[ChunkFigures]] = {} - reports: dict[str, Reports] = {} - for chunk in chunks: - if chunk.start: - routed.setdefault(chunk.start, []).append(chunk) - for kind, found in chunk.reports.items(): - reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found - return Figures( - chunks=len(chunks), - dollars=dollars, - routed=routed, - reports=reports, - escalated=summed(chunks, lambda chunk: chunk.escalated), - skipped=skipped, - unattributed=sum(chunk.unattributed for chunk in chunks), - lacking=sum(chunk.lacking for chunk in chunks), - unmatched=sum(chunk.start is not None and chunk.fixed_later is None for chunk in chunks), - unread=unread, - ) - - -def calls(figures: Figures) -> list[str]: - """Each routing change the figures call for, worded alike whatever the numbers, so a call already raised is known again.""" - compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position) - found = [] - for lower, upper in zip(compared, compared[1:]): - 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: reports and searches are both text the worker would read, so their sums compare their shares of its context. - 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 - - -def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float: - return statistics.mean(map(of, chunks)) - - -def basis(figures: Figures) -> str: - """What the dollars are, what they leave out, and where the archive falls short of the recorded cost.""" - text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none." - if figures.unattributed: - text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive." - if figures.lacking: - text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls." - return text - - -def fixes_basis(figures: Figures) -> str: - """What the later fixes column counts, and how many routed chunks it can't count.""" - text = "A routed chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, counted as `score-outcomes` counts them. A recent chunk has had less time to gather any. The routed chunk is matched to the chunk on that branch that removed the item its route names from todo.md. The column gives the mean over a rung's chunks whose later fixes are known, and how many those are." - if figures.unmatched: - text += f" The later fixes of {figures.unmatched} of the routed chunks are unknown, since no chunk on the branch removed their item from todo.md, or the branch could not be read." - return text - - -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'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}", - "## 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"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))], - "## Routed chunks by the rung they started on", - fixes_basis(figures), - table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [ - (str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", fixes_per_chunk(chunks), subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated))) - for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0])) - ]), - "## Escalations by trigger across every chunk, routed or not", - f"{triggers(figures.escalated) or 'None'}.", - "## Subagent reports against the searches they ran, in characters", - table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]), - *(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []), - *(["## Default branches unread","".join(f"- {project}\n" for project in figures.unread).rstrip("\n")] if figures.unread else []), - ] - return "\n\n".join(sections) + "\n" - - -def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter: - return sum(map(of, chunks), collections.Counter()) - - -def fixes_per_chunk(chunks: list[ChunkFigures]) -> str: - """The mean later fixes of the chunks whose later fixes are known, and how many those are, as `1.0 (3 known)`; `unknown` where none is.""" - # A mean, not a median: most chunks gather no later fix, so the median reads 0 until over half do, and can't show the rise per finished chunk that goal 1's counter-signal watches. - known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None] - return f"{statistics.mean(known):.1f} ({len(known)} known)" if known else "unknown" - - -def subagent_rungs(chunks: list[ChunkFigures]) -> str: - """The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`.""" - return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common()) - - -def triggers(escalated: collections.Counter[int]) -> str: - """Escalations as `trigger 2: 3, trigger 3: 1`.""" - return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items())) - - -def money(dollars: float) -> str: - return f"${dollars:,.2f}" - - -def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str: - if not rows: - return "None." - return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows]) diff --git a/bin/routing_figures/render.py b/bin/routing_figures/render.py new file mode 100644 index 00000000..b0ab9c57 --- /dev/null +++ b/bin/routing_figures/render.py @@ -0,0 +1,100 @@ +"""The routing figures as the markdown kept at the archive's root.""" +import collections +import statistics +import typing + +from routing_figures.calls import Call, Figures, mean, summed +from routing_figures.chunk import ChunkFigures +from routing_figures.dollars import DIMENSIONS +from model_routing.ladder import position + + +def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str: + """The figures as markdown, for the human to read. 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'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}", + "## Calls for a routing change", + bullets([call.sentence() for call in found]) or "None.", + *[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", dollars_table(figures, dimension))], + "## Routed chunks by the rung they started on", + fixes_basis(figures), + routed_table(figures), + "## Escalations by trigger across every chunk, routed or not", + f"{triggers(figures.escalated) or 'None'}.", + "## Subagent reports against the searches they ran, in characters", + table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]), + *(["## Chunks skipped, unreadable", bullets(figures.skipped)] if figures.skipped else []), + *(["## Default branches unread", bullets(figures.unread)] if figures.unread else []), + ] + return "\n\n".join(sections) + "\n" + + +def dollars_table(figures: Figures, dimension: str) -> str: + """The dimension's labels and their dollars, largest first.""" + return table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]) + + +def routed_table(figures: Figures) -> str: + """One row per rung the routed chunks started on, from the bottom of the ladder up.""" + return table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [ + ( + str(rung), + str(len(chunks)), + f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", + f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", + fixes_per_chunk(chunks), + subagent_rungs(chunks), + triggers(summed(chunks, lambda chunk: chunk.escalated)), + ) + for rung, chunks in sorted(figures.routed.items(), key=lambda routed: position(routed[0])) + ]) + + +def bullets(lines: typing.Iterable[str]) -> str: + return "\n".join(f"- {line}" for line in lines) + + +def basis(figures: Figures) -> str: + """What the dollars are, what they leave out, and where the archive falls short of the recorded cost.""" + text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none." + if figures.unattributed: + text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive." + if figures.lacking: + text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls." + return text + + +def fixes_basis(figures: Figures) -> str: + """What the later fixes column counts, and how many routed chunks it can't count.""" + text = "A routed chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, counted as `score-outcomes` counts them. A recent chunk has had less time to gather any. The routed chunk is matched to the chunk on that branch that removed the item its route names from todo.md. The column gives the mean over a rung's chunks whose later fixes are known, and how many those are." + if figures.unmatched: + text += f" The later fixes of {figures.unmatched} of the routed chunks are unknown, since no chunk on the branch removed their item from todo.md, or the branch could not be read." + return text + + +def fixes_per_chunk(chunks: list[ChunkFigures]) -> str: + """The mean later fixes of the chunks whose later fixes are known, and how many those are, as `1.0 (3 known)`; `unknown` where none is.""" + # A mean, not a median: most chunks gather no later fix, so the median reads 0 until over half do, and can't show the rise per finished chunk that goal 1's counter-signal watches. + known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None] + return f"{statistics.mean(known):.1f} ({len(known)} known)" if known else "unknown" + + +def subagent_rungs(chunks: list[ChunkFigures]) -> str: + """The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`.""" + return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common()) + + +def triggers(escalated: collections.Counter[int]) -> str: + """Escalations as `trigger 2: 3, trigger 3: 1`.""" + return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items())) + + +def money(dollars: float) -> str: + return f"${dollars:,.2f}" + + +def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str: + if not rows: + return "None." + return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows]) diff --git a/bin/routing_figures/state.py b/bin/routing_figures/state.py new file mode 100644 index 00000000..f6d11a9e --- /dev/null +++ b/bin/routing_figures/state.py @@ -0,0 +1,124 @@ +"""What loop-claude keeps at the archive's root between measurements: the cycle it last measured at and each call it raised, as fields in STATE, and the calls raised as lines the human reads in RAISED, where a reset is written: docs/decisions.md → `routing:`.""" +import dataclasses +import json +import pathlib +import re + +from routing_figures.calls import Call, SENTENCES +from failure import Failure +from file_writes import replace_file +from utc_stamp import STAMPED + +CYCLES_PER_CHECK = 20 +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" +# {"measured_at": 40, "raised": [{"at": "2026-10-15T00:00:00Z", "kind": "reports", "subjects": ["Explore"]}]} +STATE = "routing-state.json" + + +@dataclasses.dataclass(frozen=True) +class Stamped: + """A call and when it was raised.""" + at: str + call: Call + + +@dataclasses.dataclass(frozen=True) +class State: + """measured_at is the cycle the kept figures were measured at, 0 before any; raised holds every call raised, oldest first.""" + measured_at: int + raised: tuple[Stamped, ...] + + +@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[Call] + + +def due(cycle: int, measured_at: int) -> bool: + """Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK.""" + return cycle >= measured_at + CYCLES_PER_CHECK + + +def read_state(root: pathlib.Path) -> State | Failure: + """The kept state; before any is kept, no measurement and no call.""" + try: + text = (root / STATE).read_text(encoding="utf-8") + except FileNotFoundError: + return State(0, ()) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {root / STATE}: {failure}") + return decoded(text) or Failure(f"could not read {root / STATE}: not the shape its comment in routing_figures/state.py shows") + + +def decoded(text: str) -> State | None: + try: + data = json.loads(text) + except ValueError: + return None + if not isinstance(data, dict) or type(data.get("measured_at")) is not int or not isinstance(data.get("raised"), list): + return None + raised = [stamped(entry) for entry in data["raised"]] + return State(data["measured_at"], tuple(entry for entry in raised if entry)) if all(raised) else None + + +def stamped(entry: object) -> Stamped | None: + if not isinstance(entry, dict) or not isinstance(at := entry.get("at"), str) or (kind := entry.get("kind")) not in SENTENCES: + return None + subjects = entry.get("subjects") + if not isinstance(subjects, list) or not all(isinstance(subject, str) for subject in subjects) or len(subjects) != SENTENCES[kind].count("{}"): + return None + return Stamped(at, Call(kind, tuple(subjects))) + + +def write_state(root: pathlib.Path, state: State) -> Failure | None: + text = json.dumps({"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t") + unwritten = replace_file(root / STATE, (text + "\n").encode()) + return Failure(f"could not write {root / STATE}: {unwritten.reason}") if unwritten else None + + +def mark_measured(root: pathlib.Path, cycle: int) -> Failure | None: + kept = read_state(root) + return kept if isinstance(kept, Failure) else write_state(root, dataclasses.replace(kept, measured_at=cycle)) + + +def raised(root: pathlib.Path) -> Raised | Failure: + """The calls raised after the latest reset that RAISED names.""" + text = read_raised(root) + if isinstance(text, Failure): + return text + kept = read_state(root) + if isinstance(kept, Failure): + return kept + since = max((stamp for stamp, what in RAISED_LINE.findall(text) if what == RESET), default="") + return Raised(since, frozenset(entry.call for entry in kept.raised if entry.at > since)) + + +def mark_raised(root: pathlib.Path, calls: list[Call], at: str) -> Failure | None: + """Keeps the calls in STATE, and adds a line for each to RAISED.""" + kept = read_state(root) + if isinstance(kept, Failure): + return kept + text = read_raised(root) + if isinstance(text, Failure): + return text + if unwritten := write_state(root, dataclasses.replace(kept, raised=kept.raised + tuple(Stamped(at, call) for call in calls))): + return unwritten + # The first line opens a list below the heading; each later one joins it. + gap = "\n" if RAISED_LINE.search(text) else "\n\n" + unwritten = replace_file(root / RAISED, (text.rstrip("\n") + gap + "".join(f"- {at} {call.sentence()}\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}") diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 23614f74..d945ac8e 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -14,15 +14,18 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from routing_figures import archive +from routing_figures import archive, state from branch_chunks.cut import BranchChunk -from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals +from routing_figures.calls import Call, calls, totals +from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent +from routing_figures.state import due from failure import Failure import git_repo from test_env import isolated_env from todo_table import Item from model_routing.ladder import LADDER, Rung from transcript_archive import outcomes, write +from routing_figures.render import render from model_routing.route import Route LOW = Rung("claude-opus-5-5", "medium") @@ -77,7 +80,7 @@ class Measured(unittest.TestCase): message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}), ] kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j")) - found = measured(Chunk("log", [kept], worker, []), "/h") + found = chunk_figures(Chunk("log", [kept], worker, []), "/h") self.assertEqual(found.dollars["project"], {"log": 6.0}) self.assertEqual(found.dollars["subagent type"], {"worker": 6.0}) self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0}) @@ -86,7 +89,7 @@ class Measured(unittest.TestCase): def test_counts_the_judges_recorded_cost_under_the_judge_and_the_rung_it_ran_on(self): kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "judge-rung", "", judge_cost=0.5)) + stamped("2026-10-14T12:00:00Z", outcomes.finished(LOW_ROUTE, "m", "judge-rung", judge_cost=0.25)) + stamped("2026-10-14T12:00:00Z", outcomes.rejected("why", "{}", "other-rung", judge_cost=1.0)) - found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T10:00:00Z")], []), "/h") + found = chunk_figures(Chunk("log", [kept], [message("m1", "2026-10-14T10:00:00Z")], []), "/h") self.assertEqual(found.dollars["project"], {"log": 3.75}) self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "judge": 1.75}) self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, "judge-rung": 0.75, "other-rung": 1.0}) @@ -102,7 +105,7 @@ class Measured(unittest.TestCase): 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", "j"))], worker, subagents), "/h") + found = chunk_figures(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h") self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1}) self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0}) self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)}) @@ -112,16 +115,16 @@ class Measured(unittest.TestCase): message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", prompt="Escalation trigger 2: the test failed twice"), call("Agent", "a2", prompt="Escalation trigger 2: again"), call("Agent", "a3", prompt="Escalation trigger 3: a 🔴 in round 2")), message("m2", "2026-10-14T10:01:00Z", call("Agent", "a4", prompt="Find the callers. Escalation trigger 1: not at the start"), call("Agent", "a5", prompt="Escalation trigger x: no number")), ] - self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1}) + self.assertEqual(chunk_figures(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1}) def test_counts_review_rounds_past_each_passs_first_once_per_title(self): commit = lambda id_, title: message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'")) worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")] - self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1) + self.assertEqual(chunk_figures(Chunk("log", [], worker, []), "/h").rounds_past_first, 1) def fixed_later(self, history, route=LOW_ROUTE): """The later fixes measured counts for a chunk that route started, which LOW_ROUTE does by item 7, on a project whose default branch holds history, None where it could not be read.""" - return measured(Chunk("log", [stamped("2026-10-14T10:00:00Z", outcomes.finished(route, "m", "j"))], [], []), "/h", history).fixed_later + return chunk_figures(Chunk("log", [stamped("2026-10-14T10:00:00Z", outcomes.finished(route, "m", "j"))], [], []), "/h", history).fixed_later def test_counts_the_later_fixes_of_the_chunk_that_shipped_the_item_its_route_names(self): self.assertEqual(self.fixed_later([shipping(6, fixed_by=("c", "d", "e")), shipping(5, 7, fixed_by=("c", "d"))]), 2) @@ -141,7 +144,7 @@ class Measured(unittest.TestCase): def test_starts_no_route_for_a_chunk_no_item_routed(self): kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j")) - found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") + found = chunk_figures(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") self.assertIsNone(found.start) self.assertEqual(found.dollars["rung"], {str(LOW): 2.0}) @@ -153,14 +156,14 @@ class Measured(unittest.TestCase): message("m3", "2026-10-14T10:31:00Z", call("Agent", "a2", subagent_type="Explore")), ] subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])] - found = measured(Chunk("log", [kept], worker, subagents), "/h") + found = chunk_figures(Chunk("log", [kept], worker, subagents), "/h") self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1}) self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0}) def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self): worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))] subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])] - self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)}) + self.assertEqual(chunk_figures(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)}) def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self): worker = [ @@ -170,20 +173,20 @@ class Measured(unittest.TestCase): {"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}}, {"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}}, ] - found = measured(Chunk("log", [], worker, []), "/h") + found = chunk_figures(Chunk("log", [], worker, []), "/h") self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0}) self.assertEqual(found.dollars["project"], {"log": 12.0}) def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self): usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000} - opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") + opus = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20) - sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h") + sonnet = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h") self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10) def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self): usage = {"cache_creation_input_tokens": 1_000_000} - found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") + found = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") self.assertAlmostEqual(found.dollars["project"]["log"], 5) def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self): @@ -194,31 +197,31 @@ class Measured(unittest.TestCase): cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5), ] subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])] - found = measured(Chunk("log", [], worker, subagents), "/h") + found = chunk_figures(Chunk("log", [], worker, subagents), "/h") self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0}) self.assertEqual(found.dollars["project"], {"log": 9.0}) self.assertEqual(found.unattributed, 0.5) def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self): worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))] - found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h") + found = chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h") self.assertEqual(found.lacking, 1) - unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h") + unnamed = chunk_figures(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h") self.assertEqual(unnamed.lacking, 0) nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))] - launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h") + launched = chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h") self.assertEqual(launched.lacking, 0) - self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1) + self.assertEqual(chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1) def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self): undated = message("m1", "") del undated["timestamp"] kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j")) - self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0}) + self.assertEqual(chunk_figures(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0}) def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self): worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)] - found = measured(Chunk("log", [], worker, []), "/h") + found = chunk_figures(Chunk("log", [], worker, []), "/h") self.assertEqual(found.dollars["project"], {"log": 4.0}) self.assertEqual(found.unattributed, 0.0) @@ -226,15 +229,14 @@ class Measured(unittest.TestCase): class Calls(unittest.TestCase): def test_calls_when_chunks_on_a_rung_took_more_rounds_or_unfinished_verdicts_than_the_rung_above(self): chunks = [figures(LOW, rounds=2)] * 5 + [figures(HIGH, unfinished=1)] * 5 - self.assertEqual(calls(totals(chunks)), [ - f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.", - ]) - self.assertEqual(calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5)), [ - f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.", - ]) + self.assertEqual(calls(totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))]) + self.assertEqual(calls(totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.") + [unfinished] = calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5)) + self.assertEqual(unfinished, Call("unfinished", (str(LOW), str(HIGH)))) + self.assertEqual(unfinished.sentence(), f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.") def test_compares_the_bottom_rungs_and_calls_nothing_on_a_tie(self): - self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [f"Chunks routed onto {LADDER[0]} took more review rounds past each pass's first than chunks routed onto {LADDER[1]}."]) + self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [Call("rounds", (str(LADDER[0]), str(LADDER[1])))]) self.assertEqual(calls(totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), []) self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), []) @@ -242,17 +244,17 @@ class Calls(unittest.TestCase): self.assertEqual(calls(totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), []) def test_calls_when_a_subagent_types_reports_outgrow_the_searches_they_ran(self): - self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5)), [ - "Explore subagents' reports took more of the worker's context than their searches would have.", - ]) + [call] = calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5)) + self.assertEqual(call, Call("reports", ("Explore",))) + self.assertEqual(call.sentence(), "Explore subagents' reports took more of the worker's context than their searches would have.") self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), []) self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), []) def test_renders_each_dimension_largest_first_and_the_calls(self): chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0) - text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "") + text = render(totals([chunk]), [Call("reports", ("Explore",))], "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("## Calls for a routing change\n\n- Explore subagents' reports took more of the worker's context than their searches would have.\n", text) self.assertIn("## Dollars by project", text) self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text) self.assertIn("cache reads included", text) @@ -318,7 +320,7 @@ class Archive(unittest.TestCase): found = archive.measure_archive(self.root, "/h", "", no_checkout) self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}]) self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) - self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.Measured([], ())) + self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ())) def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self): home = self.root / "home" @@ -407,26 +409,40 @@ class Archive(unittest.TestCase): self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1"))) self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, "")) - 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_keeps_the_cycle_it_measured_at_and_reads_it_back(self): + self.assertEqual(state.read_state(self.root), state.State(0, ())) + self.assertIsNone(state.mark_measured(self.root, 40)) + self.assertEqual(state.read_state(self.root), state.State(40, ())) + self.assertIsNone(archive.write_figures(self.root, "# Routing figures\n")) + self.assertEqual(state.read_state(self.root).measured_at, 40, "the rendered figures are for the human, and never read back") 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.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", "C."], "2026-10-15T00:30:00Z")) - self.assertEqual(archive.raised(self.root), archive.Raised("2026-10-15T00:30:00Z", frozenset({"B."}))) + a, b, c = Call("reports", ("Explore",)), Call("rounds", ("x", "y")), Call("unfinished", ("x", "y")) + self.assertEqual(state.raised(self.root), state.Raised("", frozenset())) + self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z")) + self.assertIsNone(state.mark_raised(self.root, [b], "2026-10-15T01:00:00Z")) + self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n") + self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b}))) + with open(self.root / state.RAISED, "a") as handle: + handle.write("- 2026-10-15T00:30:00Z Reset\n") + self.assertIsNone(state.mark_raised(self.root, [c], "2026-10-15T00:20:00Z")) + self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T00:30:00Z", frozenset({b}))) - def test_reads_no_measured_cycle_from_figures_that_name_none(self): - (self.root / archive.FIGURES).write_text("# Routing figures\n") - self.assertEqual(archive.last_measured(self.root), 0) - (self.root / archive.FIGURES).unlink() - (self.root / archive.FIGURES).mkdir() - self.assertIsInstance(archive.last_measured(self.root), Failure) + def test_knows_a_raised_call_by_its_fields_whatever_its_line_reads(self): + call = Call("reports", ("Explore",)) + self.assertIsNone(state.mark_raised(self.root, [call], "2026-10-15T00:00:00Z")) + (self.root / state.RAISED).write_text("# Routing calls raised\n\n- 2026-10-15T00:00:00Z Reworded.\n") + self.assertEqual(state.raised(self.root).calls, frozenset({call})) + + def test_fails_on_a_state_it_cannot_read(self): + for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}'): + with self.subTest(text): + (self.root / state.STATE).write_text(text) + self.assertIsInstance(state.read_state(self.root), Failure) + self.assertIsInstance(state.raised(self.root), Failure) + (self.root / state.STATE).unlink() + (self.root / state.STATE).mkdir() + self.assertIsInstance(state.read_state(self.root), Failure) def test_holds_the_lock_while_no_other_loop_does(self): with archive.locked(self.root) as held, archive.locked(self.root) as other: @@ -435,8 +451,8 @@ class Archive(unittest.TestCase): self.assertTrue(again) def test_fails_on_an_archive_it_cannot_read(self): - (self.root / archive.RAISED).mkdir() - self.assertIsInstance(archive.raised(self.root), Failure) + (self.root / state.RAISED).mkdir() + self.assertIsInstance(state.raised(self.root), Failure) if __name__ == "__main__": diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 28df02c4..917f3a02 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1068,3 +1068,18 @@ Read most (opens and searches): - `AGENTS.md` 2 - `CHANGELOG.md` 1 - `README.md` 1 + +## Reading cost, chunk efca40024e84, finished 2026-11-08T18:44:32Z + +87773 new input tokens before the first commit. + +Read most (opens and searches): + +- `docs/comprehension-history.md` 8 +- `bin/comprehension_history.py` 7 +- `bin/larv_review/test_larv_review.py` 6 +- `todo.md` 4 +- `CHANGELOG.md` 1 +- `README.md` 1 +- `bin/larv_review/agreement.py` 1 +- `bin/markdown_text.py` 1 diff --git a/todo.md b/todo.md index 5d873110..b5008439 100644 --- a/todo.md +++ b/todo.md @@ -13,13 +13,11 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | -| 139 | 0.7.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 | | 158 | 0.7.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 | | 155 | 0.7.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | code health by 4, 1.4 by 6 | 9.6 | | 215 | 0.7.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 9.0 | | 237 | 0.7.0 | | principle | **Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.** | 2 | 1 | 2 | 3 | 3 | code health by 2 | 9.0 | | 242 | 0.7.0 | | principle | **Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.** | 2 | 1 | 1 | 2 | 3 | code health by 2 | 9.0 | -| 49 | 0.7.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 8.4 | | 263 | 0.7.0 | | | **Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 6, 1.5 by 2 | 8.1 | | 262 | 0.7.0 | | | **Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for.** | 3 | 2 | 3 | 6 | 4 | 1.2 by 7, 1.5 by 5 | 8.0 | | 105 | 0.7.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 8.0 | @@ -29,7 +27,6 @@ | 184 | 0.7.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 | | 221 | 0.7.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 3 | 1 | 3 | 5 | 5 | code health by 4 | 7.2 | | 116 | 0.7.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 7.0 | -| 203 | 0.7.0 | | | **Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 7.0 | | 113 | 0.7.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 | | 112 | 0.7.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 6.3 | | 124 | 0.7.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 5.7 | @@ -84,10 +81,6 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3). -### 139. Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders. - -The paired ruling on PR #265 ruled worse. Make these places easier to read: `measure.py` `measured` and `render` (token attribution, subagent rungs, round counting, calls and rendering in one module; `measured`, `Measured` and `measure_archive` side by side); `calls` with `archive.py` `raised` and `last_measured`, where a call's identity is its sentence and the measured cycle is read back from rendered markdown; and `Reports.searches`, which holds characters, not searches. - ### 158. Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it. F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk costs more than its size: the worker reads about 130k tokens before its first commit whatever the item, and every chunk takes its review passes. Fit cost against 2**S from the finished chunks `score-outcomes` measures, in the same units `2**S` counts, and say in `docs/decisions.md` → `todo.md: …` how far the fit holds. A chunk bundling tiny items shares F between them. @@ -108,10 +101,6 @@ Found by the principles audit of PR #376. "About seven things per level" in `pri "Tests" in `principles/technical-principles.md`. The principles audit of PR #380 found test bodies that loop over their cases without `subTest`, some checking several behaviours at once: `bin/judge_replay/test_judge_replay.py:38`, `:139`, `:176`; `bin/loop_claude/test_loop_claude.py:590`; `bin/machine_load/test_machine_load.py:19`, `:31`; `bin/rule_hook/test_rule_hook.py:480`; `bin/subagent_rung/test_subagent_rung.py:32`, `:43`, `:45`; `bin/test_settings_filter.py:28`; `bin/test_statusline.py:102`. The first failing case stops the loop, and without a message the failure doesn't say which case broke. Split the tests that check several behaviours at once, `test_judge_replay.py:176` and `test_subagent_rung.py:43-46`, into one test per behaviour ("One behaviour per test"). -### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`. - -DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy. - ### 263. Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open. 43 of the 175 chunks with an interrupt asked two or more times, and hold 123 of the archive's 255 interrupts (2026-11-08). Examples: adf-codec asked 4 times between 19:04 and 20:54 on 2026-11-04, 3 of them on item 167; bender-infra asked 3 times on 2026-10-21 whether to grant principles and stability one more round; fejkdata asked twice in 4 minutes on 2026-10-12 to cut 0.1.0. The judge already reads the transcript (`docs/decisions.md:45`), so it sees the earlier answer. The change touches `bin/loop_claude/cycle/judge.py` `quotes_checked` and `grounded`; make them easier to read, as the seats named them. @@ -162,10 +151,6 @@ In `bin/loop_claude/loop/main.py`'s docstring, the line holding "of one PR, is f `score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known. -### 203. Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds. - -A retitled decision leaves its citations in `todo.md` stale, and no check reads them. `test_citations.py` covers only citations of `CLAUDE.md` and of rule files. Item 49 covers `AGENTS.md`'s list of titles, not these citations. - ### 113. Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists. `score-outcomes` grounds L, E, I and S in finished chunks only. Where an item names files or units, their size bounds what the change can touch. @@ -247,7 +232,7 @@ Weak evidence: the review folders under `~/.local/state/larv-review/`, review re ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. -Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2). +Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2). ### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it. @@ -259,7 +244,7 @@ Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin ### 269. Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids. -The `Judge cost:` line is new under `CHANGELOG.md` → "Unreleased", and no outcomes file in the archive holds one yet (2026-11-08). Of the 460 verdicts that name their judge, 48 ran on opus at xhigh, 78 at high and 310 at medium. In this repo the judge reads about 175k characters of records each time: `AGENTS.md`, `docs/decisions.md`, `CLAUDE.md`, `rules/` and larv-review's standards. `bin/routing_figures/measure.py` already adds the lines to the dollars by rung. +The `Judge cost:` line is new under `CHANGELOG.md` → "Unreleased", and no outcomes file in the archive holds one yet (2026-11-08). Of the 460 verdicts that name their judge, 48 ran on opus at xhigh, 78 at high and 310 at medium. In this repo the judge reads about 175k characters of records each time: `AGENTS.md`, `docs/decisions.md`, `CLAUDE.md`, `rules/` and larv-review's standards. `bin/routing_figures/dollars.py` already adds the lines to the dollars by rung. ### 267. Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop. @@ -333,11 +318,11 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic ### 187. Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context. -Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/measure.py`), so neither sees the report reads. Found by the architecture review of PR #310. +Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/chunk.py`), so neither sees the report reads. Found by the architecture review of PR #310. ### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars. -Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/measure.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with. Item 139 splits `measure.py`; where this change touches `measured`, make it easier to read, as the seats named it. +Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/chunk.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with. ### 266. Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project. -- 2.52.0 From f0ff379251daadbba4fd3782bed26bf7b3927457 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 20:02:58 +0100 Subject: [PATCH 2/4] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(0=20misread);=20slim=20chun?= =?UTF-8?q?k=5Ffigures,=20type=20a=20call's=20kind,=20keep=20the=20state?= =?UTF-8?q?=20through=20replace=5Fjson,=20add=20the=20missing=20state=20an?= =?UTF-8?q?d=20raise=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_loop_claude.py | 11 +++++++ bin/repo_checks/test_citations.py | 2 +- bin/routing_figures/calls.py | 12 +++++--- bin/routing_figures/chunk.py | 34 ++++++++++++++------- bin/routing_figures/render.py | 4 +-- bin/routing_figures/state.py | 11 ++++--- bin/routing_figures/test_routing_figures.py | 28 ++++++++++++----- 9 files changed, 73 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee7dfab9..615eedfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. Both markdown files read as before, and a `Reset` line in `routing-calls-raised.md` still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once, and puts a call raised since the latest reset to you once more. +- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. The two markdown files hold what they held before. From them, loop-claude now reads only a `Reset` line in `routing-calls-raised.md`, which still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once. If the figures still make a call raised since the latest reset, it puts that call to you once more. - `loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence. ## 0.6.0 diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index c90fba99..7fa59cfa 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -1,4 +1,4 @@ -"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`.""" +"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: loop-claude measures review rounds…`.""" import pathlib from routing_figures import archive diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 6e5466f9..7cc9642b 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -21,6 +21,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, state from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal +from routing_figures.calls import Call from loop_claude.project import checkout, model_choice, records from loop_claude.loop import chunk_start, close from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed @@ -970,6 +971,16 @@ class RoutingCheck(unittest.TestCase): self.assertIsNone(stop) self.assertIn("routing figures: could not write", said) + def test_puts_every_new_call_to_the_human_and_says_one_it_cannot_keep(self): + new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))] + fake = FakeEffects(on_terminal_claude=[0]) + with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")): + self.assertIsNone(routing_check.raise_calls(self.root, "/code/log", "s1", new, Rung("m", "high"), self.paths, self.paths.waiting, fake.effects())) + ((args),) = fake.made("claude_on_terminal") + self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6]) + self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue()) + self.assertIn("routing figures: full", said.getvalue()) + class ModelPrompt(unittest.TestCase): OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] diff --git a/bin/repo_checks/test_citations.py b/bin/repo_checks/test_citations.py index 06cb373f..f4cd4548 100644 --- a/bin/repo_checks/test_citations.py +++ b/bin/repo_checks/test_citations.py @@ -52,7 +52,7 @@ class Citations(unittest.TestCase): def test_agents_md_lists_exactly_the_decision_titles(self): listed = (ROOT / "AGENTS.md").read_text().split("Decisions live in `docs/decisions.md`:\n\n")[1].split("\n\n")[0] - # AGENTS.md sorts the titles, which docs/decisions.md keeps in no order. + # The two files order the titles differently, so they are compared sorted. self.assertEqual(sorted(LISTED_TITLE.findall(listed)), sorted(DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text()))) def test_every_todo_citation_of_a_decision_names_a_title(self): diff --git a/bin/routing_figures/calls.py b/bin/routing_figures/calls.py index 2a50c526..939d505f 100644 --- a/bin/routing_figures/calls.py +++ b/bin/routing_figures/calls.py @@ -1,4 +1,4 @@ -"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing:`.""" +"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing: loop-claude measures review rounds…`.""" import collections import dataclasses import statistics @@ -54,8 +54,9 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tu ) +Kind = typing.Literal["rounds", "unfinished", "reports"] # Each kind of call to the sentence it is put to the human in, filled with its subjects in order. -SENTENCES = { +SENTENCES: dict[Kind, str] = { "rounds": "Chunks routed onto {} took more review rounds past each pass's first than chunks routed onto {}.", "unfinished": "Chunks routed onto {} took more unfinished verdicts than chunks routed onto {}.", "reports": "{} subagents' reports took more of the worker's context than their searches would have.", @@ -64,8 +65,8 @@ SENTENCES = { @dataclasses.dataclass(frozen=True) class Call: - """A routing change the figures call for, known again by its fields when raised twice. kind is a key of SENTENCES; subjects are the two rungs compared, lower first, or the subagent type.""" - kind: str + """A routing change the figures call for. Its fields, not its sentence, tell whether it was raised before. kind names its sentence in SENTENCES; subjects are the two rungs compared, lower first, or the subagent type.""" + kind: Kind subjects: tuple[str, ...] def sentence(self) -> str: @@ -77,7 +78,8 @@ def calls(figures: Figures) -> list[Call]: compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position) found = [] for lower, upper in zip(compared, compared[1:]): - for kind, of in (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished)): + measures: tuple[tuple[Kind, typing.Callable[[ChunkFigures], int]], ...] = (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished)) + for kind, of in measures: if mean(figures.routed[lower], of) > mean(figures.routed[upper], of): found.append(Call(kind, (str(lower), str(upper)))) # Characters stand in for tokens: reports and the tool results their subagents read are both text the worker would read, so their sums compare their shares of its context. diff --git a/bin/routing_figures/chunk.py b/bin/routing_figures/chunk.py index 3e4d053d..274fcad0 100644 --- a/bin/routing_figures/chunk.py +++ b/bin/routing_figures/chunk.py @@ -65,21 +65,15 @@ def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = N launches = agent_calls(chunk.worker) reported = results(chunk.worker) delegated = [delegation(subagent, launches, reported, cycles) for subagent in chunk.subagents] - spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] - spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages] - judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] - dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) + dollars, unattributed = chunk_dollars(chunk, cycles, delegated) start = route_from(cycles[0][1]) if cycles else None - reports: dict[str, Reports] = {} - for one in delegated: - reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars) return ChunkFigures( dollars=dollars, start=start.rung if start and start.item else None, rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)), unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), delegated=collections.Counter(one.rung for one in delegated), - reports=reports, + reports=reports_by_type(delegated), escalated=escalations(launches), unattributed=unattributed, lacking=transcripts_lacking(launches, chunk.subagents), @@ -87,6 +81,21 @@ def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = N ) +def chunk_dollars(chunk: Chunk, cycles: list[tuple[str, str]], delegated: list[Delegation]) -> tuple[Dollars, float]: + """What costed makes of the messages of the worker, each on the rung of the cycle it ran in, and of its subagents, and of the chunk's judge runs.""" + spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] + spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages] + judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] + return costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) + + +def reports_by_type(delegated: list[Delegation]) -> dict[str, Reports]: + reports: dict[str, Reports] = {} + for one in delegated: + reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars) + return reports + + @dataclasses.dataclass(frozen=True) class Delegation: """One subagent as the figures count it: its type, the rung it ran on, the characters of its report and of the tool results it read, and its messages.""" @@ -141,13 +150,16 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]: def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker.""" - # An outcome is stamped to the second, as 2026-10-15T00:00:00Z, and a message to the millisecond, so the message's stamp is cut to the second to compare them as text. - second = timestamp[:19] + "Z" - found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") + found = next((rung for stamp, rung in cycles if stamp >= to_the_second(timestamp)), cycles[-1][1] if cycles else "unrouted") route = route_from(found) return route.rung if route else found +def to_the_second(timestamp: str) -> str: + """A message's stamp, such as 2026-10-15T00:00:00.123Z, cut to the second, as an outcome is stamped: 2026-10-15T00:00:00Z. Stamps in that one form sort as text in time order.""" + return timestamp[:19] + "Z" + + def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: """The model the subagent ran, at the effort its Agent call set, or else at the worker's.""" model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown")) diff --git a/bin/routing_figures/render.py b/bin/routing_figures/render.py index b0ab9c57..d088a62a 100644 --- a/bin/routing_figures/render.py +++ b/bin/routing_figures/render.py @@ -22,8 +22,8 @@ def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) routed_table(figures), "## Escalations by trigger across every chunk, routed or not", f"{triggers(figures.escalated) or 'None'}.", - "## Subagent reports against the searches they ran, in characters", - table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]), + "## Subagent reports against the tool results they read, in characters", + table(("Subagent type", "Subagents", "Reports", "Tool results read"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]), *(["## Chunks skipped, unreadable", bullets(figures.skipped)] if figures.skipped else []), *(["## Default branches unread", bullets(figures.unread)] if figures.unread else []), ] diff --git a/bin/routing_figures/state.py b/bin/routing_figures/state.py index f6d11a9e..9f88146a 100644 --- a/bin/routing_figures/state.py +++ b/bin/routing_figures/state.py @@ -1,4 +1,6 @@ -"""What loop-claude keeps at the archive's root between measurements: the cycle it last measured at and each call it raised, as fields in STATE, and the calls raised as lines the human reads in RAISED, where a reset is written: docs/decisions.md → `routing:`.""" +"""What loop-claude keeps at the archive's root between measurements: docs/decisions.md → `routing: loop-claude measures review rounds…`. + +STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as AGENTS.md says, and loop-claude reads the resets from there.""" import dataclasses import json import pathlib @@ -6,7 +8,7 @@ import re from routing_figures.calls import Call, SENTENCES from failure import Failure -from file_writes import replace_file +from file_writes import replace_file, replace_json from utc_stamp import STAMPED CYCLES_PER_CHECK = 20 @@ -53,7 +55,7 @@ def read_state(root: pathlib.Path) -> State | Failure: return State(0, ()) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {root / STATE}: {failure}") - return decoded(text) or Failure(f"could not read {root / STATE}: not the shape its comment in routing_figures/state.py shows") + return decoded(text) or Failure(f"could not read {root / STATE}: not the shape the comment on STATE in bin/routing_figures/state.py shows") def decoded(text: str) -> State | None: @@ -77,8 +79,7 @@ def stamped(entry: object) -> Stamped | None: def write_state(root: pathlib.Path, state: State) -> Failure | None: - text = json.dumps({"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t") - unwritten = replace_file(root / STATE, (text + "\n").encode()) + unwritten = replace_json(root / STATE, {"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t") return Failure(f"could not write {root / STATE}: {unwritten.reason}") if unwritten else None diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index d945ac8e..60b80713 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -420,13 +420,27 @@ class Archive(unittest.TestCase): a, b, c = Call("reports", ("Explore",)), Call("rounds", ("x", "y")), Call("unfinished", ("x", "y")) self.assertEqual(state.raised(self.root), state.Raised("", frozenset())) self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z")) - self.assertIsNone(state.mark_raised(self.root, [b], "2026-10-15T01:00:00Z")) - self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n") - self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b}))) + self.assertIsNone(state.mark_raised(self.root, [b, c], "2026-10-15T01:00:00Z")) + self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n- 2026-10-15T01:00:00Z {c.sentence()}\n") + self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b, c}))) with open(self.root / state.RAISED, "a") as handle: - handle.write("- 2026-10-15T00:30:00Z Reset\n") - self.assertIsNone(state.mark_raised(self.root, [c], "2026-10-15T00:20:00Z")) - self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T00:30:00Z", frozenset({b}))) + handle.write("- 2026-10-15T01:00:00Z Reset\n") + self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset()), "a call stamped at the reset's second was raised before it") + self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z")) + self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset({a}))) + + @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") + def test_fails_when_it_cannot_keep_the_state(self): + self.root.chmod(0o555) + self.addCleanup(self.root.chmod, 0o755) + self.assertIsInstance(state.mark_measured(self.root, 40), Failure) + self.assertIsInstance(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure) + + def test_fails_when_it_cannot_list_a_raised_call_for_the_human(self): + self.assertIsNone(state.mark_measured(self.root, 40)) + written = state.replace_file + with unittest.mock.patch.object(state, "replace_file", lambda path, data: Failure("full") if path.name == state.RAISED else written(path, data)): + self.assertEqual(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure(f"could not write {self.root / state.RAISED}: full")) def test_knows_a_raised_call_by_its_fields_whatever_its_line_reads(self): call = Call("reports", ("Explore",)) @@ -435,7 +449,7 @@ class Archive(unittest.TestCase): self.assertEqual(state.raised(self.root).calls, frozenset({call})) def test_fails_on_a_state_it_cannot_read(self): - for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}'): + for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": "a"}]}'): with self.subTest(text): (self.root / state.STATE).write_text(text) self.assertIsInstance(state.read_state(self.root), Failure) -- 2.52.0 From babe33943060b43c2fb2c70def3fb15b7ffbffd7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 20:02:58 +0100 Subject: [PATCH 3/4] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20fixed=20in?= =?UTF-8?q?=20the=20stability=20round's=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From fbd2e62e410618f80ed558156c51cf1bc308565b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 20:07:04 +0100 Subject: [PATCH 4/4] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0