Answer architecture round 1: 2 🔴, 4 🟡 (0 misread); one branch_chunks reader with a pure fix rule, routed chunks matched by item

This commit is contained in:
2026-10-28 21:22:25 +01:00
parent 1a81b55925
commit a16f0e4625
22 changed files with 639 additions and 595 deletions
+9 -7
View File
@@ -2,17 +2,19 @@
import contextlib
import dataclasses
import fcntl
import functools
import json
import pathlib
import re
import typing
from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks
from branch_chunks.read import branch_chunks
from branch_chunks.cut import BranchChunk
from project_key import checkout_of
from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent
from git_repo import default_ref
from git_repo import default_ref, Git
from failure import Failure
from score_outcomes.later_fixes import Landed, later_fixes
from claude_code.entries import parse_entry
from file_writes import replace_file
from utc_stamp import STAMPED
@@ -83,7 +85,7 @@ class Measured:
unread: tuple[str, ...] = ()
def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Failure:
def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> Measured | Failure:
"""The figures of each chunk that finished after since, measured one chunk at a time because the archive outgrows memory. Only an archive that cannot be listed fails."""
listed = archived_outcomes(root)
if isinstance(listed, Failure):
@@ -99,7 +101,7 @@ def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Fai
skipped.append(key)
continue
chunks = [chunk for chunk in chunks if chunk.finished > since]
history = branch_history(checkout_of(key, pathlib.Path(home))) if chunks else None
history = branch_history(checkout_of(key, pathlib.Path(home)), git) if chunks else None
if isinstance(history, Failure):
unread.append(f"{key}: {history.reason}")
history = None
@@ -116,10 +118,10 @@ def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Fai
return Measured(found, tuple(skipped), tuple(unread))
def branch_history(checkout: str) -> list[Landed] | Failure:
def branch_history(checkout: str, git: Git) -> list[BranchChunk] | Failure:
"""The chunks on the checkout's default branch as last fetched, read guarded, since the checkout's config may name a program."""
ref = default_ref(checkout, GIT_TIMEOUT, guarded=True)
return ref if isinstance(ref, Failure) else later_fixes(ref, cwd=checkout, guarded=True, timeout=GIT_TIMEOUT)
ref = default_ref(checkout, GIT_TIMEOUT, guarded=True, git=git)
return ref if isinstance(ref, Failure) else branch_chunks(ref, functools.partial(git, cwd=checkout, timeout=GIT_TIMEOUT, guarded=True))
def entries(path: pathlib.Path) -> list[dict]:
+14 -19
View File
@@ -6,12 +6,12 @@ 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_from
from score_outcomes.later_fixes import Landed
from routing_figures.prices import listed
from model_routing.ladder import position, Rung
from round_titles import round_counts
from round_titles import rounds_past_first
from shell_command import simple_commands
from transcript_archive.outcomes import UNFINISHED_AT, workers
@@ -57,7 +57,7 @@ class Reports:
@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 chunk on its project's default branch matches it."""
"""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 chunk on its project's default branch shipped its item."""
dollars: Dollars
start: Rung | None
rounds_past_first: int
@@ -72,7 +72,7 @@ class ChunkFigures:
@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 chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why."""
"""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]]
@@ -101,7 +101,7 @@ class Spent(typing.NamedTuple):
message: Message
def measured(chunk: Chunk, home: str, history: list[Landed] | None = None) -> ChunkFigures:
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)]
@@ -118,29 +118,24 @@ def measured(chunk: Chunk, home: str, history: list[Landed] | None = None) -> Ch
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
start = route_from(cycles[0][1]) if cycles else None
titles = commit_titles(chunk.worker, home)
return ChunkFigures(
dollars=dollars,
start=start.rung if start and start.item else None,
rounds_past_first=sum(max(0, rounds - 1) for rounds in round_counts(titles).values()),
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=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
fixed_later=later_fixes_of(titles, history or []),
fixed_later=later_fixes_of(start.item, history or []) if start and start.item else None,
)
def later_fixes_of(titles: list[str], history: list[Landed]) -> int | None:
"""How many chunks in history fixed code that the chunks holding one of titles shipped, each counted once and none of those chunks itself; None where no chunk holds one. Only a title no other chunk holds counts, since one such as a round's with no findings recurs."""
# A worker's commits may land as several chunks, as a rebase cut by commit time does, and every one of them is its work.
holders = collections.Counter(title for landed in history for title in landed.titles)
shipped = [landed for landed in history if any(holders[title] == 1 for title in landed.titles.intersection(titles))]
if not shipped:
return None
return len({later for landed in shipped for later in landed.fixed_by} - {landed.label for landed in shipped})
def later_fixes_of(item: int, history: list[BranchChunk]) -> int | None:
"""How many later chunks fixed code shipped by the chunk in history that shipped item; None where no chunk shipped it."""
# lilleman chose on 2026-10-28 to match by the item a chunk's route names over commit titles, since it drops the title matching and reads projects whose commit titles the worker's transcript doesn't show; the cost is that a chunk whose PR didn't remove its item reads as unknown.
return next((len(chunk.fixed_by) for chunk in history if any(shipped.id == item for shipped in chunk.shipped)), None)
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
@@ -252,7 +247,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tu
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(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks), sum(chunk.fixed_later is None for chunk in chunks), unread)
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks), sum(chunk.start is not None and chunk.fixed_later is None for chunk in chunks), unread)
def calls(figures: Figures) -> list[str]:
@@ -279,9 +274,9 @@ def basis(figures: Figures) -> str:
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."
text += " A chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, as `score-outcomes` counts them, so a recent chunk has had less time to gather them. What it shipped is each chunk there holding a title of the worker's commits that no other chunk there holds."
text += " A routed chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, as `score-outcomes` counts them, so a recent chunk has had less time to gather them. Its chunk there is the one that removed the item its route names from todo.md."
if figures.unmatched:
text += f" The later fixes of {figures.unmatched} of the chunks are unknown, since no chunk on the branch held such a title, or the branch could not be read."
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
+34 -26
View File
@@ -14,18 +14,19 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive
from branch_chunks.cut import BranchChunk
from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals
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 score_outcomes.later_fixes import Landed
from transcript_archive import outcomes, write
from model_routing.route import Route
LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
ROUND = "Answer stability round 1: 0 🔴, 0 🟡"
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
@@ -45,10 +46,6 @@ def result(id_, text):
return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": id_, "content": [{"type": "text", "text": text}]}]}}
def commit(id_, title):
return message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'"))
def stamped(at, outcome):
return f"{at} {outcome}\n"
@@ -57,6 +54,15 @@ def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None):
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0)
def shipping(*items, fixed_by=()):
"""A chunk on a default branch that shipped the items with these IDs."""
return BranchChunk("before", "tip", "abc1234", "merge", "2026-10-14T11:00:00Z", (), tuple(Item(id_, (0, 1, 0), "", f"**Item {id_}.**", {}, (), ()) for id_ in items), fixed_by)
def no_checkout(*args, **options):
return Failure("no checkout")
class Measured(unittest.TestCase):
def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self):
worker = [
@@ -96,18 +102,19 @@ class Measured(unittest.TestCase):
self.assertEqual(measured(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)
def test_counts_the_later_fixes_of_the_landed_chunks_holding_a_title_of_the_workers_commits_no_other_holds(self):
worker = [commit("m1", "Ship it"), commit("m2", ROUND)]
fixed_later = lambda *history: measured(Chunk("log", [], worker, []), "/h", list(history)).fixed_later
self.assertEqual(fixed_later(Landed("b", "2026-10-14T11:00:00Z", frozenset({ROUND}), ("c", "d", "e")), Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it", ROUND}), ("c", "d"))), 2)
self.assertEqual(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ())), 0)
self.assertEqual(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ("c", "d")), Landed("b", "2026-10-14T10:20:00Z", frozenset({ROUND}), ("d", "a"))), 2)
self.assertIsNone(fixed_later(Landed("b", "2026-10-14T11:00:00Z", frozenset({"Ship it"}), ("c",)), Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ())))
self.assertIsNone(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Other"}), ())))
self.assertIsNone(measured(Chunk("log", [], worker, []), "/h").fixed_later)
def test_counts_the_later_fixes_of_the_chunk_that_shipped_the_item_its_route_names(self):
routed = [stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))]
fixed_later = lambda kept, *history: measured(Chunk("log", kept, [], []), "/h", list(history)).fixed_later
self.assertEqual(fixed_later(routed, shipping(6, fixed_by=("c", "d", "e")), shipping(5, 7, fixed_by=("c", "d"))), 2)
self.assertEqual(fixed_later(routed, shipping(7)), 0)
self.assertIsNone(fixed_later(routed, shipping(8, fixed_by=("c",))))
self.assertIsNone(fixed_later(routed))
self.assertIsNone(measured(Chunk("log", routed, [], []), "/h").fixed_later)
self.assertIsNone(fixed_later([stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j"))], shipping(7, fixed_by=("c",))))
def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
@@ -251,10 +258,10 @@ class Calls(unittest.TestCase):
def test_renders_the_median_later_fixes_of_the_matched_chunks_and_names_each_history_unread(self):
matched = [dataclasses.replace(figures(), fixed_later=fixed) for fixed in (0, 3)]
text = render(totals([*matched, figures()], unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, "")
text = render(totals([*matched, figures(), figures(start=None)], unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, "")
self.assertIn(f"| {LOW} | 3 | 0.0 | 0.0 | 1.5 | | |", text)
self.assertIn("as `score-outcomes` counts them", text)
self.assertIn("The later fixes of 1 of the chunks are unknown", text)
self.assertIn("The later fixes of 1 of the routed chunks are unknown", text)
self.assertIn("## Project histories unread\n\n- log: no main branch\n", text)
self.assertNotIn("are unknown", render(totals(matched), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertNotIn("histories unread", render(totals(matched), [], "2026-10-15T00:00:00Z", 40, ""))
@@ -288,10 +295,10 @@ class Archive(unittest.TestCase):
def test_measures_each_finished_chunk_keyed_by_its_project(self):
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
found = archive.measure_archive(self.root, "/h", "")
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"), archive.Measured([], ()))
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.Measured([], ()))
def test_counts_each_chunks_later_fixes_from_its_projects_checkout_and_names_each_history_it_cannot_read(self):
home = self.root / "home"
@@ -309,16 +316,17 @@ class Archive(unittest.TestCase):
git("commit", "-q", "-m", title)
git("switch", "-q", "main")
git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
fix = "| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n"
git("init", "-q", "-b", "main")
(checkout / "todo.md").write_text(plan("| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n"))
(checkout / "todo.md").write_text(plan("| 7 | 0.1.0 | | | **Ship seven.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n" + fix))
(checkout / "a.py").write_text("1\n")
git("add", "todo.md", "a.py")
git("commit", "-q", "-m", "Start")
merge("ship", "Ship it", {"a.py": "1\nx\n"})
merge("ship", "Ship seven", {"a.py": "1\nx\n", "todo.md": plan(fix)})
merge("fix", "Fix six", {"a.py": "1\ny\n", "todo.md": plan("")})
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [commit("m1", "Ship it")])
self.chunk("gone", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [commit("m1", "Ship it")])
found = archive.measure_archive(self.root, str(home), "")
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
self.chunk("gone", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
found = archive.measure_archive(self.root, str(home), "", git_repo.git)
self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"gone": 0}.keys(), None), ({"log": 0}.keys(), 1)])
(unread,) = found.unread
self.assertTrue(unread.startswith("gone: "), unread)
@@ -332,7 +340,7 @@ class Archive(unittest.TestCase):
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800))
(found,) = archive.measure_archive(kept, "/h", "").chunks
(found,) = archive.measure_archive(kept, "/h", "", no_checkout).chunks
self.assertEqual((found.start, found.unfinished), (LOW, 1))
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0})
@@ -342,7 +350,7 @@ class Archive(unittest.TestCase):
self.chunk("other", "c2", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
self.chunk("broken", "c3", "", [])
(self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff")
found = archive.measure_archive(self.root, "/h", "")
found = archive.measure_archive(self.root, "/h", "", no_checkout)
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, ""))