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
-162
View File
@@ -1,162 +0,0 @@
"""Each chunk on a default branch, with the later chunks that fixed code it 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]`. Chunks are cut as score-outcomes cuts them, and each counts at most once against each earlier chunk."""
import dataclasses
import re
import typing
from failure import Failure
from git_repo import file_at, git
from round_titles import title_counts
from score_outcomes.results import chunk_log, label, NOT_WORK, shipped
from utc_stamp import utc
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
FIXES = ("defect", "security")
# A todo.md row that may hold one of FIXES, as the extended regex `git log -G` takes; shipped confirms it.
FIX_ROW = r"[|] *(defect|security) *[|]"
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]+")
# Runs git with the given arguments, in the checkout's top.
Run = typing.Callable[..., str | Failure]
@dataclasses.dataclass(frozen=True)
class Landed:
"""A chunk: its label as score-outcomes names it, its commit time, the titles of every commit it brought to the default branch, and the labels of the later chunks that fixed code it shipped, newest first."""
label: str
landed: str
titles: frozenset[str]
fixed_by: tuple[str, ...]
def later_fixes(default: str, cwd: str | None = None, guarded: bool = False, timeout: float | None = None) -> list[Landed] | Failure:
"""Each chunk on default's first-parent line, newest first, read in the checkout holding cwd, else the current directory, each git call run as `git` runs it with timeout and guarded."""
top = git("rev-parse", "--show-toplevel", cwd=cwd, timeout=timeout, guarded=guarded)
if isinstance(top, Failure):
return top
# Blame and a pathspec read a path from the current directory, and the diff names each from the top.
root = top.strip()
def run(*args: str) -> str | Failure:
return git(*args, cwd=root, timeout=timeout, guarded=guarded)
log = run("log", "--format=%x1e%H %h %ct %at %P%x1f%s", default)
if isinstance(log, Failure):
return log
shorts: dict[str, str] = {}
parents: dict[str, list[str]] = {}
titles: dict[str, str] = {}
headers: dict[str, str] = {}
for record in log.split("\x1e")[1:]:
header, _, title = record.rstrip("\n").partition("\x1f")
full, short, committed, authored, *above = header.split()
shorts[full], parents[full], titles[full] = short, above, title
headers[full] = " ".join([full, committed, authored, *above])
# git log prints the commit it starts from first.
line = [next(iter(parents))]
while parents[line[-1]]:
line.append(parents[line[-1]][0])
chunks = chunk_log([headers[commit] for commit in line])
owner = owners(chunks, line, parents)
changes = fixing_changes(chunks, owner, parents, titles, run, lambda revision: file_at(revision, "todo.md", root, timeout, guarded), default)
if isinstance(changes, Failure):
return changes
fixed: dict[int, set[int]] = {}
for index, before, tip in changes:
traced = traced_to(before, tip, run)
if isinstance(traced, Failure):
return traced
for commit in traced:
# A commit no chunk owns cannot be one before can reach; take it as the fixing chunk's own.
if owner.get(commit, index) > index:
fixed.setdefault(owner[commit], set()).add(index)
owned: dict[int, set[str]] = {}
for commit, index in owner.items():
owned.setdefault(index, set()).add(titles[commit])
names = [label(shorts[first], shorts[last]) for first, last, _, _ in chunks]
return [Landed(names[index], utc(time), frozenset(owned[index]), tuple(names[later] for later in sorted(fixed.get(index, ())))) for index, (_, _, time, _) in enumerate(chunks)]
def owners(chunks: list, line: list[str], parents: dict[str, list[str]]) -> dict[str, int]:
"""Each commit's chunk, as its index in chunks, newest first: the oldest chunk on the first-parent line whose commits reach it."""
at = {commit: place for place, commit in enumerate(line)}
owner: dict[str, int] = {}
for index in reversed(range(len(chunks))):
first, last, _, _ = chunks[index]
for commit in reversed(line[at[last]:at[first] + 1]):
unowned = [commit]
while unowned:
found = unowned.pop()
if found not in owner:
owner[found] = index
unowned += parents[found]
return owner
def fixing_changes(chunks: list, owner: dict[str, int], parents: dict[str, list[str]], titles: dict[str, str], run: Run, plan_at: typing.Callable[[str], str | Failure], default: str) -> list[tuple[int, str, str]] | Failure:
"""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]`."""
touched = run("log", "--first-parent", f"-G{FIX_ROW}", "--format=%H", default, "--", "todo.md")
if isinstance(touched, Failure):
return touched
changes = []
for index in sorted({owner[commit] for commit in touched.split()}):
first, last, _, _ = chunks[index]
if not parents[first]:
continue
before = parents[first][0]
planned, after = plan_at(before), plan_at(last)
if isinstance(planned, Failure):
return planned
if isinstance(after, Failure):
return after
if any(item.exempt in FIXES for item in shipped(planned, after)):
changes.append((index, before, last))
for commit, title in titles.items():
counts = title_counts(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 parents[commit]:
changes.append((owner[commit], parents[commit][0], commit))
return changes
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 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
# 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):
return blame
traced |= blamed(blame)
return traced
def removed(diff: str) -> dict[str, list[tuple[int, int]]]:
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
spans: dict[str, list[tuple[int, int]]] = {}
path, left = None, 0
for row in diff.splitlines():
if left and row[:1] in ("-", "+", " "):
left -= 1
elif row.startswith("diff --git "):
path, left = None, 0
elif row.startswith("--- "):
# Git ends a path holding a space with a tab.
path = row[len("--- a/"):].removesuffix("\t") if row.startswith("--- a/") else None
elif hunk := HUNK.match(row):
start, count = int(hunk.group(1)), int(hunk.group(2) or 1)
left = count + int(hunk.group(3) or 1)
if path and count:
spans.setdefault(path, []).append((start, count))
return spans
def blamed(porcelain: str) -> set[str]:
"""The commit each line of `git blame --porcelain` output comes from."""
return {header.group(1) for row in porcelain.splitlines() if (header := BLAME_HEADER.match(row))}
+21 -53
View File
@@ -35,10 +35,10 @@ holds R and S, and C too where its table also had A, G and Goals. The chunk meas
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its branch's
commits'; any other chunk's are its own. Two pull requests merged in the same second read as one
chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk gives its
rounds and findings as lower bounds, `at least`, and the report ends saying all this.
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its own and
its branch's commits'; any other chunk's are its own. Two pull requests merged in the same second
read as one chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk
gives its rounds and findings as lower bounds, `at least`, and the report ends saying all this.
Given L, E and I, on the levels ~/.claude/rules/todo-items.md defines, and S, it works out R from
L, E and I, as rank_todo.py does, and lists the 5 finished items whose guesses sit closest, closest
@@ -71,18 +71,18 @@ Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout o
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
left out.
"""
import functools
import pathlib
import re
import sys
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
from score_outcomes.results import chunk_log, fixed_later, label, Landing, misreads, nearest, render, report, Result, results_of, shipped
from git_repo import default_branch, file_at, full_history, git, top
from branch_chunks.read import branch_chunks
from git_repo import default_branch, full_history, git, top
from failure import Failure
from score_outcomes.later_fixes import later_fixes
from score_outcomes.results import fixed_later, misreads, nearest, render, report, Result, results_of
from todo_table import LEVELS, risk, TOP_SCORE
from markdown_text import listed
from utc_stamp import utc
# The scores score-outcomes takes, in order.
GIVEN = ("L", "E", "I", "S")
@@ -157,51 +157,19 @@ def read_results(default: str) -> list[Result] | Failure:
"""What each chunk on the default branch's first-parent line measured."""
if partial := full_history():
return partial
# Both logs read one commit, so a fetch that moves the branch between them cannot cut chunks two ways.
tip = git("rev-parse", "--verify", f"{default}^{{commit}}")
if isinstance(tip, Failure):
return tip
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", tip.strip())
if isinstance(log, Failure):
return log
fixes = later_fixes(tip.strip())
if isinstance(fixes, Failure):
return fixes
fixed_by = {landed.label: landed.fixed_by for landed in fixes}
# Each commit's part of the log is its line, then the files it changed against its first parent.
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
headers = [commit[0] for commit in commits]
hashes = [header.split()[0] for header in headers]
plan = {short for short, commit in zip(hashes, commits) if "todo.md" in commit}
root = top()
if isinstance(root, Failure):
return root
run = functools.partial(git, cwd=root)
chunks = branch_chunks(default, run)
if isinstance(chunks, Failure):
return chunks
results: list[Result] = []
for first, last, committed, landed in chunk_log(headers):
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
for chunk in chunks:
if chunk.before is None or not chunk.shipped:
continue
titled = f"{first}^1..{first}^2" if landed == "merge" else f"{first}^1..{last}"
named = label(first, last)
measured = measure(f"{first}^1", last, named, utc(committed), titled, landed, fixed_by[named])
if isinstance(measured, Failure):
return measured
results += measured
numstat = run("diff", "--numstat", chunk.before, chunk.tip)
if isinstance(numstat, Failure):
return numstat
results += results_of(chunk, numstat)
return results
def measure(before: str, tip: str, named: str, merged: str, titled: str, landed: Landing, fixed_by: tuple[str, ...]) -> list[Result] | Failure:
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
planned = file_at(before, "todo.md")
if isinstance(planned, Failure):
return planned
after = file_at(tip, "todo.md")
if isinstance(after, Failure):
return after
items = shipped(planned, after)
if not items:
return []
numstat = git("diff", "--numstat", before, tip)
if isinstance(numstat, Failure):
return numstat
titles = git("log", "--format=%s", titled)
if isinstance(titles, Failure):
return titles
return results_of(items, named, merged, numstat, titles.splitlines(), landed, fixed_by)
+9 -49
View File
@@ -2,27 +2,19 @@ import dataclasses
import statistics
import typing
from round_titles import Findings, round_counts, round_findings
from comprehension_history import HISTORY
from todo_table import Item, items
from branch_chunks.cut import BranchChunk, Landing, NOT_WORK
from round_titles import Findings, round_findings, rounds_past_first
from todo_table import Item
from markdown_text import listed
from reading_cost.figures import RECORD
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing = typing.Literal["merge", "rebase", "push"]
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
Chunk = tuple[str, str, int, Landing]
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
@dataclasses.dataclass(frozen=True)
class Result:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed. fixed_by names the later chunks that fixed code it shipped, newest first, as later_fixes counts them."""
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed. fixed_by names the later chunks that fixed code it shipped, newest first, as branch_chunks counts them."""
item: Item
merge: str
merged: str
@@ -45,49 +37,17 @@ ORDERED = ("L", "E", "I")
SHOWN = ("L", "E", "I", "R", "S", "C")
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing, fixed_by: tuple[str, ...]) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
def results_of(chunk: BranchChunk, numstat: str) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed, fixed_by) for item in shipped]
def chunk_log(lines: list[str]) -> list[Chunk]:
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
chunks: list[Chunk] = []
joinable = False
for line in lines:
short, committed, authored, *parents = line.split()
if len(parents) > 1:
chunks.append((short, short, int(committed), "merge"))
joinable = False
elif joinable and chunks[-1][2] == int(committed):
_, newest, time, landed = chunks[-1]
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
else:
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
joinable = True
return chunks
def label(first: str, last: str) -> str:
"""How the report names a chunk: its one commit's short hash, or its first and last commits' as a range."""
return first if first == last else f"{first}^..{last}"
titles = list(chunk.titles)
ids = [item.id for item in chunk.shipped]
return [Result(item, chunk.label, chunk.merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), rounds_past_first(titles), round_findings(titles), chunk.landed, chunk.fixed_by) for item in chunk.shipped]
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
-192
View File
@@ -1,192 +0,0 @@
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.later_fixes import blamed, Landed, later_fixes, removed
from failure import Failure
from test_env import isolated_env
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
ROWS = {
4: "| 4 | 0.1.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
5: "| 5 | 0.1.0 | | | **Do five.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
6: "| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
7: "| 7 | 0.1.0 | | security | **Close seven.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
8: "| 8 | 0.1.0 | | defect | **Fix eight.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
9: "| 9 | 0.1.0 | | defect | **Fix nine.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
}
def todo(*ids: int) -> str:
return "# todo\n\n## Items\n\n" + HEADER + "".join(f"{ROWS[id_]}\n" for id_ in ids)
class Removed(unittest.TestCase):
def test_reads_the_old_lines_each_hunk_removes_or_rewrites_by_the_path_they_had(self):
diff = "\n".join([
"diff --git a/a.py b/a.py",
"--- a/a.py",
"+++ b/a.py",
"@@ -2 +2 @@ def f():",
"-x",
"+y",
"@@ -5,3 +4,0 @@",
"@@ -9,0 +8,2 @@",
"diff --git a/old.py b/new.py",
"--- a/old.py",
"+++ b/new.py",
"@@ -1,2 +1,2 @@",
"diff --git a/gone.py b/gone.py",
"--- a/gone.py",
"+++ /dev/null",
"@@ -1,4 +0,0 @@",
"diff --git a/born.py b/born.py",
"--- /dev/null",
"+++ b/born.py",
"@@ -0,0 +1,3 @@",
"diff --git \"a/tab\\there.py\" \"b/tab\\there.py\"",
"--- \"a/tab\\there.py\"",
"+++ \"b/tab\\there.py\"",
"@@ -1 +1 @@",
"diff --git a/my file.py b/my file.py",
"--- a/my file.py\t",
"+++ b/my file.py\t",
"@@ -7,2 +7 @@",
])
self.assertEqual(removed(diff), {"a.py": [(2, 1), (5, 3)], "old.py": [(1, 2)], "gone.py": [(1, 4)], "my file.py": [(7, 2)]})
def test_reads_a_hunk_line_inside_the_changed_text_as_text(self):
diff = "--- a/a.md\n+++ b/a.md\n@@ -3 +3 @@\n---- a/quoted\n+text\n"
self.assertEqual(removed(diff), {"a.md": [(3, 1)]})
class Blamed(unittest.TestCase):
def test_reads_the_commit_of_each_line_from_porcelain_output(self):
first, second = "a" * 40, "b" * 40
porcelain = f"{first} 2 2 1\nauthor t\nfilename a.py\n\tx\n{second} 5 5 2\nauthor t\n\ty\n{second} 6 6\n\t{first} 1 1 1\n"
self.assertEqual(blamed(porcelain), {first, second})
class LaterFixes(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.checkout = pathlib.Path(os.path.realpath(temp.name))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.checkout)}
self.git("init", "-q", "-b", "main")
self.commit("Start", {"todo.md": todo(4, 5, 6, 7, 8), "a.py": "1\n2\n3\n"})
def git(self, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
def commit(self, title, files, at=None):
for name, text in files.items():
(self.checkout / name).write_text(text)
self.git("add", name)
dates = {"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at} if at else {}
self.env.update(dates)
self.git("commit", "-q", "-m", title)
for name in dates:
self.env.pop(name)
return self.git("rev-parse", "--short", "HEAD").strip()
def chunk(self, branch, *commits):
"""Merges a branch holding each (title, files) commit, and returns the merge commit's short hash."""
self.git("switch", "-q", "-c", branch)
for title, files in commits:
self.commit(title, files)
self.git("switch", "-q", "main")
self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
return self.git("rev-parse", "--short", "HEAD").strip()
def fixes(self):
found = later_fixes("main", cwd=str(self.checkout))
self.assertNotIsInstance(found, Failure)
return {landed.label: landed.fixed_by for landed in found}
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_an_earlier_chunk_added(self):
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
fixed = self.chunk("six", ("Fix six", {"b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}))
found = self.fixes()
self.assertEqual(found[shipped], (fixed,))
self.assertEqual(found[fixed], ())
def test_counts_a_chunk_that_ships_a_security_item_as_a_fix(self):
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
fixed = self.chunk("seven", ("Close seven", {"b.py": "x\n", "todo.md": todo(5, 6, 8)}))
self.assertEqual(self.fixes()[shipped], (fixed,))
def test_counts_no_chunk_whose_shipped_items_are_neither_defect_nor_security(self):
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
self.chunk("five", ("Do five", {"b.py": "x\nY\n", "todo.md": todo(6, 7, 8)}))
self.assertEqual(self.fixes()[shipped], ())
def test_counts_no_chunk_that_only_edits_a_defect_items_row(self):
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
self.chunk("edit", ("Re-score six", {"b.py": "x\nY\n", "todo.md": todo(5, 6, 7, 8).replace("**Fix six.**", "**Fix six now.**")}))
self.assertEqual(self.fixes()[shipped], ())
def test_leaves_the_plans_row_out_so_a_fix_does_not_trace_to_the_chunk_that_filed_it(self):
filed = self.chunk("file", ("File item 9", {"c.py": "c\n", "todo.md": todo(4, 5, 6, 7, 8, 9)}))
self.chunk("nine", ("Fix nine", {"d.py": "d\n", "todo.md": todo(4, 5, 6, 7, 8)}))
self.assertEqual(self.fixes()[filed], ())
def test_counts_a_round_commit_that_answers_a_misread_red_finding_and_rewrites_an_earlier_chunks_line(self):
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
fixed = self.chunk("five", ("Do five", {"c.py": "c\n", "todo.md": todo(6, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); keep y's caller", {"b.py": "x\nY\n"}))
self.assertEqual(self.fixes()[shipped], (fixed,))
def test_counts_no_round_commit_without_both_a_red_and_a_misread_finding(self):
shipped = self.chunk("four", ("Do four", {"b.py": "w\nx\ny\n", "todo.md": todo(5, 6, 7, 8)}))
self.chunk("five", ("Do five", {"c.py": "c\n", "todo.md": todo(6, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (0 misread); fix", {"b.py": "W\nx\ny\n"}), ("Answer prose round 1: 0 🔴, 1 🟡 (1 misread); fix", {"b.py": "W\nX\ny\n"}), ("Answer principles round 1: 1 🔴, 0 🟡; fix", {"b.py": "W\nX\nY\n"}))
self.assertEqual(self.fixes()[shipped], ())
def test_counts_no_fix_of_lines_its_own_chunk_wrote(self):
self.chunk("six", ("Fix six", {"b.py": "x\ny\n", "todo.md": todo(4, 5, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); fix", {"b.py": "x\nY\n"}))
self.assertEqual(set(self.fixes().values()), {()})
def test_counts_a_fixing_chunk_once_against_each_chunk_it_fixes_newest_first(self):
first = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "d.py": "d\n", "todo.md": todo(5, 6, 7, 8)}))
second = self.chunk("five", ("Do five", {"c.py": "z\n", "todo.md": todo(6, 7, 8)}))
fixed = self.chunk("six", ("Fix six", {"b.py": "X\ny\n", "todo.md": todo(7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); fix", {"b.py": "X\nY\n", "c.py": "Z\n"}))
again = self.chunk("eight", ("Fix eight", {"b.py": "XX\nY\n", "d.py": "D\n", "todo.md": todo(7)}))
found = self.fixes()
self.assertEqual(found[first], (again, fixed))
self.assertEqual(found[second], (fixed,))
self.assertEqual(found[fixed], (again,))
def test_traces_a_line_to_the_rebased_run_that_added_it_and_labels_runs_as_score_outcomes_does(self):
first = self.commit("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}, at="2026-10-13T09:00:00Z")
last = self.commit("Answer stability round 1: 0 🔴, 0 🟡 (0 misread)", {"c.py": "c\n"}, at="2026-10-13T09:00:00Z")
fixed = self.commit("Fix six", {"b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}, at="2026-10-13T10:00:00Z")
self.assertEqual(self.fixes()[f"{first}^..{last}"], (fixed,))
def test_holds_each_chunks_commit_titles_and_landing_time(self):
self.git("switch", "-q", "-c", "four")
self.commit("Do four", {"b.py": "x\n", "todo.md": todo(5, 6, 7, 8)})
self.git("switch", "-q", "main")
self.env.update({"GIT_COMMITTER_DATE": "2026-10-14T10:00:00Z", "GIT_AUTHOR_DATE": "2026-10-14T10:00:00Z"})
self.git("merge", "-q", "--no-ff", "-m", "Merge four", "four")
merged = self.git("rev-parse", "--short", "HEAD").strip()
newest = later_fixes("main", cwd=str(self.checkout))[0]
self.assertEqual(newest, Landed(merged, "2026-10-14T10:00:00Z", frozenset({"Do four", "Merge four"}), ()))
def test_reads_paths_from_the_checkouts_top_when_run_in_a_folder_of_it(self):
(self.checkout / "sub").mkdir()
shipped = self.chunk("four", ("Do four", {"sub/b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
fixed = self.chunk("six", ("Fix six", {"sub/b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}))
found = later_fixes("main", cwd=str(self.checkout / "sub"))
self.assertNotIsInstance(found, Failure)
self.assertEqual({landed.label: landed.fixed_by for landed in found}[shipped], (fixed,))
def test_fails_where_git_cannot_read_the_branch(self):
self.assertIsInstance(later_fixes("missing", cwd=str(self.checkout)), Failure)
if __name__ == "__main__":
unittest.main()
+12 -51
View File
@@ -8,23 +8,23 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.anchors import anchor_lines, parse_anchors
from score_outcomes.results import chunk_log, Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
from branch_chunks.cut import BranchChunk, Landing
from failure import Failure
from round_titles import Findings
from test_env import isolated_env
from todo_table import Item
from score_outcomes.results import nearest, rank_correlation, render, report, Result, results_of
from score_outcomes.main import report_text
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 10 | 6 | 7 | 1 | 9.0 |"
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |"
def todo(*rows: str, header: str = HEADER) -> str:
return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows)
def todo(*rows: str) -> str:
return "# todo\n\n## Items\n\n" + HEADER + "".join(f"{row}\n" for row in rows)
def item(id_: int, scores: dict[str, int]) -> Item:
@@ -35,55 +35,16 @@ def result(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landed, fixed_by)
class Shipped(unittest.TestCase):
def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self):
self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4])
self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 10, "A": 6, "G": 7})
def test_lists_the_shipped_items_by_id(self):
self.assertEqual([found.id for found in shipped(todo(SECOND, FIRST), todo())], [4, 5])
def test_reads_a_table_from_before_c_joined_it(self):
older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |"
self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7})
def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self):
self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), [])
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
class ChunkLog(unittest.TestCase):
# Lines are `%h %ct %at %p`, newest first: short hash, commit time, author time, parents.
def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self):
self.assertEqual(chunk_log(["m 100 100 a b", "c 100 100 a"]), [("m", "m", 100, "merge"), ("c", "c", 100, "push")])
def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self):
self.assertEqual(chunk_log(["c2 200 150 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self):
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 200 r"]), [("c1", "c2", 200, "push")])
def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self):
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self):
self.assertEqual(chunk_log(["c2 200 100 c1", "c1 200 200 r"]), [("c1", "c2", 200, "rebase")])
def test_a_commit_at_another_time_starts_a_new_chunk(self):
self.assertEqual(chunk_log(["c2 300 300 c1", "c1 200 200 r"]), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
class ResultsOf(unittest.TestCase):
def test_measures_the_change_less_the_plan_and_the_tool_records_and_counts_binary_files(self):
numstat = "3\t1\ta.py\n-\t-\tlogo.png\n0\t1\t2026\n5\t0\ttodo.md\n9\t0\tdocs/reading-cost.md\n4\t0\tdocs/comprehension-history.md\n"
titles = ["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer stability round 2: 0 🔴, 1 🟡; fix", "Answer prose round 1: 0 🔴, 3 🟡", "Do it"]
found = results_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge", ("def5678",))
found = results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", tuple(titles), (item(4, {"R": 2}), item(5, {"R": 3})), ("def5678",)), numstat)
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge", ("def5678",)))
self.assertEqual(found[1].shipped_with, (4,))
def test_measures_no_chunk_that_changed_only_the_plan(self):
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge", ()), [])
self.assertEqual(results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", (), (item(4, {"R": 2}),), ()), "0\t5\ttodo.md\n"), [])
class Nearest(unittest.TestCase):
@@ -307,8 +268,8 @@ class ScoreOutcomesTool(unittest.TestCase):
self.env.pop(name, None)
return self.git("rev-parse", "--short", "HEAD").strip()
def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
def run_tool(self, *args, cwd=None):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True)
def test_measures_each_merged_chunk_that_removed_an_item(self):
self.git("switch", "-q", "-c", "chunk")
@@ -322,17 +283,17 @@ class ScoreOutcomesTool(unittest.TestCase):
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged ", ran.stdout)
self.assertNotIn("Item 5", ran.stdout)
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_a_chunk_shipped(self):
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_a_chunk_shipped_run_from_a_folder_below_the_top(self):
self.commit("File a fix", {"todo.md": todo(FIRST, SECOND, FIX)})
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND, FIX)})
self.commit("Do it", {"sub/a.py": "1\n2\n3\n", "todo.md": todo(SECOND, FIX)})
self.git("switch", "-q", "main")
shipped = self.merge_branch("chunk", "2026-10-13T10:00:00Z")
self.git("switch", "-q", "-c", "fix")
self.commit("Fix it", {"a.py": "1\n2\n4\n", "todo.md": todo(SECOND)})
self.commit("Fix it", {"sub/a.py": "1\n2\n4\n", "todo.md": todo(SECOND)})
self.git("switch", "-q", "main")
fixed = self.merge_branch("fix", "2026-10-14T10:00:00Z")
ran = self.run_tool("1", "2", "1", "3")
ran = self.run_tool("1", "2", "1", "3", cwd=self.checkout / "sub")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn(f"findings unknown, 1 later fix; merged 2026-10-13T10:00:00Z in {shipped}. **Do it.**", ran.stdout)
self.assertIn(f"- 2026-10-13T10:00:00Z in {shipped}: 1 later fix, by {fixed}\n- The other 1 finished chunk: none.", ran.stdout)