From d967219f7eb152b53f9abbae8a2051272ef323ea Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 21:51:59 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20stage=20typ?= =?UTF-8?q?es=20for=20the=20cut=20and=20shipped=20chunks,=20one=20text=5Fa?= =?UTF-8?q?t,=20the=20path=20rule=20in=20the=20core,=20a=20parse=20that=20?= =?UTF-8?q?fails=20as=20a=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/branch_chunks/cut.py | 65 +++++++++++++------ bin/branch_chunks/fixes.py | 54 ++++++++++++---- bin/branch_chunks/read.py | 43 ++++++------ bin/branch_chunks/test_branch_chunks.py | 68 ++++++++++++------- bin/git_repo.py | 30 ++++++--- bin/routing_figures/archive.py | 53 ++++++++------- bin/routing_figures/measure.py | 13 +++- bin/routing_figures/test_routing_figures.py | 72 ++++++++++++++------- bin/score_outcomes/results.py | 16 +++-- bin/test_git_repo.py | 12 ++++ 10 files changed, 280 insertions(+), 146 deletions(-) diff --git a/bin/branch_chunks/cut.py b/bin/branch_chunks/cut.py index c69caaf3..b922b30d 100644 --- a/bin/branch_chunks/cut.py +++ b/bin/branch_chunks/cut.py @@ -1,6 +1,8 @@ import dataclasses +import re import typing +from failure import Failure from comprehension_history import HISTORY from todo_table import Item, items from reading_cost.figures import RECORD @@ -8,8 +10,10 @@ from utc_stamp import utc # The plan, and the records tools append to: none of their lines are the chunk's work. NOT_WORK = ("todo.md", HISTORY, RECORD) -# Each commit as its hash, commit and author times and parents, its short hash and title, then the files it changed; a merge's are those it changed against its first parent. -LOG = ("log", "--format=%x1e%H %ct %at %P%x1f%h%x1f%s", "--name-only", "--diff-merges=first-parent") +# Each commit as its hash, commit and author times and parents, its short hash and title, then the files it changed; a merge's are those it changed against its first parent. git refuses a NUL byte in a commit message, so a title can't split a record. +LOG = ("log", "--format=%x00%H %ct %at %P%x1f%h%x1f%s", "--name-only", "--diff-merges=first-parent") +# One commit's record in LOG's output, without the NUL that opens it. +LOG_RECORD = re.compile(r"([0-9a-f]+) ([0-9]+) ([0-9]+) ([0-9a-f ]*)\x1f([0-9a-f]+)\x1f(.*)", re.DOTALL) # How a chunk reached the default branch; rebase and push leave no merge commit to bound it. Landing = typing.Literal["merge", "rebase", "push"] @@ -27,14 +31,19 @@ class Commit: @dataclasses.dataclass(frozen=True) -class BranchChunk: - """A chunk on a default branch. Its change runs from before, None for the branch's first chunk, to tip, its newest commit on the first-parent line. label names it as the reports do, landed says how it reached the branch, and merged is tip's commit time. titles are those of every commit it brought; shipped holds each todo.md item its change removed, as scored before it; fixed_by names the later chunks that fixed code it shipped, newest first.""" +class Span: + """A chunk on a default branch, as cut_branch cuts it. Its change runs from before, None for the branch's first chunk, to tip, its newest commit on the first-parent line. label names it as the reports do, landed says how it reached the branch, and merged is tip's commit time. titles are those of every commit it brought.""" before: str | None tip: str label: str landed: Landing merged: str titles: tuple[str, ...] + + +@dataclasses.dataclass(frozen=True) +class BranchChunk(Span): + """A chunk with shipped, each todo.md item its change removed, as scored before it, and fixed_by, the later chunks that fixed code it shipped, newest first.""" shipped: tuple[Item, ...] fixed_by: tuple[str, ...] @@ -43,13 +52,17 @@ class BranchChunk: class Branch: """A default branch's commits by hash, its chunks newest first, and each commit's chunk as an index into chunks.""" commits: dict[str, Commit] - chunks: list[BranchChunk] + chunks: list[Span] owner: dict[str, int] -def cut_branch(log: str) -> Branch: +def cut_branch(log: str) -> Branch | Failure: """The branch LOG printed, cut into chunks as chunk_log cuts its first-parent line; a commit belongs to the oldest chunk whose commits reach it.""" commits = parsed(log) + if isinstance(commits, Failure): + return commits + if not commits: + return Failure("git log printed no commit") # git log prints the commit it starts from first. line = [commits[next(iter(commits))]] while line[-1].parents: @@ -59,18 +72,29 @@ def cut_branch(log: str) -> Branch: titles: list[list[str]] = [[] for _ in runs] for commit in commits.values(): titles[owner[commit.hash]].append(commit.title) - chunks = [BranchChunk(run[-1].parents[0] if run[-1].parents else None, run[0].hash, label(run[-1].short, run[0].short), landing(run), utc(run[0].committed), tuple(titles[index]), (), ()) for index, run in enumerate(runs)] - return Branch(commits, chunks, owner) + spans = [] + for index, run in enumerate(runs): + spans.append(Span( + before=run[-1].parents[0] if run[-1].parents else None, + tip=run[0].hash, + label=label(run[-1].short, run[0].short), + landed=landing(run), + merged=utc(run[0].committed), + titles=tuple(titles[index]), + )) + return Branch(commits, spans, owner) -def parsed(log: str) -> dict[str, Commit]: +def parsed(log: str) -> dict[str, Commit] | Failure: """Each commit LOG printed, by hash, in the order it printed them.""" commits = {} - for record in log.split("\x1e")[1:]: - header, short, rest = record.split("\x1f", 2) - full, committed, authored, *parents = header.split() + for record in log.split("\x00")[1:]: + found = LOG_RECORD.fullmatch(record) + if not found: + return Failure(f"git log printed a commit it could not read: {record[:200]!r}") + full, committed, authored, parents, short, rest = found.groups() title, *files = rest.split("\n") - commits[full] = Commit(full, short, int(committed), int(authored), tuple(parents), title, tuple(name for name in files if name)) + commits[full] = Commit(full, short, int(committed), int(authored), tuple(parents.split()), title, tuple(name for name in files if name)) return commits @@ -121,7 +145,7 @@ def shipped(before: str, after: str) -> list[Item]: def plan_revisions(branch: Branch) -> list[str]: - """The revisions whose todo.md with_shipped needs: the commit before and the tip of each chunk, but the branch's first, that brought a commit changing todo.md.""" + """The revisions whose todo.md shipped_by needs: the commit before and the tip of each chunk, but the branch's first, that brought a commit changing todo.md.""" changed = sorted({branch.owner[commit.hash] for commit in branch.commits.values() if "todo.md" in commit.files}) revisions: dict[str, None] = {} for index in changed: @@ -131,7 +155,12 @@ def plan_revisions(branch: Branch) -> list[str]: return list(revisions) -def with_shipped(branch: Branch, plans: dict[str, str]) -> Branch: - """The branch with each chunk's shipped items, read from todo.md's text at each revision plan_revisions named, as plans holds it; a chunk with a revision plans lacks changed no plan.""" - chunks = [dataclasses.replace(chunk, shipped=tuple(shipped(plans[chunk.before], plans[chunk.tip]))) if chunk.before is not None and chunk.before in plans and chunk.tip in plans else chunk for chunk in branch.chunks] - return dataclasses.replace(branch, chunks=chunks) +def shipped_by(branch: Branch, plans: dict[str, str]) -> list[tuple[Item, ...]]: + """The items each of the branch's chunks shipped, in the order of its chunks, read from todo.md's text at each revision plan_revisions named, as plans holds it; none for a chunk with a revision plans lacks, which changed no plan.""" + found: list[tuple[Item, ...]] = [] + for chunk in branch.chunks: + if chunk.before is not None and chunk.before in plans and chunk.tip in plans: + found.append(tuple(shipped(plans[chunk.before], plans[chunk.tip]))) + else: + found.append(()) + return found diff --git a/bin/branch_chunks/fixes.py b/bin/branch_chunks/fixes.py index 52d58116..93b89155 100644 --- a/bin/branch_chunks/fixes.py +++ b/bin/branch_chunks/fixes.py @@ -1,10 +1,11 @@ """The later chunks that fixed code each chunk on a default branch shipped: its escaped defects. A later chunk fixed code an earlier chunk shipped where one of its changes removes or rewrites lines that `git blame` traces to a commit the earlier chunk brought. Two kinds of change count: the chunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk answering a 🔴 that a reviewer marked `[misread]`. Each later chunk counts at most once against each earlier chunk.""" -import dataclasses import re +import typing -from branch_chunks.cut import Branch, BranchChunk +from branch_chunks.cut import Branch, BranchChunk, NOT_WORK +from todo_table import Item from round_titles import title_counts # The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect. @@ -13,26 +14,51 @@ HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@") BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+") -def fixing_changes(branch: Branch) -> list[tuple[int, str, str]]: - """Each change that fixes a defect, as its chunk's index, the commit before it and its tip: the whole change of each chunk that ships a FIXES item, and each round commit answering a 🔴 a reviewer marked `[misread]`.""" - changes = [(index, chunk.before, chunk.tip) for index, chunk in enumerate(branch.chunks) if chunk.before is not None and any(item.exempt in FIXES for item in chunk.shipped)] +class FixingChange(typing.NamedTuple): + """A change that fixes a defect: the index of its chunk, the commit before it and its tip.""" + chunk: int + before: str + tip: str + + +class Traced(typing.NamedTuple): + """The commits that last changed the lines a fixing change removes, with the index of the change's chunk.""" + chunk: int + commits: set[str] + + +def fixing_changes(branch: Branch, shipped: list[tuple[Item, ...]]) -> list[FixingChange]: + """Each change that fixes a defect: the whole change of each chunk that ships a FIXES item, as shipped_by lists them, and each round commit answering a 🔴 a reviewer marked `[misread]`.""" + changes = [] + for index, (chunk, items) in enumerate(zip(branch.chunks, shipped)): + if chunk.before is not None and any(item.exempt in FIXES for item in items): + changes.append(FixingChange(index, chunk.before, chunk.tip)) for commit in branch.commits.values(): counts = title_counts(commit.title) # A title counts misread 🔴 and 🟡 findings together, so it takes one with both a 🔴 and a misread finding to answer a misread 🔴. if counts and counts.red and counts.misread and commit.parents: - changes.append((branch.owner[commit.hash], commit.parents[0], commit.hash)) + changes.append(FixingChange(branch.owner[commit.hash], commit.parents[0], commit.hash)) return changes -def with_fixes(branch: Branch, traced: list[tuple[int, set[str]]]) -> list[BranchChunk]: - """The branch's chunks, each naming the later chunks that fixed code it shipped, from the commits each fixing change traced to, paired with its chunk's index.""" +def with_fixes(branch: Branch, shipped: list[tuple[Item, ...]], traced: list[Traced]) -> list[BranchChunk]: + """The branch's chunks, each with the items it shipped, as shipped_by lists them, and the later chunks that fixed code it shipped, from the commits each fixing change traced to.""" fixed: dict[int, set[int]] = {} - for index, commits in traced: - for commit in commits: - # A commit no chunk owns cannot be one before can reach; take it as the fixing chunk's own. - if branch.owner.get(commit, index) > index: - fixed.setdefault(branch.owner[commit], set()).add(index) - return [dataclasses.replace(chunk, fixed_by=tuple(branch.chunks[later].label for later in sorted(fixed.get(index, ())))) for index, chunk in enumerate(branch.chunks)] + for change in traced: + for commit in change.commits: + # Blame at a commit names only commits the branch's log holds; one it lacks counts against no chunk. + if commit in branch.owner and branch.owner[commit] > change.chunk: + fixed.setdefault(branch.owner[commit], set()).add(change.chunk) + chunks = [] + for index, (span, items) in enumerate(zip(branch.chunks, shipped)): + fixed_by = tuple(branch.chunks[later].label for later in sorted(fixed.get(index, ()))) + chunks.append(BranchChunk(**vars(span), shipped=items, fixed_by=fixed_by)) + return chunks + + +def removed_work(diff: str) -> dict[str, list[tuple[int, int]]]: + """The old lines of a chunk's work each hunk of a `git diff -U0` removes or rewrites, as removed reads them: outside the plan and the records.""" + return {path: spans for path, spans in removed(diff).items() if path not in NOT_WORK} def removed(diff: str) -> dict[str, list[tuple[int, int]]]: diff --git a/bin/branch_chunks/read.py b/bin/branch_chunks/read.py index 53db033d..5fee549a 100644 --- a/bin/branch_chunks/read.py +++ b/bin/branch_chunks/read.py @@ -1,63 +1,58 @@ -import typing - -from branch_chunks.fixes import blamed, fixing_changes, removed, with_fixes -from branch_chunks.cut import BranchChunk, cut_branch, LOG, NOT_WORK, plan_revisions, with_shipped +from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes +from branch_chunks.cut import BranchChunk, cut_branch, LOG, plan_revisions, shipped_by from failure import Failure - -# Runs git with the given arguments in the checkout's top: blame and a pathspec read a path from the current directory, and the diff names each from the top. -Run = typing.Callable[..., str | Failure] +from git_repo import Run, text_at def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure: - """Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.""" + """Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped. + + run runs git in the checkout's top: blame and a pathspec read a path from the current directory, and the diff names each from the top.""" # The -- keeps a file named like the branch from making it ambiguous. log = run(*LOG, default, "--") if isinstance(log, Failure): return log branch = cut_branch(log) + if isinstance(branch, Failure): + return branch plans = plans_at(plan_revisions(branch), run) if isinstance(plans, Failure): return plans - branch = with_shipped(branch, plans) - traced = traces(fixing_changes(branch), run) - return traced if isinstance(traced, Failure) else with_fixes(branch, traced) + shipped = shipped_by(branch, plans) + traced = traces(fixing_changes(branch, shipped), run) + return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced) def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure: """todo.md's text at each revision, empty where the revision holds none.""" plans = {} for revision in revisions: - listed = run("ls-tree", "--name-only", revision, "--", "todo.md") - if isinstance(listed, Failure): - return listed - plan = run("show", f"{revision}:todo.md") if listed.strip() else "" + plan = text_at(revision, "todo.md", run) if isinstance(plan, Failure): return plan plans[revision] = plan return plans -def traces(changes: list[tuple[int, str, str]], run: Run) -> list[tuple[int, set[str]]] | Failure: - """The commits each change traced_to traces, paired with the change's chunk's index.""" +def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure: + """The commits traced_to traces for each change.""" found = [] - for index, before, tip in changes: - traced = traced_to(before, tip, run) + for change in changes: + traced = traced_to(change.before, change.tip, run) if isinstance(traced, Failure): return traced - found.append((index, traced)) + found.append(Traced(change.chunk, traced)) return found def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure: - """The commits that last changed each line the change from before to tip removes or rewrites, outside the plan and the records.""" + """The commits that last changed each line of a chunk's work that the change from before to tip removes or rewrites.""" # The prefixes and options keep the checkout's diff config out of the output. diff = run("diff", "-U0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip) if isinstance(diff, Failure): return diff traced: set[str] = set() - for path, spans in removed(diff).items(): - if path in NOT_WORK: - continue + for path, spans in removed_work(diff).items(): # An empty --ignore-revs-file drops a configured one, which blame fails on where the file is missing. blame = run("blame", "--porcelain", "--no-textconv", "--ignore-revs-file=", *(f"-L{start},+{count}" for start, count in spans), before, "--", path) if isinstance(blame, Failure): diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index 7d623ef2..54d3e6a3 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -5,11 +5,12 @@ import subprocess import sys import tempfile import unittest +import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from branch_chunks.fixes import blamed, fixing_changes, removed, with_fixes -from branch_chunks.cut import Branch, BranchChunk, chunk_log, Commit, landing, shipped +from branch_chunks.fixes import blamed, fixing_changes, removed, removed_work, Traced, with_fixes +from branch_chunks.cut import Branch, chunk_log, Commit, cut_branch, landing, NOT_WORK, shipped, Span from branch_chunks.read import branch_chunks, traced_to from failure import Failure from git_repo import git @@ -31,8 +32,8 @@ def item(id_: int, exempt: str = "") -> Item: return Item(id_, (0, 1, 0), exempt, f"**Item {id_}.**", {}, (), ()) -def chunk(label: str, shipped: tuple[Item, ...] = ()) -> BranchChunk: - return BranchChunk(f"{label}-before", f"{label}-tip", label, "merge", "2026-10-13T10:00:00Z", (), shipped, ()) +def span(label: str) -> Span: + return Span(f"{label}-before", f"{label}-tip", label, "merge", "2026-10-13T10:00:00Z", ()) def commit(hash_: str, committed: int, authored: int, *parents: str, title: str = "") -> Commit: @@ -61,6 +62,19 @@ class Shipped(unittest.TestCase): self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), []) +class CutBranch(unittest.TestCase): + def test_reads_a_title_that_holds_a_control_character(self): + found = cut_branch(f"\x00{'a' * 40} 100 100 \x1faaaaaaa\x1fTake \x1e and \x1f\n\nb.py\n") + self.assertNotIsInstance(found, Failure) + self.assertEqual([found.titles for found in found.chunks], [("Take \x1e and \x1f",)]) + + def test_fails_on_a_commit_it_cannot_read(self): + self.assertIsInstance(cut_branch(f"\x00{'a' * 40} 100\x1faaaaaaa\n"), Failure) + + def test_fails_on_a_log_that_holds_no_commit(self): + self.assertIsInstance(cut_branch(""), Failure) + + class ChunkLog(unittest.TestCase): def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self): self.assertEqual(cut(commit("m", 100, 100, "a", "b"), commit("c", 100, 100, "a")), [("m", "m", 100, "merge"), ("c", "c", 100, "push")]) @@ -83,8 +97,9 @@ class ChunkLog(unittest.TestCase): class FixingChanges(unittest.TestCase): def test_takes_the_whole_change_of_each_chunk_that_ships_a_defect_or_a_security_item(self): - branch = Branch({}, [chunk("d", (item(9, "security"),)), chunk("c", (item(8),)), chunk("b", (item(6, "defect"), item(7))), chunk("a")], {}) - self.assertEqual(fixing_changes(branch), [(0, "d-before", "d-tip"), (2, "b-before", "b-tip")]) + branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {}) + shipped = [(item(9, "security"),), (item(8),), (item(6, "defect"), item(7)), ()] + self.assertEqual(fixing_changes(branch, shipped), [(0, "d-before", "d-tip"), (2, "b-before", "b-tip")]) def test_takes_each_round_commit_whose_title_counts_both_a_red_and_a_misread_finding(self): titles = { @@ -95,19 +110,24 @@ class FixingChanges(unittest.TestCase): "r5": "Do the work", } commits = {name: commit(name, 100, 100, f"{name}-parent", title=title) for name, title in titles.items()} - branch = Branch(commits, [chunk("b"), chunk("a")], {"r1": 1, "r2": 0, "r3": 0, "r4": 0, "r5": 0}) - self.assertEqual(fixing_changes(branch), [(1, "r1-parent", "r1")]) + branch = Branch(commits, [span("b"), span("a")], {"r1": 1, "r2": 0, "r3": 0, "r4": 0, "r5": 0}) + self.assertEqual(fixing_changes(branch, [(), ()]), [(1, "r1-parent", "r1")]) class WithFixes(unittest.TestCase): def test_names_each_later_chunk_once_against_each_chunk_whose_commits_its_fixes_traced_to_newest_first(self): - branch = Branch({}, [chunk("d"), chunk("c"), chunk("b"), chunk("a")], {"a1": 3, "a2": 3, "b1": 2, "c1": 1, "d1": 0}) - found = with_fixes(branch, [(1, {"a1", "a2"}), (0, {"a1", "b1", "c1"}), (1, {"a2"}), (0, {"a2"})]) + branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {"a1": 3, "a2": 3, "b1": 2, "c1": 1, "d1": 0}) + found = with_fixes(branch, [()] * 4, [Traced(1, {"a1", "a2"}), Traced(0, {"a1", "b1", "c1"}), Traced(1, {"a2"}), Traced(0, {"a2"})]) self.assertEqual([found.fixed_by for found in found], [(), ("d",), ("d",), ("d", "c")]) def test_counts_no_fix_of_its_own_chunks_commit_a_newer_chunks_or_one_no_chunk_brought(self): - branch = Branch({}, [chunk("b"), chunk("a")], {"b1": 0, "a1": 1}) - self.assertEqual([found.fixed_by for found in with_fixes(branch, [(1, {"a1", "b1", "elsewhere"})])], [(), ()]) + branch = Branch({}, [span("b"), span("a")], {"b1": 0, "a1": 1}) + self.assertEqual([found.fixed_by for found in with_fixes(branch, [(), ()], [Traced(1, {"a1", "b1", "elsewhere"})])], [(), ()]) + + def test_keeps_each_chunk_as_cut_with_the_items_it_shipped(self): + (found,) = with_fixes(Branch({}, [span("a")], {}), [(item(4),)], []) + self.assertEqual((found.before, found.tip, found.label, found.landed, found.merged, found.titles), ("a-before", "a-tip", "a", "merge", "2026-10-13T10:00:00Z", ())) + self.assertEqual([shipped.id for shipped in found.shipped], [4]) class Removed(unittest.TestCase): @@ -149,6 +169,12 @@ class Removed(unittest.TestCase): self.assertEqual(removed(diff), {"a.md": [(3, 1)]}) +class RemovedWork(unittest.TestCase): + def test_leaves_out_the_plan_and_the_records(self): + diff = "".join(f"--- a/{path}\n+++ b/{path}\n@@ -2 +2 @@\n-x\n+y\n" for path in ("a.py", *NOT_WORK)) + self.assertEqual(removed_work(diff), {"a.py": [(2, 1)]}) + + class Blamed(unittest.TestCase): def test_reads_the_commit_of_each_line_from_porcelain_output(self): first, second = "a" * 40, "b" * 40 @@ -157,18 +183,11 @@ class Blamed(unittest.TestCase): class TracedTo(unittest.TestCase): - DIFF = "--- a/a.py\n+++ b/a.py\n@@ -2 +2 @@\n-x\n+y\n--- a/todo.md\n+++ b/todo.md\n@@ -5 +4,0 @@\n-| 6 |\n--- a/docs/reading-cost.md\n+++ b/docs/reading-cost.md\n@@ -1 +1 @@\n-a\n+b\n" + DIFF = "--- a/a.py\n+++ b/a.py\n@@ -2 +2 @@\n-x\n+y\n--- a/todo.md\n+++ b/todo.md\n@@ -5 +4,0 @@\n-| 6 |\n" - def test_blames_the_lines_a_change_removes_before_it_leaving_out_the_plan_and_the_records(self): - blames = [] - - def run(*args): - if args[0] == "diff": - return self.DIFF - blames.append(args) - return f"{'a' * 40} 2 2 1\n\tx\n" - self.assertEqual(traced_to("before", "tip", run), {"a" * 40}) - self.assertEqual([(args[-1], "-L2,+1" in args, "before" in args) for args in blames], [("a.py", True, True)]) + def test_names_the_commits_blame_names_for_the_work_a_change_removes(self): + blames = {"a.py": f"{'a' * 40} 2 2 1\n\tx\n", "todo.md": f"{'b' * 40} 5 5 1\n\t| 6 |\n"} + self.assertEqual(traced_to("before", "tip", lambda *args: self.DIFF if args[0] == "diff" else blames[args[-1]]), {"a" * 40}) def test_fails_where_git_cannot_blame(self): self.assertEqual(traced_to("before", "tip", lambda *args: self.DIFF if args[0] == "diff" else Failure("no blame")), Failure("no blame")) @@ -206,7 +225,8 @@ class BranchChunks(unittest.TestCase): def test_reads_each_chunk_with_the_items_it_shipped_and_the_later_chunks_that_fixed_it(self): shipped = self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z") fixed = self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z") - found = branch_chunks("main", functools.partial(git, cwd=str(self.checkout))) + with unittest.mock.patch.dict(os.environ, self.env, clear=True): + found = branch_chunks("main", functools.partial(git, cwd=str(self.checkout))) self.assertNotIsInstance(found, Failure) self.assertEqual([(found.label, found.landed, found.merged, [item.id for item in found.shipped], found.fixed_by) for found in found[:2]], [(fixed, "merge", "2026-10-14T10:00:00Z", [6], ()), (shipped, "merge", "2026-10-13T10:00:00Z", [4], (fixed,))]) self.assertEqual(sorted(found[1].titles), ["Do four", "Merge four"]) diff --git a/bin/git_repo.py b/bin/git_repo.py index 1d887fb8..5c7e5ece 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -1,6 +1,7 @@ """Run git, in the current directory or a given one, and read the checkout, its default branch and its files. Every tool in bin/ starts git through `git` here.""" +import functools import os import re import subprocess @@ -49,6 +50,10 @@ class Git(typing.Protocol): def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure: ... +# Runs git with the given arguments, in the checkout and with the options its caller bound, as functools.partial(git, cwd=...) does. +Run = typing.Callable[..., str | Failure] + + def top() -> str | Failure: found = git("rev-parse", "--show-toplevel") return found if isinstance(found, Failure) else found.strip() @@ -67,20 +72,20 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s return ref if isinstance(ref, Failure) else (ref, note) -def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, git: Git = git) -> str | Failure: - """The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/` with that remote, else the local main or master. +def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure: + """The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/` with that remote, else the local main or master. run runs git. Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin.""" - remotes = git("remote", cwd=cwd, guarded=guarded) + remotes = run("remote", cwd=cwd, guarded=guarded) if isinstance(remotes, Failure): return remotes if "origin" in remotes.split(): - recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded) + recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded) if not isinstance(recorded, Failure): return recorded.strip() - return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout, git) + return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout, run) for branch in ("main", "master"): - if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure): + if not isinstance(run("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure): return branch return Failure("no origin remote, and no main or master branch to take as the default branch") @@ -93,9 +98,9 @@ def branch_titles(default: str, cwd: str | None = None, timeout: float | None = return titles if isinstance(titles, Failure) else titles.splitlines() -def origin_head(cwd: str | None, timeout: float | None, git: Git) -> str | Failure: +def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failure: """The default branch origin names, for a clone made by `git init` and `git remote add`, which records none.""" - listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout) + listed = run("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout) if isinstance(listed, Failure): return listed if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed): @@ -124,10 +129,15 @@ def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure: """A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file.""" if not commit_exists(revision, cwd): return "" - listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd) + return text_at(revision, path, functools.partial(git, cwd=cwd)) + + +def text_at(revision: str, path: str, run: Run) -> str | Failure: + """A file's text at a commit, as run reads it; empty where the commit holds no such file. ls-tree reads path from the directory run runs in, and show from the checkout's top.""" + listed = run("ls-tree", "--name-only", revision, "--", path) if isinstance(listed, Failure): return listed - return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else "" + return run("show", f"{revision}:{path}") if listed.strip() else "" def full_history() -> Failure | None: diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index a0155b77..c4735c70 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -90,37 +90,42 @@ def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> Meas listed = archived_outcomes(root) if isinstance(listed, Failure): return listed - projects = sorted({root / key for key, _ in listed}) + projects = [measure_project(root, project, home, since, git) for project in sorted({root / key for key, _ in listed})] + return Measured( + [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: + """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,)) + chunks = [chunk for chunk in listed if chunk.finished > since] + if not chunks: + return Measured([], ()) + history = branch_history(checkout_of(key, pathlib.Path(home)), git) found = [] skipped = [] - unread = [] - for project in projects: - key = str(project.relative_to(root)) - chunks = finished_chunks(project) - if isinstance(chunks, Failure): - skipped.append(key) + for chunk in chunks: + folder = project / chunk.folder + try: + kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)] + subagents = [subagent(path) for path in chunk.subagents] + worker = entries(chunk.transcript) + except (OSError, UnicodeDecodeError): + skipped.append(str(folder.relative_to(root))) continue - chunks = [chunk for chunk in chunks if chunk.finished > since] - 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 - for chunk in chunks: - folder = project / chunk.folder - try: - kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)] - subagents = [subagent(path) for path in chunk.subagents] - worker = entries(chunk.transcript) - except (OSError, UnicodeDecodeError): - skipped.append(str(folder.relative_to(root))) - continue - found.append(measured(Chunk(key, kept, worker, subagents), home, history)) - return Measured(found, tuple(skipped), tuple(unread)) + 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 ()) 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, git=git) + ref = default_ref(checkout, GIT_TIMEOUT, guarded=True, run=git) return ref if isinstance(ref, Failure) else branch_chunks(ref, functools.partial(git, cwd=checkout, timeout=GIT_TIMEOUT, guarded=True)) diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index 8cfe2df9..f0a5257f 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -247,7 +247,18 @@ 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.start is not None and chunk.fixed_later is None for chunk in chunks), unread) + 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]: diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 16cd6910..ffc7360c 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -10,6 +10,7 @@ import subprocess import sys import tempfile import unittest +import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -63,6 +64,10 @@ def no_checkout(*args, **options): return Failure("no checkout") +# Two routed chunks whose later fixes are known: 0 and 3. +MATCHED = [dataclasses.replace(figures(), fixed_later=fixed) for fixed in (0, 3)] + + class Measured(unittest.TestCase): def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self): worker = [ @@ -106,15 +111,25 @@ class Measured(unittest.TestCase): 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 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 + 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",)))) + self.assertEqual(self.fixed_later([shipping(6, fixed_by=("c", "d", "e")), shipping(5, 7, fixed_by=("c", "d"))]), 2) + + def test_counts_no_later_fix_where_no_later_chunk_fixed_the_chunk_that_shipped_the_item(self): + self.assertEqual(self.fixed_later([shipping(7)]), 0) + + def test_leaves_the_later_fixes_unknown_where_no_chunk_shipped_the_item(self): + self.assertIsNone(self.fixed_later([shipping(8, fixed_by=("c",))])) + self.assertIsNone(self.fixed_later([])) + + def test_leaves_the_later_fixes_unknown_where_the_history_could_not_be_read(self): + self.assertIsNone(self.fixed_later(None)) + + def test_leaves_the_later_fixes_unknown_where_the_route_names_no_item(self): + self.assertIsNone(self.fixed_later([shipping(7, fixed_by=("c",))], Route(LOW).worker_line())) 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" @@ -256,15 +271,18 @@ class Calls(unittest.TestCase): self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "")) self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z")) - def test_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(), figures(start=None)], unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, "") + def test_renders_the_median_later_fixes_of_the_matched_chunks(self): + text = render(totals([*MATCHED, figures()]), [], "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 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, "")) + + def test_counts_the_routed_chunks_whose_later_fixes_are_unknown(self): + self.assertIn("The later fixes of 1 of the routed chunks are unknown", render(totals([*MATCHED, figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, "")) + self.assertNotIn("are unknown", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, "")) + + def test_names_each_project_history_unread(self): + self.assertIn("## Project histories unread\n\n- log: no main branch\n", render(totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, "")) + self.assertNotIn("histories unread", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, "")) def test_measures_once_the_count_runs_20_past_the_last_measurement(self): self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True]) @@ -300,11 +318,23 @@ class Archive(unittest.TestCase): 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([], ())) - def test_counts_each_chunks_later_fixes_from_its_projects_checkout_and_names_each_history_it_cannot_read(self): + def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self): home = self.root / "home" - checkout = home / "code" / "log" - checkout.mkdir(parents=True) env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)} + self.ship_then_fix(home / "code" / "log", env) + self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) + with unittest.mock.patch.dict(os.environ, env, clear=True): + 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], [({"log": 0}.keys(), 1)]) + + def test_names_each_project_whose_history_it_cannot_read(self): + 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, "/h", "", no_checkout) + self.assertEqual(([chunk.fixed_later for chunk in found.chunks], found.unread), ([None], ("gone: no checkout",))) + + def ship_then_fix(self, checkout, env): + """Makes a checkout whose main branch merges the chunk that ships item 7 of LOW_ROUTE, then one that ships a defect item and rewrites a line item 7 shipped.""" + checkout.mkdir(parents=True) git = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=checkout, check=True, env=env, capture_output=True) plan = lambda rows: "# todo\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" + rows @@ -324,12 +354,6 @@ class Archive(unittest.TestCase): git("commit", "-q", "-m", "Start") 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")), [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) def test_reads_each_cycles_route_from_its_own_outcomes_file(self): transcript = self.root / "t.jsonl" diff --git a/bin/score_outcomes/results.py b/bin/score_outcomes/results.py index b846896e..14e0b768 100644 --- a/bin/score_outcomes/results.py +++ b/bin/score_outcomes/results.py @@ -86,24 +86,26 @@ def report(results: list[Result]) -> list[str]: def misreads(results: list[Result]) -> list[str]: """Newest first, each chunk's 🔴 and 🟡 findings with how many of them a reviewer marked `[misread]`, for each chunk whose round titles count those.""" - # A chunk that shipped several items has a Result for each, so one line per chunk. - chunks = {result.merge: result for result in results} - newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True) - lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in newest_first if result.findings is not None and result.findings.misread is not None] + lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in one_per_chunk(results) if result.findings is not None and result.findings.misread is not None] return lines or ["- None: no chunk's round titles count them."] def fixed_later(results: list[Result]) -> list[str]: """Newest first, each finished chunk that later chunks fixed code of, naming them, then how many finished chunks none fixed.""" - chunks = {result.merge: result for result in results} - newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True) - lines = [f"- {result.merged} in {result.merge}: {later(result)}, by {listed(result.fixed_by, 'and')}" for result in newest_first if result.fixed_by] + chunks = one_per_chunk(results) + lines = [f"- {result.merged} in {result.merge}: {later(result)}, by {listed(result.fixed_by, 'and')}" for result in chunks if result.fixed_by] if not lines: return ["- None: no later chunk fixed code a finished chunk shipped."] others = len(chunks) - len(lines) return lines + ([f"- The other {plural(others, 'finished chunk')}: none."] if others else []) +def one_per_chunk(results: list[Result]) -> list[Result]: + """One result for each chunk, newest first: a chunk that shipped several items has a Result for each, and the report gives each chunk one line.""" + chunks = {result.merge: result for result in results} + return sorted(chunks.values(), key=lambda result: result.merged, reverse=True) + + def too_few(held: int, name: str, what: str) -> str: chunks = "such chunk records" if held == 1 else "such chunks record" return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}." diff --git a/bin/test_git_repo.py b/bin/test_git_repo.py index b9c3e766..f7d1b321 100644 --- a/bin/test_git_repo.py +++ b/bin/test_git_repo.py @@ -99,5 +99,17 @@ class StalledOrigin(unittest.TestCase): self.assertIn("stopped after 0.5 s", found.reason) +class TextAt(unittest.TestCase): + def test_reads_the_file_the_revision_lists(self): + answers = {"ls-tree": "todo.md\n", "show": "# todo\n"} + self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: answers[args[0]]), "# todo\n") + + def test_reads_empty_where_the_revision_lists_no_such_file(self): + self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: "" if args[0] == "ls-tree" else Failure("no such file")), "") + + def test_fails_where_git_cannot_list_the_revision(self): + self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: Failure("bad revision")), Failure("bad revision")) + + if __name__ == "__main__": unittest.main()